repo stringlengths 5 67 | path stringlengths 4 218 | func_name stringlengths 0 151 | original_string stringlengths 52 373k | language stringclasses 6 values | code stringlengths 52 373k | code_tokens listlengths 10 512 | docstring stringlengths 3 47.2k | docstring_tokens listlengths 3 234 | sha stringlengths 40 40 | url stringlengths 85 339 | partition stringclasses 3 values |
|---|---|---|---|---|---|---|---|---|---|---|---|
muffinista/chatterbot | lib/chatterbot/blocklist.rb | Chatterbot.Blocklist.skip_me? | def skip_me?(s)
search = s.respond_to?(:text) ? s.text : s
exclude.detect { |e| search.downcase.include?(e) } != nil
end | ruby | def skip_me?(s)
search = s.respond_to?(:text) ? s.text : s
exclude.detect { |e| search.downcase.include?(e) } != nil
end | [
"def",
"skip_me?",
"(",
"s",
")",
"search",
"=",
"s",
".",
"respond_to?",
"(",
":text",
")",
"?",
"s",
".",
"text",
":",
"s",
"exclude",
".",
"detect",
"{",
"|",
"e",
"|",
"search",
".",
"downcase",
".",
"include?",
"(",
"e",
")",
"}",
"!=",
"n... | Based on the text of this tweet, should it be skipped? | [
"Based",
"on",
"the",
"text",
"of",
"this",
"tweet",
"should",
"it",
"be",
"skipped?"
] | e98ebb4e23882a9aa078bc5f749a6d045c35e9be | https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/blocklist.rb#L26-L29 | valid |
muffinista/chatterbot | lib/chatterbot/blocklist.rb | Chatterbot.Blocklist.on_blocklist? | def on_blocklist?(s)
search = if s.is_a?(Twitter::User)
s.name
elsif s.respond_to?(:user) && !s.is_a?(Twitter::NullObject)
from_user(s)
else
s
end.downcase
blocklist.any? { |b| search.include?(b.downcase) }
end | ruby | def on_blocklist?(s)
search = if s.is_a?(Twitter::User)
s.name
elsif s.respond_to?(:user) && !s.is_a?(Twitter::NullObject)
from_user(s)
else
s
end.downcase
blocklist.any? { |b| search.include?(b.downcase) }
end | [
"def",
"on_blocklist?",
"(",
"s",
")",
"search",
"=",
"if",
"s",
".",
"is_a?",
"(",
"Twitter",
"::",
"User",
")",
"s",
".",
"name",
"elsif",
"s",
".",
"respond_to?",
"(",
":user",
")",
"&&",
"!",
"s",
".",
"is_a?",
"(",
"Twitter",
"::",
"NullObject... | Is this tweet from a user on our blocklist? | [
"Is",
"this",
"tweet",
"from",
"a",
"user",
"on",
"our",
"blocklist?"
] | e98ebb4e23882a9aa078bc5f749a6d045c35e9be | https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/blocklist.rb#L48-L58 | valid |
muffinista/chatterbot | lib/chatterbot/client.rb | Chatterbot.Client.reset_since_id | def reset_since_id
config[:since_id] = 1
# do a search of recent tweets with the letter 'a' in them to
# get a rough max tweet id
result = client.search("a", since:Time.now - 10).max_by(&:id)
update_since_id(result)
end | ruby | def reset_since_id
config[:since_id] = 1
# do a search of recent tweets with the letter 'a' in them to
# get a rough max tweet id
result = client.search("a", since:Time.now - 10).max_by(&:id)
update_since_id(result)
end | [
"def",
"reset_since_id",
"config",
"[",
":since_id",
"]",
"=",
"1",
"result",
"=",
"client",
".",
"search",
"(",
"\"a\"",
",",
"since",
":",
"Time",
".",
"now",
"-",
"10",
")",
".",
"max_by",
"(",
"&",
":id",
")",
"update_since_id",
"(",
"result",
")... | reset the since_id for this bot to the highest since_id we can
get, by running a really open search and updating config with
the max_id | [
"reset",
"the",
"since_id",
"for",
"this",
"bot",
"to",
"the",
"highest",
"since_id",
"we",
"can",
"get",
"by",
"running",
"a",
"really",
"open",
"search",
"and",
"updating",
"config",
"with",
"the",
"max_id"
] | e98ebb4e23882a9aa078bc5f749a6d045c35e9be | https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/client.rb#L47-L53 | valid |
muffinista/chatterbot | lib/chatterbot/client.rb | Chatterbot.Client.generate_authorize_url | def generate_authorize_url(request_token)
request = consumer.create_signed_request(:get,
consumer.authorize_path, request_token,
{:oauth_callback => 'oob'})
params = request['Authorization'].sub(/^OAuth\s+/, '').split(/,\s+/).map do |param|
key, value = param.split('=')
value =~ /"(.*?)"/
"#{key}=#{CGI::escape($1)}"
end.join('&')
"#{base_url}#{request.path}?#{params}"
end | ruby | def generate_authorize_url(request_token)
request = consumer.create_signed_request(:get,
consumer.authorize_path, request_token,
{:oauth_callback => 'oob'})
params = request['Authorization'].sub(/^OAuth\s+/, '').split(/,\s+/).map do |param|
key, value = param.split('=')
value =~ /"(.*?)"/
"#{key}=#{CGI::escape($1)}"
end.join('&')
"#{base_url}#{request.path}?#{params}"
end | [
"def",
"generate_authorize_url",
"(",
"request_token",
")",
"request",
"=",
"consumer",
".",
"create_signed_request",
"(",
":get",
",",
"consumer",
".",
"authorize_path",
",",
"request_token",
",",
"{",
":oauth_callback",
"=>",
"'oob'",
"}",
")",
"params",
"=",
... | copied from t, the awesome twitter cli app
@see https://github.com/sferik/t/blob/master/lib/t/authorizable.rb | [
"copied",
"from",
"t",
"the",
"awesome",
"twitter",
"cli",
"app"
] | e98ebb4e23882a9aa078bc5f749a6d045c35e9be | https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/client.rb#L143-L155 | valid |
muffinista/chatterbot | lib/chatterbot/client.rb | Chatterbot.Client.get_screen_name | def get_screen_name(t = @access_token)
return unless @screen_name.nil?
return if t.nil?
oauth_response = t.get('/1.1/account/verify_credentials.json')
@screen_name = JSON.parse(oauth_response.body)["screen_name"]
end | ruby | def get_screen_name(t = @access_token)
return unless @screen_name.nil?
return if t.nil?
oauth_response = t.get('/1.1/account/verify_credentials.json')
@screen_name = JSON.parse(oauth_response.body)["screen_name"]
end | [
"def",
"get_screen_name",
"(",
"t",
"=",
"@access_token",
")",
"return",
"unless",
"@screen_name",
".",
"nil?",
"return",
"if",
"t",
".",
"nil?",
"oauth_response",
"=",
"t",
".",
"get",
"(",
"'/1.1/account/verify_credentials.json'",
")",
"@screen_name",
"=",
"JS... | query twitter for the bots screen name. we do this during the bot registration process | [
"query",
"twitter",
"for",
"the",
"bots",
"screen",
"name",
".",
"we",
"do",
"this",
"during",
"the",
"bot",
"registration",
"process"
] | e98ebb4e23882a9aa078bc5f749a6d045c35e9be | https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/client.rb#L165-L171 | valid |
muffinista/chatterbot | lib/chatterbot/client.rb | Chatterbot.Client.login | def login(do_update_config=true)
if needs_api_key?
get_api_key
end
if needs_auth_token?
pin = get_oauth_verifier
return false if pin.nil?
begin
# this will throw an error that we can try and catch
@access_token = request_token.get_access_token(:oauth_verifier => pin.chomp)
get_screen_name
self.config[:access_token] = @access_token.token
self.config[:access_token_secret] = @access_token.secret
#update_config unless ! do_update_config
reset_client
rescue OAuth::Unauthorized => e
display_oauth_error
warn e.inspect
return false
end
end
return true
end | ruby | def login(do_update_config=true)
if needs_api_key?
get_api_key
end
if needs_auth_token?
pin = get_oauth_verifier
return false if pin.nil?
begin
# this will throw an error that we can try and catch
@access_token = request_token.get_access_token(:oauth_verifier => pin.chomp)
get_screen_name
self.config[:access_token] = @access_token.token
self.config[:access_token_secret] = @access_token.secret
#update_config unless ! do_update_config
reset_client
rescue OAuth::Unauthorized => e
display_oauth_error
warn e.inspect
return false
end
end
return true
end | [
"def",
"login",
"(",
"do_update_config",
"=",
"true",
")",
"if",
"needs_api_key?",
"get_api_key",
"end",
"if",
"needs_auth_token?",
"pin",
"=",
"get_oauth_verifier",
"return",
"false",
"if",
"pin",
".",
"nil?",
"begin",
"@access_token",
"=",
"request_token",
".",
... | handle oauth for this request. if the client isn't authorized, print
out the auth URL and get a pin code back from the user
If +do_update_config+ is false, don't udpate the bots config
file after authorization. This defaults to true but
chatterbot-register will pass in false because it does some
other work before saving. | [
"handle",
"oauth",
"for",
"this",
"request",
".",
"if",
"the",
"client",
"isn",
"t",
"authorized",
"print",
"out",
"the",
"auth",
"URL",
"and",
"get",
"a",
"pin",
"code",
"back",
"from",
"the",
"user",
"If",
"+",
"do_update_config",
"+",
"is",
"false",
... | e98ebb4e23882a9aa078bc5f749a6d045c35e9be | https://github.com/muffinista/chatterbot/blob/e98ebb4e23882a9aa078bc5f749a6d045c35e9be/lib/chatterbot/client.rb#L180-L209 | valid |
rx/presenters | lib/voom/container_methods.rb | Voom.ContainerMethods.reset! | def reset!
registered_keys.each { |key| ClassConstants.new(key).deconstantize }
@registered_keys = []
container._container.clear
end | ruby | def reset!
registered_keys.each { |key| ClassConstants.new(key).deconstantize }
@registered_keys = []
container._container.clear
end | [
"def",
"reset!",
"registered_keys",
".",
"each",
"{",
"|",
"key",
"|",
"ClassConstants",
".",
"new",
"(",
"key",
")",
".",
"deconstantize",
"}",
"@registered_keys",
"=",
"[",
"]",
"container",
".",
"_container",
".",
"clear",
"end"
] | This method empties out the container
It should ONLY be used for testing purposes | [
"This",
"method",
"empties",
"out",
"the",
"container",
"It",
"should",
"ONLY",
"be",
"used",
"for",
"testing",
"purposes"
] | 983c151df9d3e633dd772482149e831ab76e69fc | https://github.com/rx/presenters/blob/983c151df9d3e633dd772482149e831ab76e69fc/lib/voom/container_methods.rb#L35-L39 | valid |
rx/presenters | lib/voom/symbol/to_str.rb | Voom.Symbol.class_name | def class_name(classname)
classname = sym_to_str(classname)
classname.split('.').map { |m| inflector.camelize(m) }.join('::')
end | ruby | def class_name(classname)
classname = sym_to_str(classname)
classname.split('.').map { |m| inflector.camelize(m) }.join('::')
end | [
"def",
"class_name",
"(",
"classname",
")",
"classname",
"=",
"sym_to_str",
"(",
"classname",
")",
"classname",
".",
"split",
"(",
"'.'",
")",
".",
"map",
"{",
"|",
"m",
"|",
"inflector",
".",
"camelize",
"(",
"m",
")",
"}",
".",
"join",
"(",
"'::'",... | Converts a namespaced symbol or string to a proper class name with modules | [
"Converts",
"a",
"namespaced",
"symbol",
"or",
"string",
"to",
"a",
"proper",
"class",
"name",
"with",
"modules"
] | 983c151df9d3e633dd772482149e831ab76e69fc | https://github.com/rx/presenters/blob/983c151df9d3e633dd772482149e831ab76e69fc/lib/voom/symbol/to_str.rb#L19-L22 | valid |
javanthropus/archive-zip | lib/archive/support/zlib.rb | Zlib.ZWriter.close | def close
flush()
@deflate_buffer << @deflater.finish unless @deflater.finished?
begin
until @deflate_buffer.empty? do
@deflate_buffer.slice!(0, delegate.write(@deflate_buffer))
end
rescue Errno::EAGAIN, Errno::EINTR
retry if write_ready?
end
@checksum = @deflater.adler
@compressed_size = @deflater.total_out
@uncompressed_size = @deflater.total_in
@deflater.close
super()
nil
end | ruby | def close
flush()
@deflate_buffer << @deflater.finish unless @deflater.finished?
begin
until @deflate_buffer.empty? do
@deflate_buffer.slice!(0, delegate.write(@deflate_buffer))
end
rescue Errno::EAGAIN, Errno::EINTR
retry if write_ready?
end
@checksum = @deflater.adler
@compressed_size = @deflater.total_out
@uncompressed_size = @deflater.total_in
@deflater.close
super()
nil
end | [
"def",
"close",
"flush",
"(",
")",
"@deflate_buffer",
"<<",
"@deflater",
".",
"finish",
"unless",
"@deflater",
".",
"finished?",
"begin",
"until",
"@deflate_buffer",
".",
"empty?",
"do",
"@deflate_buffer",
".",
"slice!",
"(",
"0",
",",
"delegate",
".",
"write"... | Closes the writer by finishing the compressed data and flushing it to the
delegate.
Raises IOError if called more than once. | [
"Closes",
"the",
"writer",
"by",
"finishing",
"the",
"compressed",
"data",
"and",
"flushing",
"it",
"to",
"the",
"delegate",
"."
] | 8dfe4260da2fd74175d0cdf3a5277ed11e709f1a | https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/support/zlib.rb#L175-L191 | valid |
javanthropus/archive-zip | lib/archive/support/time.rb | Archive.DOSTime.to_time | def to_time
second = ((0b11111 & @dos_time) ) * 2
minute = ((0b111111 << 5 & @dos_time) >> 5)
hour = ((0b11111 << 11 & @dos_time) >> 11)
day = ((0b11111 << 16 & @dos_time) >> 16)
month = ((0b1111 << 21 & @dos_time) >> 21)
year = ((0b1111111 << 25 & @dos_time) >> 25) + 1980
return Time.local(year, month, day, hour, minute, second)
end | ruby | def to_time
second = ((0b11111 & @dos_time) ) * 2
minute = ((0b111111 << 5 & @dos_time) >> 5)
hour = ((0b11111 << 11 & @dos_time) >> 11)
day = ((0b11111 << 16 & @dos_time) >> 16)
month = ((0b1111 << 21 & @dos_time) >> 21)
year = ((0b1111111 << 25 & @dos_time) >> 25) + 1980
return Time.local(year, month, day, hour, minute, second)
end | [
"def",
"to_time",
"second",
"=",
"(",
"(",
"0b11111",
"&",
"@dos_time",
")",
")",
"*",
"2",
"minute",
"=",
"(",
"(",
"0b111111",
"<<",
"5",
"&",
"@dos_time",
")",
">>",
"5",
")",
"hour",
"=",
"(",
"(",
"0b11111",
"<<",
"11",
"&",
"@dos_time",
")"... | Returns a Time instance which is equivalent to the time represented by
this object. | [
"Returns",
"a",
"Time",
"instance",
"which",
"is",
"equivalent",
"to",
"the",
"time",
"represented",
"by",
"this",
"object",
"."
] | 8dfe4260da2fd74175d0cdf3a5277ed11e709f1a | https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/support/time.rb#L82-L90 | valid |
javanthropus/archive-zip | lib/archive/zip.rb | Archive.Zip.each | def each(&b)
raise IOError, 'non-readable archive' unless readable?
raise IOError, 'closed archive' if closed?
unless @parse_complete then
parse(@archive)
@parse_complete = true
end
@entries.each(&b)
end | ruby | def each(&b)
raise IOError, 'non-readable archive' unless readable?
raise IOError, 'closed archive' if closed?
unless @parse_complete then
parse(@archive)
@parse_complete = true
end
@entries.each(&b)
end | [
"def",
"each",
"(",
"&",
"b",
")",
"raise",
"IOError",
",",
"'non-readable archive'",
"unless",
"readable?",
"raise",
"IOError",
",",
"'closed archive'",
"if",
"closed?",
"unless",
"@parse_complete",
"then",
"parse",
"(",
"@archive",
")",
"@parse_complete",
"=",
... | Iterates through each entry of a readable ZIP archive in turn yielding
each one to the given block.
Raises Archive::Zip::IOError if called on a non-readable archive or after
the archive is closed. | [
"Iterates",
"through",
"each",
"entry",
"of",
"a",
"readable",
"ZIP",
"archive",
"in",
"turn",
"yielding",
"each",
"one",
"to",
"the",
"given",
"block",
"."
] | 8dfe4260da2fd74175d0cdf3a5277ed11e709f1a | https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/zip.rb#L205-L214 | valid |
javanthropus/archive-zip | lib/archive/zip.rb | Archive.Zip.add_entry | def add_entry(entry)
raise IOError, 'non-writable archive' unless writable?
raise IOError, 'closed archive' if closed?
unless entry.kind_of?(Entry) then
raise ArgumentError, 'Archive::Zip::Entry instance required'
end
@entries << entry
self
end | ruby | def add_entry(entry)
raise IOError, 'non-writable archive' unless writable?
raise IOError, 'closed archive' if closed?
unless entry.kind_of?(Entry) then
raise ArgumentError, 'Archive::Zip::Entry instance required'
end
@entries << entry
self
end | [
"def",
"add_entry",
"(",
"entry",
")",
"raise",
"IOError",
",",
"'non-writable archive'",
"unless",
"writable?",
"raise",
"IOError",
",",
"'closed archive'",
"if",
"closed?",
"unless",
"entry",
".",
"kind_of?",
"(",
"Entry",
")",
"then",
"raise",
"ArgumentError",
... | Adds _entry_ into a writable ZIP archive.
<b>NOTE:</b> No attempt is made to prevent adding multiple entries with
the same archive path.
Raises Archive::Zip::IOError if called on a non-writable archive or after
the archive is closed. | [
"Adds",
"_entry_",
"into",
"a",
"writable",
"ZIP",
"archive",
"."
] | 8dfe4260da2fd74175d0cdf3a5277ed11e709f1a | https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/zip.rb#L223-L232 | valid |
javanthropus/archive-zip | lib/archive/zip.rb | Archive.Zip.extract | def extract(destination, options = {})
raise IOError, 'non-readable archive' unless readable?
raise IOError, 'closed archive' if closed?
# Ensure that unspecified options have default values.
options[:directories] = true unless options.has_key?(:directories)
options[:symlinks] = false unless options.has_key?(:symlinks)
options[:overwrite] = :all unless options[:overwrite] == :older ||
options[:overwrite] == :never
options[:create] = true unless options.has_key?(:create)
options[:flatten] = false unless options.has_key?(:flatten)
# Flattening the archive structure implies that directory entries are
# skipped.
options[:directories] = false if options[:flatten]
# First extract all non-directory entries.
directories = []
each do |entry|
# Compute the target file path.
file_path = entry.zip_path
file_path = File.basename(file_path) if options[:flatten]
file_path = File.join(destination, file_path)
# Cache some information about the file path.
file_exists = File.exist?(file_path)
file_mtime = File.mtime(file_path) if file_exists
begin
# Skip this entry if so directed.
if (! file_exists && ! options[:create]) ||
(file_exists &&
(options[:overwrite] == :never ||
options[:overwrite] == :older && entry.mtime <= file_mtime)) ||
(! options[:exclude].nil? && options[:exclude][entry]) then
next
end
# Set the decryption key for the entry.
if options[:password].kind_of?(String) then
entry.password = options[:password]
elsif ! options[:password].nil? then
entry.password = options[:password][entry]
end
if entry.directory? then
# Record the directories as they are encountered.
directories << entry
elsif entry.file? || (entry.symlink? && options[:symlinks]) then
# Extract files and symlinks.
entry.extract(
options.merge(:file_path => file_path)
)
end
rescue StandardError => error
unless options[:on_error].nil? then
case options[:on_error][entry, error]
when :retry
retry
when :skip
else
raise
end
else
raise
end
end
end
if options[:directories] then
# Then extract the directory entries in depth first order so that time
# stamps, ownerships, and permissions can be properly restored.
directories.sort { |a, b| b.zip_path <=> a.zip_path }.each do |entry|
begin
entry.extract(
options.merge(
:file_path => File.join(destination, entry.zip_path)
)
)
rescue StandardError => error
unless options[:on_error].nil? then
case options[:on_error][entry, error]
when :retry
retry
when :skip
else
raise
end
else
raise
end
end
end
end
nil
end | ruby | def extract(destination, options = {})
raise IOError, 'non-readable archive' unless readable?
raise IOError, 'closed archive' if closed?
# Ensure that unspecified options have default values.
options[:directories] = true unless options.has_key?(:directories)
options[:symlinks] = false unless options.has_key?(:symlinks)
options[:overwrite] = :all unless options[:overwrite] == :older ||
options[:overwrite] == :never
options[:create] = true unless options.has_key?(:create)
options[:flatten] = false unless options.has_key?(:flatten)
# Flattening the archive structure implies that directory entries are
# skipped.
options[:directories] = false if options[:flatten]
# First extract all non-directory entries.
directories = []
each do |entry|
# Compute the target file path.
file_path = entry.zip_path
file_path = File.basename(file_path) if options[:flatten]
file_path = File.join(destination, file_path)
# Cache some information about the file path.
file_exists = File.exist?(file_path)
file_mtime = File.mtime(file_path) if file_exists
begin
# Skip this entry if so directed.
if (! file_exists && ! options[:create]) ||
(file_exists &&
(options[:overwrite] == :never ||
options[:overwrite] == :older && entry.mtime <= file_mtime)) ||
(! options[:exclude].nil? && options[:exclude][entry]) then
next
end
# Set the decryption key for the entry.
if options[:password].kind_of?(String) then
entry.password = options[:password]
elsif ! options[:password].nil? then
entry.password = options[:password][entry]
end
if entry.directory? then
# Record the directories as they are encountered.
directories << entry
elsif entry.file? || (entry.symlink? && options[:symlinks]) then
# Extract files and symlinks.
entry.extract(
options.merge(:file_path => file_path)
)
end
rescue StandardError => error
unless options[:on_error].nil? then
case options[:on_error][entry, error]
when :retry
retry
when :skip
else
raise
end
else
raise
end
end
end
if options[:directories] then
# Then extract the directory entries in depth first order so that time
# stamps, ownerships, and permissions can be properly restored.
directories.sort { |a, b| b.zip_path <=> a.zip_path }.each do |entry|
begin
entry.extract(
options.merge(
:file_path => File.join(destination, entry.zip_path)
)
)
rescue StandardError => error
unless options[:on_error].nil? then
case options[:on_error][entry, error]
when :retry
retry
when :skip
else
raise
end
else
raise
end
end
end
end
nil
end | [
"def",
"extract",
"(",
"destination",
",",
"options",
"=",
"{",
"}",
")",
"raise",
"IOError",
",",
"'non-readable archive'",
"unless",
"readable?",
"raise",
"IOError",
",",
"'closed archive'",
"if",
"closed?",
"options",
"[",
":directories",
"]",
"=",
"true",
... | Extracts the contents of the archive to _destination_, where _destination_
is a path to a directory which will contain the contents of the archive.
The destination path will be created if it does not already exist.
_options_ is a Hash optionally containing the following:
<b>:directories</b>::
When set to +true+ (the default), entries representing directories in
the archive are extracted. This happens after all non-directory entries
are extracted so that directory metadata can be properly updated.
<b>:symlinks</b>::
When set to +false+ (the default), entries representing symlinks in the
archive are skipped. When set to +true+, such entries are extracted.
Exceptions may be raised on plaforms/file systems which do not support
symlinks.
<b>:overwrite</b>::
When set to <tt>:all</tt> (the default), files which already exist will
be replaced. When set to <tt>:older</tt>, such files will only be
replaced if they are older according to their last modified times than
the zip entry which would replace them. When set to <tt>:none</tt>,
such files will never be replaced. Any other value is the same as
<tt>:all</tt>.
<b>:create</b>::
When set to +true+ (the default), files and directories which do not
already exist will be extracted. When set to +false+, only files and
directories which already exist will be extracted (depending on the
setting of <b>:overwrite</b>).
<b>:flatten</b>::
When set to +false+ (the default), the directory paths containing
extracted files will be created within +destination+ in order to contain
the files. When set to +true+, files are extracted directly to
+destination+ and directory entries are skipped.
<b>:exclude</b>::
Specifies a proc or lambda which takes a single argument containing a
zip entry and returns +true+ if the entry should be skipped during
extraction and +false+ if it should be extracted.
<b>:password</b>::
Specifies a proc, lambda, or a String. If a proc or lambda is used, it
must take a single argument containing a zip entry and return a String
to be used as a decryption key for the entry. If a String is used, it
will be used as a decryption key for all encrypted entries.
<b>:on_error</b>::
Specifies a proc or lambda which is called when an exception is raised
during the extraction of an entry. It takes two arguments, a zip entry
and an exception object generated while attempting to extract the entry.
If <tt>:retry</tt> is returned, extraction of the entry is attempted
again. If <tt>:skip</tt> is returned, the entry is skipped. Otherwise,
the exception is raised.
Any other options which are supported by Archive::Zip::Entry#extract are
also supported.
Raises Archive::Zip::IOError if called on a non-readable archive or after
the archive is closed.
== Example
An archive, <tt>archive.zip</tt>, contains:
zip-test/
zip-test/dir1/
zip-test/dir1/file2.txt
zip-test/dir2/
zip-test/file1.txt
A directory, <tt>extract4</tt>, contains:
zip-test
+- dir1
+- file1.txt
Extract the archive:
Archive::Zip.open('archive.zip') do |z|
z.extract('extract1')
end
Archive::Zip.open('archive.zip') do |z|
z.extract('extract2', :flatten => true)
end
Archive::Zip.open('archive.zip') do |z|
z.extract('extract3', :create => false)
end
Archive::Zip.open('archive.zip') do |z|
z.extract('extract3', :create => true)
end
Archive::Zip.open('archive.zip') do |z|
z.extract( 'extract5', :exclude => lambda { |e| e.file? })
end
The directories contain:
extract1 -> zip-test
+- dir1
| +- file2.txt
+- dir2
+- file1.txt
extract2 -> file2.txt
file1.txt
extract3 -> <empty>
extract4 -> zip-test
+- dir2
+- file1.txt <- from archive contents
extract5 -> zip-test
+- dir1
+- dir2 | [
"Extracts",
"the",
"contents",
"of",
"the",
"archive",
"to",
"_destination_",
"where",
"_destination_",
"is",
"a",
"path",
"to",
"a",
"directory",
"which",
"will",
"contain",
"the",
"contents",
"of",
"the",
"archive",
".",
"The",
"destination",
"path",
"will",... | 8dfe4260da2fd74175d0cdf3a5277ed11e709f1a | https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/zip.rb#L558-L654 | valid |
javanthropus/archive-zip | lib/archive/zip.rb | Archive.Zip.find_central_directory | def find_central_directory(io)
# First find the offset to the end of central directory record.
# It is expected that the variable length comment field will usually be
# empty and as a result the initial value of eocd_offset is all that is
# necessary.
#
# NOTE: A cleverly crafted comment could throw this thing off if the
# comment itself looks like a valid end of central directory record.
eocd_offset = -22
loop do
io.seek(eocd_offset, IO::SEEK_END)
if IOExtensions.read_exactly(io, 4) == EOCD_SIGNATURE then
io.seek(16, IO::SEEK_CUR)
if IOExtensions.read_exactly(io, 2).unpack('v')[0] ==
(eocd_offset + 22).abs then
break
end
end
eocd_offset -= 1
end
# At this point, eocd_offset should point to the location of the end of
# central directory record relative to the end of the archive.
# Now, jump into the location in the record which contains a pointer to
# the start of the central directory record and return the value.
io.seek(eocd_offset + 16, IO::SEEK_END)
return IOExtensions.read_exactly(io, 4).unpack('V')[0]
rescue Errno::EINVAL
raise Zip::UnzipError, 'unable to locate end-of-central-directory record'
end | ruby | def find_central_directory(io)
# First find the offset to the end of central directory record.
# It is expected that the variable length comment field will usually be
# empty and as a result the initial value of eocd_offset is all that is
# necessary.
#
# NOTE: A cleverly crafted comment could throw this thing off if the
# comment itself looks like a valid end of central directory record.
eocd_offset = -22
loop do
io.seek(eocd_offset, IO::SEEK_END)
if IOExtensions.read_exactly(io, 4) == EOCD_SIGNATURE then
io.seek(16, IO::SEEK_CUR)
if IOExtensions.read_exactly(io, 2).unpack('v')[0] ==
(eocd_offset + 22).abs then
break
end
end
eocd_offset -= 1
end
# At this point, eocd_offset should point to the location of the end of
# central directory record relative to the end of the archive.
# Now, jump into the location in the record which contains a pointer to
# the start of the central directory record and return the value.
io.seek(eocd_offset + 16, IO::SEEK_END)
return IOExtensions.read_exactly(io, 4).unpack('V')[0]
rescue Errno::EINVAL
raise Zip::UnzipError, 'unable to locate end-of-central-directory record'
end | [
"def",
"find_central_directory",
"(",
"io",
")",
"eocd_offset",
"=",
"-",
"22",
"loop",
"do",
"io",
".",
"seek",
"(",
"eocd_offset",
",",
"IO",
"::",
"SEEK_END",
")",
"if",
"IOExtensions",
".",
"read_exactly",
"(",
"io",
",",
"4",
")",
"==",
"EOCD_SIGNAT... | Returns the file offset of the first record in the central directory.
_io_ must be a seekable, readable, IO-like object.
Raises Archive::Zip::UnzipError if the end of central directory signature
is not found where expected or at all. | [
"Returns",
"the",
"file",
"offset",
"of",
"the",
"first",
"record",
"in",
"the",
"central",
"directory",
".",
"_io_",
"must",
"be",
"a",
"seekable",
"readable",
"IO",
"-",
"like",
"object",
"."
] | 8dfe4260da2fd74175d0cdf3a5277ed11e709f1a | https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/zip.rb#L678-L706 | valid |
javanthropus/archive-zip | lib/archive/zip.rb | Archive.Zip.dump | def dump(io)
bytes_written = 0
@entries.each do |entry|
bytes_written += entry.dump_local_file_record(io, bytes_written)
end
central_directory_offset = bytes_written
@entries.each do |entry|
bytes_written += entry.dump_central_file_record(io)
end
central_directory_length = bytes_written - central_directory_offset
bytes_written += io.write(EOCD_SIGNATURE)
bytes_written += io.write(
[
0,
0,
@entries.length,
@entries.length,
central_directory_length,
central_directory_offset,
comment.bytesize
].pack('vvvvVVv')
)
bytes_written += io.write(comment)
bytes_written
end | ruby | def dump(io)
bytes_written = 0
@entries.each do |entry|
bytes_written += entry.dump_local_file_record(io, bytes_written)
end
central_directory_offset = bytes_written
@entries.each do |entry|
bytes_written += entry.dump_central_file_record(io)
end
central_directory_length = bytes_written - central_directory_offset
bytes_written += io.write(EOCD_SIGNATURE)
bytes_written += io.write(
[
0,
0,
@entries.length,
@entries.length,
central_directory_length,
central_directory_offset,
comment.bytesize
].pack('vvvvVVv')
)
bytes_written += io.write(comment)
bytes_written
end | [
"def",
"dump",
"(",
"io",
")",
"bytes_written",
"=",
"0",
"@entries",
".",
"each",
"do",
"|",
"entry",
"|",
"bytes_written",
"+=",
"entry",
".",
"dump_local_file_record",
"(",
"io",
",",
"bytes_written",
")",
"end",
"central_directory_offset",
"=",
"bytes_writ... | Writes all the entries of this archive to _io_. _io_ must be a writable,
IO-like object providing a _write_ method. Returns the total number of
bytes written. | [
"Writes",
"all",
"the",
"entries",
"of",
"this",
"archive",
"to",
"_io_",
".",
"_io_",
"must",
"be",
"a",
"writable",
"IO",
"-",
"like",
"object",
"providing",
"a",
"_write_",
"method",
".",
"Returns",
"the",
"total",
"number",
"of",
"bytes",
"written",
... | 8dfe4260da2fd74175d0cdf3a5277ed11e709f1a | https://github.com/javanthropus/archive-zip/blob/8dfe4260da2fd74175d0cdf3a5277ed11e709f1a/lib/archive/zip.rb#L711-L736 | valid |
code-and-effect/effective_datatables | app/models/effective/datatable.rb | Effective.Datatable.view= | def view=(view)
@view = (view.respond_to?(:view_context) ? view.view_context : view)
raise 'expected view to respond to params' unless @view.respond_to?(:params)
load_cookie!
assert_cookie!
load_attributes!
# We need early access to filter and scope, to define defaults from the model first
# This means filters do knows about attributes but not about columns.
initialize_filters if respond_to?(:initialize_filters)
load_filters!
load_state!
# Bulk actions called first so it can add the bulk_actions_col first
initialize_bulk_actions if respond_to?(:initialize_bulk_actions)
# Now we initialize all the columns. columns knows about attributes and filters and scope
initialize_datatable if respond_to?(:initialize_datatable)
load_columns!
# Execute any additional DSL methods
initialize_charts if respond_to?(:initialize_charts)
# Load the collection. This is the first time def collection is called on the Datatable itself
initialize_collection if respond_to?(:initialize_collection)
load_collection!
# Figure out the class, and if it's activerecord, do all the resource discovery on it
load_resource!
apply_belongs_to_attributes!
load_resource_search!
# Check everything is okay
validate_datatable!
# Save for next time
save_cookie!
end | ruby | def view=(view)
@view = (view.respond_to?(:view_context) ? view.view_context : view)
raise 'expected view to respond to params' unless @view.respond_to?(:params)
load_cookie!
assert_cookie!
load_attributes!
# We need early access to filter and scope, to define defaults from the model first
# This means filters do knows about attributes but not about columns.
initialize_filters if respond_to?(:initialize_filters)
load_filters!
load_state!
# Bulk actions called first so it can add the bulk_actions_col first
initialize_bulk_actions if respond_to?(:initialize_bulk_actions)
# Now we initialize all the columns. columns knows about attributes and filters and scope
initialize_datatable if respond_to?(:initialize_datatable)
load_columns!
# Execute any additional DSL methods
initialize_charts if respond_to?(:initialize_charts)
# Load the collection. This is the first time def collection is called on the Datatable itself
initialize_collection if respond_to?(:initialize_collection)
load_collection!
# Figure out the class, and if it's activerecord, do all the resource discovery on it
load_resource!
apply_belongs_to_attributes!
load_resource_search!
# Check everything is okay
validate_datatable!
# Save for next time
save_cookie!
end | [
"def",
"view",
"=",
"(",
"view",
")",
"@view",
"=",
"(",
"view",
".",
"respond_to?",
"(",
":view_context",
")",
"?",
"view",
".",
"view_context",
":",
"view",
")",
"raise",
"'expected view to respond to params'",
"unless",
"@view",
".",
"respond_to?",
"(",
"... | Once the view is assigned, we initialize everything | [
"Once",
"the",
"view",
"is",
"assigned",
"we",
"initialize",
"everything"
] | fed6c03fe583b8ccb937d15377dc5aac666a5151 | https://github.com/code-and-effect/effective_datatables/blob/fed6c03fe583b8ccb937d15377dc5aac666a5151/app/models/effective/datatable.rb#L53-L91 | valid |
code-and-effect/effective_datatables | app/controllers/effective/datatables_controller.rb | Effective.DatatablesController.show | def show
begin
@datatable = EffectiveDatatables.find(params[:id])
@datatable.view = view_context
EffectiveDatatables.authorize!(self, :index, @datatable.collection_class)
render json: @datatable.to_json
rescue => e
EffectiveDatatables.authorized?(self, :index, @datatable.try(:collection_class))
render json: error_json(e)
ExceptionNotifier.notify_exception(e) if defined?(ExceptionNotifier)
raise e if Rails.env.development?
end
end | ruby | def show
begin
@datatable = EffectiveDatatables.find(params[:id])
@datatable.view = view_context
EffectiveDatatables.authorize!(self, :index, @datatable.collection_class)
render json: @datatable.to_json
rescue => e
EffectiveDatatables.authorized?(self, :index, @datatable.try(:collection_class))
render json: error_json(e)
ExceptionNotifier.notify_exception(e) if defined?(ExceptionNotifier)
raise e if Rails.env.development?
end
end | [
"def",
"show",
"begin",
"@datatable",
"=",
"EffectiveDatatables",
".",
"find",
"(",
"params",
"[",
":id",
"]",
")",
"@datatable",
".",
"view",
"=",
"view_context",
"EffectiveDatatables",
".",
"authorize!",
"(",
"self",
",",
":index",
",",
"@datatable",
".",
... | This will respond to both a GET and a POST | [
"This",
"will",
"respond",
"to",
"both",
"a",
"GET",
"and",
"a",
"POST"
] | fed6c03fe583b8ccb937d15377dc5aac666a5151 | https://github.com/code-and-effect/effective_datatables/blob/fed6c03fe583b8ccb937d15377dc5aac666a5151/app/controllers/effective/datatables_controller.rb#L6-L21 | valid |
boazsegev/plezi | lib/plezi/render/render.rb | Plezi.Renderer.register | def register(extention, handler = nil, &block)
handler ||= block
raise 'Handler or block required.' unless handler
@render_library[extention.to_s] = handler
handler
end | ruby | def register(extention, handler = nil, &block)
handler ||= block
raise 'Handler or block required.' unless handler
@render_library[extention.to_s] = handler
handler
end | [
"def",
"register",
"(",
"extention",
",",
"handler",
"=",
"nil",
",",
"&",
"block",
")",
"handler",
"||=",
"block",
"raise",
"'Handler or block required.'",
"unless",
"handler",
"@render_library",
"[",
"extention",
".",
"to_s",
"]",
"=",
"handler",
"handler",
... | Registers a rendering extention.
Slim, Markdown, ERB and SASS are registered by default.
extention:: a Symbol or String representing the extention of the file to be rendered. i.e. 'slim', 'md', 'erb', etc'
handler :: a Proc or other object that answers to call(filename, context, &block) and returnes the rendered string.
The block accepted by the handler is for chaining rendered actions (allowing for `yield` within templates)
and the context is the object within which the rendering should be performed (if `binding` handling is
supported by the engine). `filename` might not point to an existing or valid file.
If a block is passed to the `register_hook` method with no handler defined, it will act as the handler. | [
"Registers",
"a",
"rendering",
"extention",
"."
] | 8f6b1a4e7874746267751cfaa71db7ad3851993a | https://github.com/boazsegev/plezi/blob/8f6b1a4e7874746267751cfaa71db7ad3851993a/lib/plezi/render/render.rb#L20-L25 | valid |
boazsegev/plezi | lib/plezi/controller/controller.rb | Plezi.Controller.requested_method | def requested_method
params['_method'.freeze] = (params['_method'.freeze] || request.request_method.downcase).to_sym
self.class._pl_params2method(params, request.env)
end | ruby | def requested_method
params['_method'.freeze] = (params['_method'.freeze] || request.request_method.downcase).to_sym
self.class._pl_params2method(params, request.env)
end | [
"def",
"requested_method",
"params",
"[",
"'_method'",
".",
"freeze",
"]",
"=",
"(",
"params",
"[",
"'_method'",
".",
"freeze",
"]",
"||",
"request",
".",
"request_method",
".",
"downcase",
")",
".",
"to_sym",
"self",
".",
"class",
".",
"_pl_params2method",
... | Returns the method that was called by the HTTP request.
It's possible to override this method to change the default Controller behavior.
For Websocket connections this method is most likely to return :preform_upgrade | [
"Returns",
"the",
"method",
"that",
"was",
"called",
"by",
"the",
"HTTP",
"request",
"."
] | 8f6b1a4e7874746267751cfaa71db7ad3851993a | https://github.com/boazsegev/plezi/blob/8f6b1a4e7874746267751cfaa71db7ad3851993a/lib/plezi/controller/controller.rb#L64-L67 | valid |
boazsegev/plezi | lib/plezi/controller/controller.rb | Plezi.Controller.send_data | def send_data(data, options = {})
response.write data if data
filename = options[:filename]
# set headers
content_disposition = options[:inline] ? 'inline'.dup : 'attachment'.dup
content_disposition << "; filename=#{::File.basename(options[:filename])}" if filename
cont_type = (options[:mime] ||= filename && Rack::Mime.mime_type(::File.extname(filename)))
response['content-type'.freeze] = cont_type if cont_type
response['content-disposition'.freeze] = content_disposition
true
end | ruby | def send_data(data, options = {})
response.write data if data
filename = options[:filename]
# set headers
content_disposition = options[:inline] ? 'inline'.dup : 'attachment'.dup
content_disposition << "; filename=#{::File.basename(options[:filename])}" if filename
cont_type = (options[:mime] ||= filename && Rack::Mime.mime_type(::File.extname(filename)))
response['content-type'.freeze] = cont_type if cont_type
response['content-disposition'.freeze] = content_disposition
true
end | [
"def",
"send_data",
"(",
"data",
",",
"options",
"=",
"{",
"}",
")",
"response",
".",
"write",
"data",
"if",
"data",
"filename",
"=",
"options",
"[",
":filename",
"]",
"content_disposition",
"=",
"options",
"[",
":inline",
"]",
"?",
"'inline'",
".",
"dup... | Sends a block of data, setting a file name, mime type and content disposition headers when possible. This should also be a good choice when sending large amounts of data.
By default, `send_data` sends the data as an attachment, unless `inline: true` was set.
If a mime type is provided, it will be used to set the Content-Type header. i.e. `mime: "text/plain"`
If a file name was provided, Rack will be used to find the correct mime type (unless provided). i.e. `filename: "sample.pdf"` will set the mime type to `application/pdf`
Available options: `:inline` (`true` / `false`), `:filename`, `:mime`. | [
"Sends",
"a",
"block",
"of",
"data",
"setting",
"a",
"file",
"name",
"mime",
"type",
"and",
"content",
"disposition",
"headers",
"when",
"possible",
".",
"This",
"should",
"also",
"be",
"a",
"good",
"choice",
"when",
"sending",
"large",
"amounts",
"of",
"d... | 8f6b1a4e7874746267751cfaa71db7ad3851993a | https://github.com/boazsegev/plezi/blob/8f6b1a4e7874746267751cfaa71db7ad3851993a/lib/plezi/controller/controller.rb#L97-L107 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/graph.rb | InventoryRefresh.Graph.build_feedback_edge_set | def build_feedback_edge_set(edges, fixed_edges)
edges = edges.dup
acyclic_edges = fixed_edges.dup
feedback_edge_set = []
while edges.present?
edge = edges.shift
if detect_cycle(edge, acyclic_edges)
feedback_edge_set << edge
else
acyclic_edges << edge
end
end
feedback_edge_set
end | ruby | def build_feedback_edge_set(edges, fixed_edges)
edges = edges.dup
acyclic_edges = fixed_edges.dup
feedback_edge_set = []
while edges.present?
edge = edges.shift
if detect_cycle(edge, acyclic_edges)
feedback_edge_set << edge
else
acyclic_edges << edge
end
end
feedback_edge_set
end | [
"def",
"build_feedback_edge_set",
"(",
"edges",
",",
"fixed_edges",
")",
"edges",
"=",
"edges",
".",
"dup",
"acyclic_edges",
"=",
"fixed_edges",
".",
"dup",
"feedback_edge_set",
"=",
"[",
"]",
"while",
"edges",
".",
"present?",
"edge",
"=",
"edges",
".",
"sh... | Builds a feedback edge set, which is a set of edges creating a cycle
@param edges [Array<Array>] List of edges, where edge is defined as [InventoryCollection, InventoryCollection],
these are all edges except fixed_edges
@param fixed_edges [Array<Array>] List of edges, where edge is defined as [InventoryCollection, InventoryCollection],
fixed edges are those that can't be moved | [
"Builds",
"a",
"feedback",
"edge",
"set",
"which",
"is",
"a",
"set",
"of",
"edges",
"creating",
"a",
"cycle"
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/graph.rb#L73-L88 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/graph.rb | InventoryRefresh.Graph.detect_cycle | def detect_cycle(edge, acyclic_edges, escalation = nil)
# Test if adding edge creates a cycle, ew will traverse the graph from edge Node, through all it's
# dependencies
starting_node = edge.second
edges = [edge] + acyclic_edges
traverse_dependecies([], starting_node, starting_node, edges, node_edges(edges, starting_node), escalation)
end | ruby | def detect_cycle(edge, acyclic_edges, escalation = nil)
# Test if adding edge creates a cycle, ew will traverse the graph from edge Node, through all it's
# dependencies
starting_node = edge.second
edges = [edge] + acyclic_edges
traverse_dependecies([], starting_node, starting_node, edges, node_edges(edges, starting_node), escalation)
end | [
"def",
"detect_cycle",
"(",
"edge",
",",
"acyclic_edges",
",",
"escalation",
"=",
"nil",
")",
"starting_node",
"=",
"edge",
".",
"second",
"edges",
"=",
"[",
"edge",
"]",
"+",
"acyclic_edges",
"traverse_dependecies",
"(",
"[",
"]",
",",
"starting_node",
",",... | Detects a cycle. Based on escalation returns true or raises exception if there is a cycle
@param edge [Array(InventoryRefresh::InventoryCollection, InventoryRefresh::InventoryCollection)] Edge we are
inspecting for cycle
@param acyclic_edges [Array<Array>] Starting with fixed edges that can't have cycle, these are edges without cycle
@param escalation [Symbol] If :exception, this method throws exception when it finds a cycle
@return [Boolean, Exception] Based on escalation returns true or raises exception if there is a cycle | [
"Detects",
"a",
"cycle",
".",
"Based",
"on",
"escalation",
"returns",
"true",
"or",
"raises",
"exception",
"if",
"there",
"is",
"a",
"cycle"
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/graph.rb#L97-L103 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/graph.rb | InventoryRefresh.Graph.traverse_dependecies | def traverse_dependecies(traversed_nodes, starting_node, current_node, edges, dependencies, escalation)
dependencies.each do |node_edge|
node = node_edge.first
traversed_nodes << node
if traversed_nodes.include?(starting_node)
if escalation == :exception
raise "Cycle from #{current_node} to #{node}, starting from #{starting_node} passing #{traversed_nodes}"
else
return true
end
end
return true if traverse_dependecies(traversed_nodes, starting_node, node, edges, node_edges(edges, node), escalation)
end
false
end | ruby | def traverse_dependecies(traversed_nodes, starting_node, current_node, edges, dependencies, escalation)
dependencies.each do |node_edge|
node = node_edge.first
traversed_nodes << node
if traversed_nodes.include?(starting_node)
if escalation == :exception
raise "Cycle from #{current_node} to #{node}, starting from #{starting_node} passing #{traversed_nodes}"
else
return true
end
end
return true if traverse_dependecies(traversed_nodes, starting_node, node, edges, node_edges(edges, node), escalation)
end
false
end | [
"def",
"traverse_dependecies",
"(",
"traversed_nodes",
",",
"starting_node",
",",
"current_node",
",",
"edges",
",",
"dependencies",
",",
"escalation",
")",
"dependencies",
".",
"each",
"do",
"|",
"node_edge",
"|",
"node",
"=",
"node_edge",
".",
"first",
"traver... | Recursive method for traversing dependencies and finding a cycle
@param traversed_nodes [Array<InventoryRefresh::InventoryCollection> Already traversed nodes
@param starting_node [InventoryRefresh::InventoryCollection] Node we've started the traversal on
@param current_node [InventoryRefresh::InventoryCollection] Node we are currently on
@param edges [Array<Array>] All graph edges
@param dependencies [Array<InventoryRefresh::InventoryCollection> Dependencies of the current node
@param escalation [Symbol] If :exception, this method throws exception when it finds a cycle
@return [Boolean, Exception] Based on escalation returns true or raises exception if there is a cycle | [
"Recursive",
"method",
"for",
"traversing",
"dependencies",
"and",
"finding",
"a",
"cycle"
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/graph.rb#L114-L129 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/application_record_iterator.rb | InventoryRefresh.ApplicationRecordIterator.find_in_batches | def find_in_batches(batch_size: 1000, attributes_index: {})
attributes_index.each_slice(batch_size) do |batch|
yield(inventory_collection.db_collection_for_comparison_for(batch))
end
end | ruby | def find_in_batches(batch_size: 1000, attributes_index: {})
attributes_index.each_slice(batch_size) do |batch|
yield(inventory_collection.db_collection_for_comparison_for(batch))
end
end | [
"def",
"find_in_batches",
"(",
"batch_size",
":",
"1000",
",",
"attributes_index",
":",
"{",
"}",
")",
"attributes_index",
".",
"each_slice",
"(",
"batch_size",
")",
"do",
"|",
"batch",
"|",
"yield",
"(",
"inventory_collection",
".",
"db_collection_for_comparison_... | An iterator that can fetch batches of the AR objects based on a set of attribute_indexes
@param inventory_collection [InventoryRefresh::InventoryCollection] Inventory collection owning the iterator
Iterator that mimics find_in_batches of ActiveRecord::Relation. This iterator serves for making more optimized query
since e.g. having 1500 ids if objects we want to return. Doing relation.where(:id => 1500ids).find_each would
always search for all 1500 ids, then return on limit 1000.
With this iterator we build queries using only batch of ids, so find_each will cause relation.where(:id => 1000ids)
and relation.where(:id => 500ids)
@param batch_size [Integer] A batch size we want to fetch from DB
@param attributes_index [Hash{String => Hash}] Indexed hash with data we will be saving
@yield Code processing the batches | [
"An",
"iterator",
"that",
"can",
"fetch",
"batches",
"of",
"the",
"AR",
"objects",
"based",
"on",
"a",
"set",
"of",
"attribute_indexes"
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/application_record_iterator.rb#L22-L26 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/inventory_object.rb | InventoryRefresh.InventoryObject.assign_attributes | def assign_attributes(attributes)
attributes.each do |k, v|
# We don't want timestamps or resource versions to be overwritten here, since those are driving the conditions
next if %i(resource_timestamps resource_timestamps_max resource_timestamp).include?(k)
next if %i(resource_counters resource_counters_max resource_counter).include?(k)
if data[:resource_timestamp] && attributes[:resource_timestamp]
assign_only_newest(:resource_timestamp, :resource_timestamps, attributes, data, k, v)
elsif data[:resource_counter] && attributes[:resource_counter]
assign_only_newest(:resource_counter, :resource_counters, attributes, data, k, v)
else
public_send("#{k}=", v)
end
end
if attributes[:resource_timestamp]
assign_full_row_version_attr(:resource_timestamp, attributes, data)
elsif attributes[:resource_counter]
assign_full_row_version_attr(:resource_counter, attributes, data)
end
self
end | ruby | def assign_attributes(attributes)
attributes.each do |k, v|
# We don't want timestamps or resource versions to be overwritten here, since those are driving the conditions
next if %i(resource_timestamps resource_timestamps_max resource_timestamp).include?(k)
next if %i(resource_counters resource_counters_max resource_counter).include?(k)
if data[:resource_timestamp] && attributes[:resource_timestamp]
assign_only_newest(:resource_timestamp, :resource_timestamps, attributes, data, k, v)
elsif data[:resource_counter] && attributes[:resource_counter]
assign_only_newest(:resource_counter, :resource_counters, attributes, data, k, v)
else
public_send("#{k}=", v)
end
end
if attributes[:resource_timestamp]
assign_full_row_version_attr(:resource_timestamp, attributes, data)
elsif attributes[:resource_counter]
assign_full_row_version_attr(:resource_counter, attributes, data)
end
self
end | [
"def",
"assign_attributes",
"(",
"attributes",
")",
"attributes",
".",
"each",
"do",
"|",
"k",
",",
"v",
"|",
"next",
"if",
"%i(",
"resource_timestamps",
"resource_timestamps_max",
"resource_timestamp",
")",
".",
"include?",
"(",
"k",
")",
"next",
"if",
"%i(",... | Given hash of attributes, we assign them to InventoryObject object using its public writers
@param attributes [Hash] attributes we want to assign
@return [InventoryRefresh::InventoryObject] self | [
"Given",
"hash",
"of",
"attributes",
"we",
"assign",
"them",
"to",
"InventoryObject",
"object",
"using",
"its",
"public",
"writers"
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_object.rb#L96-L118 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/inventory_object.rb | InventoryRefresh.InventoryObject.assign_only_newest | def assign_only_newest(full_row_version_attr, partial_row_version_attr, attributes, data, k, v)
# If timestamps are in play, we will set only attributes that are newer
specific_attr_timestamp = attributes[partial_row_version_attr].try(:[], k)
specific_data_timestamp = data[partial_row_version_attr].try(:[], k)
assign = if !specific_attr_timestamp
# Data have no timestamp, we will ignore the check
true
elsif specific_attr_timestamp && !specific_data_timestamp
# Data specific timestamp is nil and we have new specific timestamp
if data.key?(k)
if attributes[full_row_version_attr] >= data[full_row_version_attr]
# We can save if the full timestamp is bigger, if the data already contains the attribute
true
end
else
# Data do not contain the attribute, so we are saving the newest
true
end
true
elsif specific_attr_timestamp > specific_data_timestamp
# both partial timestamps are there, newer must be bigger
true
end
if assign
public_send("#{k}=", v) # Attribute is newer than current one, lets use it
(data[partial_row_version_attr] ||= {})[k] = specific_attr_timestamp if specific_attr_timestamp # and set the latest timestamp
end
end | ruby | def assign_only_newest(full_row_version_attr, partial_row_version_attr, attributes, data, k, v)
# If timestamps are in play, we will set only attributes that are newer
specific_attr_timestamp = attributes[partial_row_version_attr].try(:[], k)
specific_data_timestamp = data[partial_row_version_attr].try(:[], k)
assign = if !specific_attr_timestamp
# Data have no timestamp, we will ignore the check
true
elsif specific_attr_timestamp && !specific_data_timestamp
# Data specific timestamp is nil and we have new specific timestamp
if data.key?(k)
if attributes[full_row_version_attr] >= data[full_row_version_attr]
# We can save if the full timestamp is bigger, if the data already contains the attribute
true
end
else
# Data do not contain the attribute, so we are saving the newest
true
end
true
elsif specific_attr_timestamp > specific_data_timestamp
# both partial timestamps are there, newer must be bigger
true
end
if assign
public_send("#{k}=", v) # Attribute is newer than current one, lets use it
(data[partial_row_version_attr] ||= {})[k] = specific_attr_timestamp if specific_attr_timestamp # and set the latest timestamp
end
end | [
"def",
"assign_only_newest",
"(",
"full_row_version_attr",
",",
"partial_row_version_attr",
",",
"attributes",
",",
"data",
",",
"k",
",",
"v",
")",
"specific_attr_timestamp",
"=",
"attributes",
"[",
"partial_row_version_attr",
"]",
".",
"try",
"(",
":[]",
",",
"k... | Assigns value based on the version attributes. If versions are specified, it asigns attribute only if it's
newer than existing attribute.
@param full_row_version_attr [Symbol] Attr name for full rows, allowed values are
[:resource_timestamp, :resource_counter]
@param partial_row_version_attr [Symbol] Attr name for partial rows, allowed values are
[:resource_timestamps, :resource_counters]
@param attributes [Hash] New attributes we are assigning
@param data [Hash] Existing attributes of the InventoryObject
@param k [Symbol] Name of the attribute we are assigning
@param v [Object] Value of the attribute we are assigning | [
"Assigns",
"value",
"based",
"on",
"the",
"version",
"attributes",
".",
"If",
"versions",
"are",
"specified",
"it",
"asigns",
"attribute",
"only",
"if",
"it",
"s",
"newer",
"than",
"existing",
"attribute",
"."
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_object.rb#L200-L229 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/inventory_object.rb | InventoryRefresh.InventoryObject.assign_full_row_version_attr | def assign_full_row_version_attr(full_row_version_attr, attributes, data)
if attributes[full_row_version_attr] && data[full_row_version_attr]
# If both timestamps are present, store the bigger one
data[full_row_version_attr] = attributes[full_row_version_attr] if attributes[full_row_version_attr] > data[full_row_version_attr]
elsif attributes[full_row_version_attr] && !data[full_row_version_attr]
# We are assigning timestamp that was missing
data[full_row_version_attr] = attributes[full_row_version_attr]
end
end | ruby | def assign_full_row_version_attr(full_row_version_attr, attributes, data)
if attributes[full_row_version_attr] && data[full_row_version_attr]
# If both timestamps are present, store the bigger one
data[full_row_version_attr] = attributes[full_row_version_attr] if attributes[full_row_version_attr] > data[full_row_version_attr]
elsif attributes[full_row_version_attr] && !data[full_row_version_attr]
# We are assigning timestamp that was missing
data[full_row_version_attr] = attributes[full_row_version_attr]
end
end | [
"def",
"assign_full_row_version_attr",
"(",
"full_row_version_attr",
",",
"attributes",
",",
"data",
")",
"if",
"attributes",
"[",
"full_row_version_attr",
"]",
"&&",
"data",
"[",
"full_row_version_attr",
"]",
"data",
"[",
"full_row_version_attr",
"]",
"=",
"attribute... | Assigns attribute representing version of the whole row
@param full_row_version_attr [Symbol] Attr name for full rows, allowed values are
[:resource_timestamp, :resource_counter]
@param attributes [Hash] New attributes we are assigning
@param data [Hash] Existing attributes of the InventoryObject | [
"Assigns",
"attribute",
"representing",
"version",
"of",
"the",
"whole",
"row"
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_object.rb#L237-L245 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/inventory_collection.rb | InventoryRefresh.InventoryCollection.uniq_keys_candidates | def uniq_keys_candidates(keys)
# Find all uniq indexes that that are covering our keys
uniq_key_candidates = unique_indexes.each_with_object([]) { |i, obj| obj << i if (keys - i.columns.map(&:to_sym)).empty? }
if unique_indexes.blank? || uniq_key_candidates.blank?
raise "#{self} and its table #{model_class.table_name} must have a unique index defined "\
"covering columns #{keys} to be able to use saver_strategy :concurrent_safe_batch."
end
uniq_key_candidates
end | ruby | def uniq_keys_candidates(keys)
# Find all uniq indexes that that are covering our keys
uniq_key_candidates = unique_indexes.each_with_object([]) { |i, obj| obj << i if (keys - i.columns.map(&:to_sym)).empty? }
if unique_indexes.blank? || uniq_key_candidates.blank?
raise "#{self} and its table #{model_class.table_name} must have a unique index defined "\
"covering columns #{keys} to be able to use saver_strategy :concurrent_safe_batch."
end
uniq_key_candidates
end | [
"def",
"uniq_keys_candidates",
"(",
"keys",
")",
"uniq_key_candidates",
"=",
"unique_indexes",
".",
"each_with_object",
"(",
"[",
"]",
")",
"{",
"|",
"i",
",",
"obj",
"|",
"obj",
"<<",
"i",
"if",
"(",
"keys",
"-",
"i",
".",
"columns",
".",
"map",
"(",
... | Find candidates for unique key. Candidate must cover all columns we are passing as keys.
@param keys [Array<Symbol>]
@raise [Exception] if the unique index for the columns was not found
@return [Array<ActiveRecord::ConnectionAdapters::IndexDefinition>] Array of unique indexes fitting the keys | [
"Find",
"candidates",
"for",
"unique",
"key",
".",
"Candidate",
"must",
"cover",
"all",
"columns",
"we",
"are",
"passing",
"as",
"keys",
"."
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L236-L246 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/inventory_collection.rb | InventoryRefresh.InventoryCollection.filtered_dependency_attributes | def filtered_dependency_attributes
filtered_attributes = dependency_attributes
if attributes_blacklist.present?
filtered_attributes = filtered_attributes.reject { |key, _value| attributes_blacklist.include?(key) }
end
if attributes_whitelist.present?
filtered_attributes = filtered_attributes.select { |key, _value| attributes_whitelist.include?(key) }
end
filtered_attributes
end | ruby | def filtered_dependency_attributes
filtered_attributes = dependency_attributes
if attributes_blacklist.present?
filtered_attributes = filtered_attributes.reject { |key, _value| attributes_blacklist.include?(key) }
end
if attributes_whitelist.present?
filtered_attributes = filtered_attributes.select { |key, _value| attributes_whitelist.include?(key) }
end
filtered_attributes
end | [
"def",
"filtered_dependency_attributes",
"filtered_attributes",
"=",
"dependency_attributes",
"if",
"attributes_blacklist",
".",
"present?",
"filtered_attributes",
"=",
"filtered_attributes",
".",
"reject",
"{",
"|",
"key",
",",
"_value",
"|",
"attributes_blacklist",
".",
... | List attributes causing a dependency and filters them by attributes_blacklist and attributes_whitelist
@return [Hash{Symbol => Set}] attributes causing a dependency and filtered by blacklist and whitelist | [
"List",
"attributes",
"causing",
"a",
"dependency",
"and",
"filters",
"them",
"by",
"attributes_blacklist",
"and",
"attributes_whitelist"
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L326-L338 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/inventory_collection.rb | InventoryRefresh.InventoryCollection.fixed_attributes | def fixed_attributes
if model_class
presence_validators = model_class.validators.detect { |x| x.kind_of?(ActiveRecord::Validations::PresenceValidator) }
end
# Attributes that has to be always on the entity, so attributes making unique index of the record + attributes
# that have presence validation
fixed_attributes = manager_ref
fixed_attributes += presence_validators.attributes if presence_validators.present?
fixed_attributes
end | ruby | def fixed_attributes
if model_class
presence_validators = model_class.validators.detect { |x| x.kind_of?(ActiveRecord::Validations::PresenceValidator) }
end
# Attributes that has to be always on the entity, so attributes making unique index of the record + attributes
# that have presence validation
fixed_attributes = manager_ref
fixed_attributes += presence_validators.attributes if presence_validators.present?
fixed_attributes
end | [
"def",
"fixed_attributes",
"if",
"model_class",
"presence_validators",
"=",
"model_class",
".",
"validators",
".",
"detect",
"{",
"|",
"x",
"|",
"x",
".",
"kind_of?",
"(",
"ActiveRecord",
"::",
"Validations",
"::",
"PresenceValidator",
")",
"}",
"end",
"fixed_at... | Attributes that are needed to be able to save the record, i.e. attributes that are part of the unique index
and attributes with presence validation or NOT NULL constraint
@return [Array<Symbol>] attributes that are needed for saving of the record | [
"Attributes",
"that",
"are",
"needed",
"to",
"be",
"able",
"to",
"save",
"the",
"record",
"i",
".",
"e",
".",
"attributes",
"that",
"are",
"part",
"of",
"the",
"unique",
"index",
"and",
"attributes",
"with",
"presence",
"validation",
"or",
"NOT",
"NULL",
... | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L344-L353 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/inventory_collection.rb | InventoryRefresh.InventoryCollection.fixed_dependencies | def fixed_dependencies
fixed_attrs = fixed_attributes
filtered_dependency_attributes.each_with_object(Set.new) do |(key, value), fixed_deps|
fixed_deps.merge(value) if fixed_attrs.include?(key)
end.reject(&:saved?)
end | ruby | def fixed_dependencies
fixed_attrs = fixed_attributes
filtered_dependency_attributes.each_with_object(Set.new) do |(key, value), fixed_deps|
fixed_deps.merge(value) if fixed_attrs.include?(key)
end.reject(&:saved?)
end | [
"def",
"fixed_dependencies",
"fixed_attrs",
"=",
"fixed_attributes",
"filtered_dependency_attributes",
".",
"each_with_object",
"(",
"Set",
".",
"new",
")",
"do",
"|",
"(",
"key",
",",
"value",
")",
",",
"fixed_deps",
"|",
"fixed_deps",
".",
"merge",
"(",
"value... | Returns fixed dependencies, which are the ones we can't move, because we wouldn't be able to save the data
@returns [Set<InventoryRefresh::InventoryCollection>] all unique non saved fixed dependencies | [
"Returns",
"fixed",
"dependencies",
"which",
"are",
"the",
"ones",
"we",
"can",
"t",
"move",
"because",
"we",
"wouldn",
"t",
"be",
"able",
"to",
"save",
"the",
"data"
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L358-L364 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/inventory_collection.rb | InventoryRefresh.InventoryCollection.dependency_attributes_for | def dependency_attributes_for(inventory_collections)
attributes = Set.new
inventory_collections.each do |inventory_collection|
attributes += filtered_dependency_attributes.select { |_key, value| value.include?(inventory_collection) }.keys
end
attributes
end | ruby | def dependency_attributes_for(inventory_collections)
attributes = Set.new
inventory_collections.each do |inventory_collection|
attributes += filtered_dependency_attributes.select { |_key, value| value.include?(inventory_collection) }.keys
end
attributes
end | [
"def",
"dependency_attributes_for",
"(",
"inventory_collections",
")",
"attributes",
"=",
"Set",
".",
"new",
"inventory_collections",
".",
"each",
"do",
"|",
"inventory_collection",
"|",
"attributes",
"+=",
"filtered_dependency_attributes",
".",
"select",
"{",
"|",
"_... | Returns what attributes are causing a dependencies to certain InventoryCollection objects.
@param inventory_collections [Array<InventoryRefresh::InventoryCollection>]
@return [Array<InventoryRefresh::InventoryCollection>] attributes causing the dependencies to certain
InventoryCollection objects | [
"Returns",
"what",
"attributes",
"are",
"causing",
"a",
"dependencies",
"to",
"certain",
"InventoryCollection",
"objects",
"."
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L376-L382 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/inventory_collection.rb | InventoryRefresh.InventoryCollection.records_identities | def records_identities(records)
records = [records] unless records.respond_to?(:map)
records.map { |record| record_identity(record) }
end | ruby | def records_identities(records)
records = [records] unless records.respond_to?(:map)
records.map { |record| record_identity(record) }
end | [
"def",
"records_identities",
"(",
"records",
")",
"records",
"=",
"[",
"records",
"]",
"unless",
"records",
".",
"respond_to?",
"(",
":map",
")",
"records",
".",
"map",
"{",
"|",
"record",
"|",
"record_identity",
"(",
"record",
")",
"}",
"end"
] | Returns array of records identities
@param records [Array<ApplicationRecord>, Array[Hash]] list of stored records
@return [Array<Hash>] array of records identities | [
"Returns",
"array",
"of",
"records",
"identities"
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L553-L556 | valid |
ManageIQ/inventory_refresh | lib/inventory_refresh/inventory_collection.rb | InventoryRefresh.InventoryCollection.record_identity | def record_identity(record)
identity = record.try(:[], :id) || record.try(:[], "id") || record.try(:id)
raise "Cannot obtain identity of the #{record}" if identity.blank?
{
:id => identity
}
end | ruby | def record_identity(record)
identity = record.try(:[], :id) || record.try(:[], "id") || record.try(:id)
raise "Cannot obtain identity of the #{record}" if identity.blank?
{
:id => identity
}
end | [
"def",
"record_identity",
"(",
"record",
")",
"identity",
"=",
"record",
".",
"try",
"(",
":[]",
",",
":id",
")",
"||",
"record",
".",
"try",
"(",
":[]",
",",
"\"id\"",
")",
"||",
"record",
".",
"try",
"(",
":id",
")",
"raise",
"\"Cannot obtain identit... | Returns a hash with a simple record identity
@param record [ApplicationRecord, Hash] list of stored records
@return [Hash{Symbol => Bigint}] record identity | [
"Returns",
"a",
"hash",
"with",
"a",
"simple",
"record",
"identity"
] | 8367841fd967a8294385d57f4b20891ff9b0958f | https://github.com/ManageIQ/inventory_refresh/blob/8367841fd967a8294385d57f4b20891ff9b0958f/lib/inventory_refresh/inventory_collection.rb#L562-L568 | valid |
artofhuman/activeadmin_settings_cached | lib/activeadmin_settings_cached/dsl.rb | ActiveadminSettingsCached.DSL.active_admin_settings_page | def active_admin_settings_page(options = {}, &block)
options.assert_valid_keys(*ActiveadminSettingsCached::Options::VALID_OPTIONS)
options = ActiveadminSettingsCached::Options.options_for(options)
coercion =
ActiveadminSettingsCached::Coercions.new(options[:template_object].defaults, options[:template_object].display)
content title: options[:title] do
render partial: options[:template], locals: { settings_model: options[:template_object] }
end
page_action :update, method: :post do
settings_params = params.require(:settings).permit!
coercion.cast_params(settings_params) do |name, value|
options[:template_object].save(name, value)
end
flash[:success] = t('activeadmin_settings_cached.settings.update.success'.freeze)
Rails.version.to_i >= 5 ? redirect_back(fallback_location: admin_root_path) : redirect_to(:back)
options[:after_save].call if options[:after_save].respond_to?(:call)
end
instance_eval(&block) if block_given?
end | ruby | def active_admin_settings_page(options = {}, &block)
options.assert_valid_keys(*ActiveadminSettingsCached::Options::VALID_OPTIONS)
options = ActiveadminSettingsCached::Options.options_for(options)
coercion =
ActiveadminSettingsCached::Coercions.new(options[:template_object].defaults, options[:template_object].display)
content title: options[:title] do
render partial: options[:template], locals: { settings_model: options[:template_object] }
end
page_action :update, method: :post do
settings_params = params.require(:settings).permit!
coercion.cast_params(settings_params) do |name, value|
options[:template_object].save(name, value)
end
flash[:success] = t('activeadmin_settings_cached.settings.update.success'.freeze)
Rails.version.to_i >= 5 ? redirect_back(fallback_location: admin_root_path) : redirect_to(:back)
options[:after_save].call if options[:after_save].respond_to?(:call)
end
instance_eval(&block) if block_given?
end | [
"def",
"active_admin_settings_page",
"(",
"options",
"=",
"{",
"}",
",",
"&",
"block",
")",
"options",
".",
"assert_valid_keys",
"(",
"*",
"ActiveadminSettingsCached",
"::",
"Options",
"::",
"VALID_OPTIONS",
")",
"options",
"=",
"ActiveadminSettingsCached",
"::",
... | Declares settings function.
@api public
@param [Hash] options
@option options [String] :model_name, settings model name override (default: uses name from global config.)
@option options [String] :starting_with, each key must starting with, (default: nil)
@option options [String] :key, root key can be replacement for starting_with, (default: nil)
@option options [String] :template custom, template rendering (default: 'admin/settings/index')
@option options [String] :template_object, object to use in templates (default: ActiveadminSettingsCached::Model instance)
@option options [String] :display, display settings override (default: nil)
@option options [String] :title, title value override (default: I18n.t('settings.menu.label'))
@option options [Proc] :after_save, callback for action after page update, (default: nil) | [
"Declares",
"settings",
"function",
"."
] | 00c4131e5afd12af657cac0f68a4d62c223d3850 | https://github.com/artofhuman/activeadmin_settings_cached/blob/00c4131e5afd12af657cac0f68a4d62c223d3850/lib/activeadmin_settings_cached/dsl.rb#L18-L42 | valid |
pzol/monadic | lib/monadic/either.rb | Monadic.Either.or | def or(value=nil, &block)
return Failure(block.call(@value)) if failure? && block_given?
return Failure(value) if failure?
return self
end | ruby | def or(value=nil, &block)
return Failure(block.call(@value)) if failure? && block_given?
return Failure(value) if failure?
return self
end | [
"def",
"or",
"(",
"value",
"=",
"nil",
",",
"&",
"block",
")",
"return",
"Failure",
"(",
"block",
".",
"call",
"(",
"@value",
")",
")",
"if",
"failure?",
"&&",
"block_given?",
"return",
"Failure",
"(",
"value",
")",
"if",
"failure?",
"return",
"self",
... | If it is a Failure it will return a new Failure with the provided value
@return [Success, Failure] | [
"If",
"it",
"is",
"a",
"Failure",
"it",
"will",
"return",
"a",
"new",
"Failure",
"with",
"the",
"provided",
"value"
] | 50669c95f93013df6576c86e32ea9aeffd8a548e | https://github.com/pzol/monadic/blob/50669c95f93013df6576c86e32ea9aeffd8a548e/lib/monadic/either.rb#L39-L43 | valid |
SciRuby/rubex | lib/rubex/code_writer.rb | Rubex.CodeWriter.write_func_declaration | def write_func_declaration type:, c_name:, args: [], static: true
write_func_prototype type, c_name, args, static: static
@code << ";"
new_line
end | ruby | def write_func_declaration type:, c_name:, args: [], static: true
write_func_prototype type, c_name, args, static: static
@code << ";"
new_line
end | [
"def",
"write_func_declaration",
"type",
":",
",",
"c_name",
":",
",",
"args",
":",
"[",
"]",
",",
"static",
":",
"true",
"write_func_prototype",
"type",
",",
"c_name",
",",
"args",
",",
"static",
":",
"static",
"@code",
"<<",
"\";\"",
"new_line",
"end"
] | type - Return type of the method.
c_name - C Name.
args - Array of Arrays containing data type and variable name. | [
"type",
"-",
"Return",
"type",
"of",
"the",
"method",
".",
"c_name",
"-",
"C",
"Name",
".",
"args",
"-",
"Array",
"of",
"Arrays",
"containing",
"data",
"type",
"and",
"variable",
"name",
"."
] | bf5ee9365e1b93ae58c97827c1a6ef6c04cb5f33 | https://github.com/SciRuby/rubex/blob/bf5ee9365e1b93ae58c97827c1a6ef6c04cb5f33/lib/rubex/code_writer.rb#L32-L36 | valid |
piotrmurach/benchmark-trend | lib/benchmark/trend.rb | Benchmark.Trend.range | def range(start, limit, ratio: 8)
check_greater(start, 0)
check_greater(limit, start)
check_greater(ratio, 2)
items = []
count = start
items << count
(limit / ratio).times do
count *= ratio
break if count >= limit
items << count
end
items << limit if start != limit
items
end | ruby | def range(start, limit, ratio: 8)
check_greater(start, 0)
check_greater(limit, start)
check_greater(ratio, 2)
items = []
count = start
items << count
(limit / ratio).times do
count *= ratio
break if count >= limit
items << count
end
items << limit if start != limit
items
end | [
"def",
"range",
"(",
"start",
",",
"limit",
",",
"ratio",
":",
"8",
")",
"check_greater",
"(",
"start",
",",
"0",
")",
"check_greater",
"(",
"limit",
",",
"start",
")",
"check_greater",
"(",
"ratio",
",",
"2",
")",
"items",
"=",
"[",
"]",
"count",
... | Generate a range of inputs spaced by powers.
The default range is generated in the multiples of 8.
@example
Benchmark::Trend.range(8, 8 << 10)
# => [8, 64, 512, 4096, 8192]
@param [Integer] start
@param [Integer] limit
@param [Integer] ratio
@api public | [
"Generate",
"a",
"range",
"of",
"inputs",
"spaced",
"by",
"powers",
"."
] | 7f565cb6a09667b4e7cf7d7741b5a604076b447e | https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L55-L70 | valid |
piotrmurach/benchmark-trend | lib/benchmark/trend.rb | Benchmark.Trend.measure_execution_time | def measure_execution_time(data = nil, repeat: 1, &work)
inputs = data || range(1, 10_000)
times = []
inputs.each_with_index do |input, i|
GC.start
measurements = []
repeat.times do
measurements << clock_time { work.(input, i) }
end
times << measurements.reduce(&:+).to_f / measurements.size
end
[inputs, times]
end | ruby | def measure_execution_time(data = nil, repeat: 1, &work)
inputs = data || range(1, 10_000)
times = []
inputs.each_with_index do |input, i|
GC.start
measurements = []
repeat.times do
measurements << clock_time { work.(input, i) }
end
times << measurements.reduce(&:+).to_f / measurements.size
end
[inputs, times]
end | [
"def",
"measure_execution_time",
"(",
"data",
"=",
"nil",
",",
"repeat",
":",
"1",
",",
"&",
"work",
")",
"inputs",
"=",
"data",
"||",
"range",
"(",
"1",
",",
"10_000",
")",
"times",
"=",
"[",
"]",
"inputs",
".",
"each_with_index",
"do",
"|",
"input"... | Gather times for each input against an algorithm
@param [Array[Numeric]] data
the data to run measurements for
@param [Integer] repeat
nubmer of times work is called to compute execution time
@return [Array[Array, Array]]
@api public | [
"Gather",
"times",
"for",
"each",
"input",
"against",
"an",
"algorithm"
] | 7f565cb6a09667b4e7cf7d7741b5a604076b447e | https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L100-L115 | valid |
piotrmurach/benchmark-trend | lib/benchmark/trend.rb | Benchmark.Trend.fit_logarithmic | def fit_logarithmic(xs, ys)
fit(xs, ys, tran_x: ->(x) { Math.log(x) })
end | ruby | def fit_logarithmic(xs, ys)
fit(xs, ys, tran_x: ->(x) { Math.log(x) })
end | [
"def",
"fit_logarithmic",
"(",
"xs",
",",
"ys",
")",
"fit",
"(",
"xs",
",",
"ys",
",",
"tran_x",
":",
"->",
"(",
"x",
")",
"{",
"Math",
".",
"log",
"(",
"x",
")",
"}",
")",
"end"
] | Find a line of best fit that approximates logarithmic function
Model form: y = a*lnx + b
@param [Array[Numeric]] xs
the data points along X axis
@param [Array[Numeric]] ys
the data points along Y axis
@return [Numeric, Numeric, Numeric]
returns a, b, and rr values
@api public | [
"Find",
"a",
"line",
"of",
"best",
"fit",
"that",
"approximates",
"logarithmic",
"function"
] | 7f565cb6a09667b4e7cf7d7741b5a604076b447e | https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L151-L153 | valid |
piotrmurach/benchmark-trend | lib/benchmark/trend.rb | Benchmark.Trend.fit_power | def fit_power(xs, ys)
a, b, rr = fit(xs, ys, tran_x: ->(x) { Math.log(x) },
tran_y: ->(y) { Math.log(y) })
[a, Math.exp(b), rr]
end | ruby | def fit_power(xs, ys)
a, b, rr = fit(xs, ys, tran_x: ->(x) { Math.log(x) },
tran_y: ->(y) { Math.log(y) })
[a, Math.exp(b), rr]
end | [
"def",
"fit_power",
"(",
"xs",
",",
"ys",
")",
"a",
",",
"b",
",",
"rr",
"=",
"fit",
"(",
"xs",
",",
"ys",
",",
"tran_x",
":",
"->",
"(",
"x",
")",
"{",
"Math",
".",
"log",
"(",
"x",
")",
"}",
",",
"tran_y",
":",
"->",
"(",
"y",
")",
"{... | Finds a line of best fit that approxmimates power function
Function form: y = bx^a
@return [Numeric, Numeric, Numeric]
returns a, b, and rr values
@api public | [
"Finds",
"a",
"line",
"of",
"best",
"fit",
"that",
"approxmimates",
"power",
"function"
] | 7f565cb6a09667b4e7cf7d7741b5a604076b447e | https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L167-L172 | valid |
piotrmurach/benchmark-trend | lib/benchmark/trend.rb | Benchmark.Trend.fit_exponential | def fit_exponential(xs, ys)
a, b, rr = fit(xs, ys, tran_y: ->(y) { Math.log(y) })
[Math.exp(a), Math.exp(b), rr]
end | ruby | def fit_exponential(xs, ys)
a, b, rr = fit(xs, ys, tran_y: ->(y) { Math.log(y) })
[Math.exp(a), Math.exp(b), rr]
end | [
"def",
"fit_exponential",
"(",
"xs",
",",
"ys",
")",
"a",
",",
"b",
",",
"rr",
"=",
"fit",
"(",
"xs",
",",
"ys",
",",
"tran_y",
":",
"->",
"(",
"y",
")",
"{",
"Math",
".",
"log",
"(",
"y",
")",
"}",
")",
"[",
"Math",
".",
"exp",
"(",
"a",... | Find a line of best fit that approximates exponential function
Model form: y = ab^x
@return [Numeric, Numeric, Numeric]
returns a, b, and rr values
@api public | [
"Find",
"a",
"line",
"of",
"best",
"fit",
"that",
"approximates",
"exponential",
"function"
] | 7f565cb6a09667b4e7cf7d7741b5a604076b447e | https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L183-L187 | valid |
piotrmurach/benchmark-trend | lib/benchmark/trend.rb | Benchmark.Trend.fit | def fit(xs, ys, tran_x: ->(x) { x }, tran_y: ->(y) { y })
eps = (10 ** -10)
n = 0
sum_x = 0.0
sum_x2 = 0.0
sum_y = 0.0
sum_y2 = 0.0
sum_xy = 0.0
xs.zip(ys).each do |x, y|
n += 1
sum_x += tran_x.(x)
sum_y += tran_y.(y)
sum_x2 += tran_x.(x) ** 2
sum_y2 += tran_y.(y) ** 2
sum_xy += tran_x.(x) * tran_y.(y)
end
txy = n * sum_xy - sum_x * sum_y
tx = n * sum_x2 - sum_x ** 2
ty = n * sum_y2 - sum_y ** 2
is_linear = tran_x.(Math::E) * tran_y.(Math::E) == Math::E ** 2
if tx.abs < eps # no variation in xs
raise ArgumentError, "No variation in data #{xs}"
elsif ty.abs < eps && is_linear # no variation in ys - constant fit
slope = 0
intercept = sum_y / n
residual_sq = 1 # doesn't exist
else
slope = txy / tx
intercept = (sum_y - slope * sum_x) / n
residual_sq = (txy ** 2) / (tx * ty)
end
[slope, intercept, residual_sq]
end | ruby | def fit(xs, ys, tran_x: ->(x) { x }, tran_y: ->(y) { y })
eps = (10 ** -10)
n = 0
sum_x = 0.0
sum_x2 = 0.0
sum_y = 0.0
sum_y2 = 0.0
sum_xy = 0.0
xs.zip(ys).each do |x, y|
n += 1
sum_x += tran_x.(x)
sum_y += tran_y.(y)
sum_x2 += tran_x.(x) ** 2
sum_y2 += tran_y.(y) ** 2
sum_xy += tran_x.(x) * tran_y.(y)
end
txy = n * sum_xy - sum_x * sum_y
tx = n * sum_x2 - sum_x ** 2
ty = n * sum_y2 - sum_y ** 2
is_linear = tran_x.(Math::E) * tran_y.(Math::E) == Math::E ** 2
if tx.abs < eps # no variation in xs
raise ArgumentError, "No variation in data #{xs}"
elsif ty.abs < eps && is_linear # no variation in ys - constant fit
slope = 0
intercept = sum_y / n
residual_sq = 1 # doesn't exist
else
slope = txy / tx
intercept = (sum_y - slope * sum_x) / n
residual_sq = (txy ** 2) / (tx * ty)
end
[slope, intercept, residual_sq]
end | [
"def",
"fit",
"(",
"xs",
",",
"ys",
",",
"tran_x",
":",
"->",
"(",
"x",
")",
"{",
"x",
"}",
",",
"tran_y",
":",
"->",
"(",
"y",
")",
"{",
"y",
"}",
")",
"eps",
"=",
"(",
"10",
"**",
"-",
"10",
")",
"n",
"=",
"0",
"sum_x",
"=",
"0.0",
... | Fit the performance measurements to construct a model with
slope and intercept parameters that minimize the error.
@param [Array[Numeric]] xs
the data points along X axis
@param [Array[Numeric]] ys
the data points along Y axis
@return [Array[Numeric, Numeric, Numeric]
returns slope, intercept and model's goodness-of-fit
@api public | [
"Fit",
"the",
"performance",
"measurements",
"to",
"construct",
"a",
"model",
"with",
"slope",
"and",
"intercept",
"parameters",
"that",
"minimize",
"the",
"error",
"."
] | 7f565cb6a09667b4e7cf7d7741b5a604076b447e | https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L206-L243 | valid |
piotrmurach/benchmark-trend | lib/benchmark/trend.rb | Benchmark.Trend.fit_at | def fit_at(type, slope: nil, intercept: nil, n: nil)
raise ArgumentError, "Incorrect input size: #{n}" unless n > 0
case type
when :logarithmic, :log
intercept + slope * Math.log(n)
when :linear
intercept + slope * n
when :power
intercept * (n ** slope)
when :exponential, :exp
intercept * (slope ** n)
else
raise ArgumentError, "Unknown fit type: #{type}"
end
end | ruby | def fit_at(type, slope: nil, intercept: nil, n: nil)
raise ArgumentError, "Incorrect input size: #{n}" unless n > 0
case type
when :logarithmic, :log
intercept + slope * Math.log(n)
when :linear
intercept + slope * n
when :power
intercept * (n ** slope)
when :exponential, :exp
intercept * (slope ** n)
else
raise ArgumentError, "Unknown fit type: #{type}"
end
end | [
"def",
"fit_at",
"(",
"type",
",",
"slope",
":",
"nil",
",",
"intercept",
":",
"nil",
",",
"n",
":",
"nil",
")",
"raise",
"ArgumentError",
",",
"\"Incorrect input size: #{n}\"",
"unless",
"n",
">",
"0",
"case",
"type",
"when",
":logarithmic",
",",
":log",
... | Take a fit and estimate behaviour at input size n
@example
fit_at(:power, slope: 1.5, intercept: 2, n: 10)
@return
fit model value for input n
@api public | [
"Take",
"a",
"fit",
"and",
"estimate",
"behaviour",
"at",
"input",
"size",
"n"
] | 7f565cb6a09667b4e7cf7d7741b5a604076b447e | https://github.com/piotrmurach/benchmark-trend/blob/7f565cb6a09667b4e7cf7d7741b5a604076b447e/lib/benchmark/trend.rb#L255-L270 | valid |
digital-fabric/modulation | lib/modulation/module_mixin.rb | Modulation.ModuleMixin.export | def export(*symbols)
symbols = symbols.first if symbols.first.is_a?(Array)
__exported_symbols.concat(symbols)
end | ruby | def export(*symbols)
symbols = symbols.first if symbols.first.is_a?(Array)
__exported_symbols.concat(symbols)
end | [
"def",
"export",
"(",
"*",
"symbols",
")",
"symbols",
"=",
"symbols",
".",
"first",
"if",
"symbols",
".",
"first",
".",
"is_a?",
"(",
"Array",
")",
"__exported_symbols",
".",
"concat",
"(",
"symbols",
")",
"end"
] | Adds given symbols to the exported_symbols array
@param symbols [Array] array of symbols
@return [void] | [
"Adds",
"given",
"symbols",
"to",
"the",
"exported_symbols",
"array"
] | 28cd3f02f32da25ec7cf156c4df0ccfcb0294124 | https://github.com/digital-fabric/modulation/blob/28cd3f02f32da25ec7cf156c4df0ccfcb0294124/lib/modulation/module_mixin.rb#L12-L15 | valid |
digital-fabric/modulation | lib/modulation/module_mixin.rb | Modulation.ModuleMixin.__expose! | def __expose!
singleton = singleton_class
singleton.private_instance_methods.each do |sym|
singleton.send(:public, sym)
end
__module_info[:private_constants].each do |sym|
const_set(sym, singleton.const_get(sym))
end
self
end | ruby | def __expose!
singleton = singleton_class
singleton.private_instance_methods.each do |sym|
singleton.send(:public, sym)
end
__module_info[:private_constants].each do |sym|
const_set(sym, singleton.const_get(sym))
end
self
end | [
"def",
"__expose!",
"singleton",
"=",
"singleton_class",
"singleton",
".",
"private_instance_methods",
".",
"each",
"do",
"|",
"sym",
"|",
"singleton",
".",
"send",
"(",
":public",
",",
"sym",
")",
"end",
"__module_info",
"[",
":private_constants",
"]",
".",
"... | Exposes all private methods and private constants as public
@return [Module] self | [
"Exposes",
"all",
"private",
"methods",
"and",
"private",
"constants",
"as",
"public"
] | 28cd3f02f32da25ec7cf156c4df0ccfcb0294124 | https://github.com/digital-fabric/modulation/blob/28cd3f02f32da25ec7cf156c4df0ccfcb0294124/lib/modulation/module_mixin.rb#L85-L97 | valid |
jeremyevans/rack-unreloader | lib/rack/unreloader.rb | Rack.Unreloader.require | def require(paths, &block)
if @reloader
@reloader.require_dependencies(paths, &block)
else
Unreloader.expand_directory_paths(paths).each{|f| super(f)}
end
end | ruby | def require(paths, &block)
if @reloader
@reloader.require_dependencies(paths, &block)
else
Unreloader.expand_directory_paths(paths).each{|f| super(f)}
end
end | [
"def",
"require",
"(",
"paths",
",",
"&",
"block",
")",
"if",
"@reloader",
"@reloader",
".",
"require_dependencies",
"(",
"paths",
",",
"&",
"block",
")",
"else",
"Unreloader",
".",
"expand_directory_paths",
"(",
"paths",
")",
".",
"each",
"{",
"|",
"f",
... | Add a file glob or array of file globs to monitor for changes. | [
"Add",
"a",
"file",
"glob",
"or",
"array",
"of",
"file",
"globs",
"to",
"monitor",
"for",
"changes",
"."
] | f9295c8fbd7e643100eba47b6eaa1e84ad466290 | https://github.com/jeremyevans/rack-unreloader/blob/f9295c8fbd7e643100eba47b6eaa1e84ad466290/lib/rack/unreloader.rb#L88-L94 | valid |
jeremyevans/rack-unreloader | lib/rack/unreloader.rb | Rack.Unreloader.record_dependency | def record_dependency(dependency, *files)
if @reloader
files = Unreloader.expand_paths(files)
Unreloader.expand_paths(dependency).each do |path|
@reloader.record_dependency(path, files)
end
end
end | ruby | def record_dependency(dependency, *files)
if @reloader
files = Unreloader.expand_paths(files)
Unreloader.expand_paths(dependency).each do |path|
@reloader.record_dependency(path, files)
end
end
end | [
"def",
"record_dependency",
"(",
"dependency",
",",
"*",
"files",
")",
"if",
"@reloader",
"files",
"=",
"Unreloader",
".",
"expand_paths",
"(",
"files",
")",
"Unreloader",
".",
"expand_paths",
"(",
"dependency",
")",
".",
"each",
"do",
"|",
"path",
"|",
"@... | Records that each path in +files+ depends on +dependency+. If there
is a modification to +dependency+, all related files will be reloaded
after +dependency+ is reloaded. Both +dependency+ and each entry in +files+
can be an array of path globs. | [
"Records",
"that",
"each",
"path",
"in",
"+",
"files",
"+",
"depends",
"on",
"+",
"dependency",
"+",
".",
"If",
"there",
"is",
"a",
"modification",
"to",
"+",
"dependency",
"+",
"all",
"related",
"files",
"will",
"be",
"reloaded",
"after",
"+",
"dependen... | f9295c8fbd7e643100eba47b6eaa1e84ad466290 | https://github.com/jeremyevans/rack-unreloader/blob/f9295c8fbd7e643100eba47b6eaa1e84ad466290/lib/rack/unreloader.rb#L100-L107 | valid |
jeremyevans/rack-unreloader | lib/rack/unreloader.rb | Rack.Unreloader.record_split_class | def record_split_class(main_file, *files)
if @reloader
files = Unreloader.expand_paths(files)
files.each do |file|
record_dependency(file, main_file)
end
@reloader.skip_reload(files)
end
end | ruby | def record_split_class(main_file, *files)
if @reloader
files = Unreloader.expand_paths(files)
files.each do |file|
record_dependency(file, main_file)
end
@reloader.skip_reload(files)
end
end | [
"def",
"record_split_class",
"(",
"main_file",
",",
"*",
"files",
")",
"if",
"@reloader",
"files",
"=",
"Unreloader",
".",
"expand_paths",
"(",
"files",
")",
"files",
".",
"each",
"do",
"|",
"file",
"|",
"record_dependency",
"(",
"file",
",",
"main_file",
... | Record that a class is split into multiple files. +main_file+ should be
the main file for the class, which should require all of the other
files. +files+ should be a list of all other files that make up the class. | [
"Record",
"that",
"a",
"class",
"is",
"split",
"into",
"multiple",
"files",
".",
"+",
"main_file",
"+",
"should",
"be",
"the",
"main",
"file",
"for",
"the",
"class",
"which",
"should",
"require",
"all",
"of",
"the",
"other",
"files",
".",
"+",
"files",
... | f9295c8fbd7e643100eba47b6eaa1e84ad466290 | https://github.com/jeremyevans/rack-unreloader/blob/f9295c8fbd7e643100eba47b6eaa1e84ad466290/lib/rack/unreloader.rb#L112-L120 | valid |
hirefire/hirefire-resource | lib/hirefire/middleware.rb | HireFire.Middleware.get_queue | def get_queue(value)
ms = (Time.now.to_f * 1000).to_i - value.to_i
ms < 0 ? 0 : ms
end | ruby | def get_queue(value)
ms = (Time.now.to_f * 1000).to_i - value.to_i
ms < 0 ? 0 : ms
end | [
"def",
"get_queue",
"(",
"value",
")",
"ms",
"=",
"(",
"Time",
".",
"now",
".",
"to_f",
"*",
"1000",
")",
".",
"to_i",
"-",
"value",
".",
"to_i",
"ms",
"<",
"0",
"?",
"0",
":",
"ms",
"end"
] | Calculates the difference, in milliseconds, between the
HTTP_X_REQUEST_START time and the current time.
@param [String] the timestamp from HTTP_X_REQUEST_START.
@return [Integer] the queue time in milliseconds. | [
"Calculates",
"the",
"difference",
"in",
"milliseconds",
"between",
"the",
"HTTP_X_REQUEST_START",
"time",
"and",
"the",
"current",
"time",
"."
] | 9f8bc1885ba73e9d5cf39d34fe4f15905ded3753 | https://github.com/hirefire/hirefire-resource/blob/9f8bc1885ba73e9d5cf39d34fe4f15905ded3753/lib/hirefire/middleware.rb#L128-L131 | valid |
infosimples/two_captcha | lib/two_captcha/client.rb | TwoCaptcha.Client.decode | def decode(options = {})
decode!(options)
rescue TwoCaptcha::Error => ex
TwoCaptcha::Captcha.new
end | ruby | def decode(options = {})
decode!(options)
rescue TwoCaptcha::Error => ex
TwoCaptcha::Captcha.new
end | [
"def",
"decode",
"(",
"options",
"=",
"{",
"}",
")",
"decode!",
"(",
"options",
")",
"rescue",
"TwoCaptcha",
"::",
"Error",
"=>",
"ex",
"TwoCaptcha",
"::",
"Captcha",
".",
"new",
"end"
] | Create a TwoCaptcha API client.
@param [String] Captcha key of the TwoCaptcha account.
@param [Hash] options Options hash.
@option options [Integer] :timeout (60) Seconds before giving up of a
captcha being solved.
@option options [Integer] :polling (5) Seconds before check_answer again
@return [TwoCaptcha::Client] A Client instance.
Decode the text from an image (i.e. solve a captcha).
@param [Hash] options Options hash. Check docs for the method decode!.
@return [TwoCaptcha::Captcha] The captcha (with solution) or an empty
captcha instance if something goes wrong. | [
"Create",
"a",
"TwoCaptcha",
"API",
"client",
"."
] | 60bc263c75a542a2416de46574a1b4982a6a2772 | https://github.com/infosimples/two_captcha/blob/60bc263c75a542a2416de46574a1b4982a6a2772/lib/two_captcha/client.rb#L33-L37 | valid |
infosimples/two_captcha | lib/two_captcha/client.rb | TwoCaptcha.Client.upload | def upload(options = {})
args = {}
args[:body] = options[:raw64] if options[:raw64]
args[:method] = options[:method] || 'base64'
args.merge!(options)
response = request('in', :multipart, args)
unless response.match(/\AOK\|/)
fail(TwoCaptcha::Error, 'Unexpected API Response')
end
TwoCaptcha::Captcha.new(
id: response.split('|', 2)[1],
api_response: response
)
end | ruby | def upload(options = {})
args = {}
args[:body] = options[:raw64] if options[:raw64]
args[:method] = options[:method] || 'base64'
args.merge!(options)
response = request('in', :multipart, args)
unless response.match(/\AOK\|/)
fail(TwoCaptcha::Error, 'Unexpected API Response')
end
TwoCaptcha::Captcha.new(
id: response.split('|', 2)[1],
api_response: response
)
end | [
"def",
"upload",
"(",
"options",
"=",
"{",
"}",
")",
"args",
"=",
"{",
"}",
"args",
"[",
":body",
"]",
"=",
"options",
"[",
":raw64",
"]",
"if",
"options",
"[",
":raw64",
"]",
"args",
"[",
":method",
"]",
"=",
"options",
"[",
":method",
"]",
"||"... | Upload a captcha to 2Captcha.
This method will not return the solution. It helps on separating concerns.
@return [TwoCaptcha::Captcha] The captcha object (not solved yet). | [
"Upload",
"a",
"captcha",
"to",
"2Captcha",
"."
] | 60bc263c75a542a2416de46574a1b4982a6a2772 | https://github.com/infosimples/two_captcha/blob/60bc263c75a542a2416de46574a1b4982a6a2772/lib/two_captcha/client.rb#L131-L146 | valid |
infosimples/two_captcha | lib/two_captcha/client.rb | TwoCaptcha.Client.captcha | def captcha(captcha_id)
response = request('res', :get, action: 'get', id: captcha_id)
decoded_captcha = TwoCaptcha::Captcha.new(id: captcha_id)
decoded_captcha.api_response = response
if response.match(/\AOK\|/)
decoded_captcha.text = response.split('|', 2)[1]
end
decoded_captcha
end | ruby | def captcha(captcha_id)
response = request('res', :get, action: 'get', id: captcha_id)
decoded_captcha = TwoCaptcha::Captcha.new(id: captcha_id)
decoded_captcha.api_response = response
if response.match(/\AOK\|/)
decoded_captcha.text = response.split('|', 2)[1]
end
decoded_captcha
end | [
"def",
"captcha",
"(",
"captcha_id",
")",
"response",
"=",
"request",
"(",
"'res'",
",",
":get",
",",
"action",
":",
"'get'",
",",
"id",
":",
"captcha_id",
")",
"decoded_captcha",
"=",
"TwoCaptcha",
"::",
"Captcha",
".",
"new",
"(",
"id",
":",
"captcha_i... | Retrieve information from an uploaded captcha.
@param [Integer] captcha_id Numeric ID of the captcha.
@return [TwoCaptcha::Captcha] The captcha object. | [
"Retrieve",
"information",
"from",
"an",
"uploaded",
"captcha",
"."
] | 60bc263c75a542a2416de46574a1b4982a6a2772 | https://github.com/infosimples/two_captcha/blob/60bc263c75a542a2416de46574a1b4982a6a2772/lib/two_captcha/client.rb#L154-L165 | valid |
infosimples/two_captcha | lib/two_captcha/client.rb | TwoCaptcha.Client.load_captcha | def load_captcha(options)
if options[:raw64]
options[:raw64]
elsif options[:raw]
Base64.encode64(options[:raw])
elsif options[:file]
Base64.encode64(options[:file].read)
elsif options[:path]
Base64.encode64(File.open(options[:path], 'rb').read)
elsif options[:url]
Base64.encode64(TwoCaptcha::HTTP.open_url(options[:url]))
else
fail TwoCaptcha::ArgumentError, 'Illegal image format'
end
rescue
raise TwoCaptcha::InvalidCaptcha
end | ruby | def load_captcha(options)
if options[:raw64]
options[:raw64]
elsif options[:raw]
Base64.encode64(options[:raw])
elsif options[:file]
Base64.encode64(options[:file].read)
elsif options[:path]
Base64.encode64(File.open(options[:path], 'rb').read)
elsif options[:url]
Base64.encode64(TwoCaptcha::HTTP.open_url(options[:url]))
else
fail TwoCaptcha::ArgumentError, 'Illegal image format'
end
rescue
raise TwoCaptcha::InvalidCaptcha
end | [
"def",
"load_captcha",
"(",
"options",
")",
"if",
"options",
"[",
":raw64",
"]",
"options",
"[",
":raw64",
"]",
"elsif",
"options",
"[",
":raw",
"]",
"Base64",
".",
"encode64",
"(",
"options",
"[",
":raw",
"]",
")",
"elsif",
"options",
"[",
":file",
"]... | Load a captcha raw content encoded in base64 from options.
@param [Hash] options Options hash.
@option options [String] :url URL of the image to be decoded.
@option options [String] :path File path of the image to be decoded.
@option options [File] :file File instance with image to be decoded.
@option options [String] :raw Binary content of the image to bedecoded.
@option options [String] :raw64 Binary content encoded in base64 of the
image to be decoded.
@return [String] The binary image base64 encoded. | [
"Load",
"a",
"captcha",
"raw",
"content",
"encoded",
"in",
"base64",
"from",
"options",
"."
] | 60bc263c75a542a2416de46574a1b4982a6a2772 | https://github.com/infosimples/two_captcha/blob/60bc263c75a542a2416de46574a1b4982a6a2772/lib/two_captcha/client.rb#L218-L234 | valid |
infosimples/two_captcha | lib/two_captcha/client.rb | TwoCaptcha.Client.request | def request(action, method = :get, payload = {})
res = TwoCaptcha::HTTP.request(
url: BASE_URL.gsub(':action', action),
timeout: timeout,
method: method,
payload: payload.merge(key: key, soft_id: 800)
)
validate_response(res)
res
end | ruby | def request(action, method = :get, payload = {})
res = TwoCaptcha::HTTP.request(
url: BASE_URL.gsub(':action', action),
timeout: timeout,
method: method,
payload: payload.merge(key: key, soft_id: 800)
)
validate_response(res)
res
end | [
"def",
"request",
"(",
"action",
",",
"method",
"=",
":get",
",",
"payload",
"=",
"{",
"}",
")",
"res",
"=",
"TwoCaptcha",
"::",
"HTTP",
".",
"request",
"(",
"url",
":",
"BASE_URL",
".",
"gsub",
"(",
"':action'",
",",
"action",
")",
",",
"timeout",
... | Perform an HTTP request to the 2Captcha API.
@param [String] action API method name.
@param [Symbol] method HTTP method (:get, :post, :multipart).
@param [Hash] payload Data to be sent through the HTTP request.
@return [String] Response from the TwoCaptcha API. | [
"Perform",
"an",
"HTTP",
"request",
"to",
"the",
"2Captcha",
"API",
"."
] | 60bc263c75a542a2416de46574a1b4982a6a2772 | https://github.com/infosimples/two_captcha/blob/60bc263c75a542a2416de46574a1b4982a6a2772/lib/two_captcha/client.rb#L244-L253 | valid |
infosimples/two_captcha | lib/two_captcha/client.rb | TwoCaptcha.Client.validate_response | def validate_response(response)
if (error = TwoCaptcha::RESPONSE_ERRORS[response])
fail(error)
elsif response.to_s.empty? || response.match(/\AERROR\_/)
fail(TwoCaptcha::Error, response)
end
end | ruby | def validate_response(response)
if (error = TwoCaptcha::RESPONSE_ERRORS[response])
fail(error)
elsif response.to_s.empty? || response.match(/\AERROR\_/)
fail(TwoCaptcha::Error, response)
end
end | [
"def",
"validate_response",
"(",
"response",
")",
"if",
"(",
"error",
"=",
"TwoCaptcha",
"::",
"RESPONSE_ERRORS",
"[",
"response",
"]",
")",
"fail",
"(",
"error",
")",
"elsif",
"response",
".",
"to_s",
".",
"empty?",
"||",
"response",
".",
"match",
"(",
... | Fail if the response has errors.
@param [String] response The body response from TwoCaptcha API. | [
"Fail",
"if",
"the",
"response",
"has",
"errors",
"."
] | 60bc263c75a542a2416de46574a1b4982a6a2772 | https://github.com/infosimples/two_captcha/blob/60bc263c75a542a2416de46574a1b4982a6a2772/lib/two_captcha/client.rb#L259-L265 | valid |
github/github-ldap | lib/github/ldap.rb | GitHub.Ldap.search | def search(options, &block)
instrument "search.github_ldap", options.dup do |payload|
result =
if options[:base]
@connection.search(options, &block)
else
search_domains.each_with_object([]) do |base, result|
rs = @connection.search(options.merge(:base => base), &block)
result.concat Array(rs) unless rs == false
end
end
return [] if result == false
Array(result)
end
end | ruby | def search(options, &block)
instrument "search.github_ldap", options.dup do |payload|
result =
if options[:base]
@connection.search(options, &block)
else
search_domains.each_with_object([]) do |base, result|
rs = @connection.search(options.merge(:base => base), &block)
result.concat Array(rs) unless rs == false
end
end
return [] if result == false
Array(result)
end
end | [
"def",
"search",
"(",
"options",
",",
"&",
"block",
")",
"instrument",
"\"search.github_ldap\"",
",",
"options",
".",
"dup",
"do",
"|",
"payload",
"|",
"result",
"=",
"if",
"options",
"[",
":base",
"]",
"@connection",
".",
"search",
"(",
"options",
",",
... | Public - Search entries in the ldap server.
options: is a hash with the same options that Net::LDAP::Connection#search supports.
block: is an optional block to pass to the search.
Returns an Array of Net::LDAP::Entry. | [
"Public",
"-",
"Search",
"entries",
"in",
"the",
"ldap",
"server",
"."
] | 34c2685bd07ae79c6283f14f1263d1276a162f28 | https://github.com/github/github-ldap/blob/34c2685bd07ae79c6283f14f1263d1276a162f28/lib/github/ldap.rb#L205-L220 | valid |
github/github-ldap | lib/github/ldap.rb | GitHub.Ldap.check_encryption | def check_encryption(encryption, tls_options = {})
return unless encryption
tls_options ||= {}
case encryption.downcase.to_sym
when :ssl, :simple_tls
{ method: :simple_tls, tls_options: tls_options }
when :tls, :start_tls
{ method: :start_tls, tls_options: tls_options }
end
end | ruby | def check_encryption(encryption, tls_options = {})
return unless encryption
tls_options ||= {}
case encryption.downcase.to_sym
when :ssl, :simple_tls
{ method: :simple_tls, tls_options: tls_options }
when :tls, :start_tls
{ method: :start_tls, tls_options: tls_options }
end
end | [
"def",
"check_encryption",
"(",
"encryption",
",",
"tls_options",
"=",
"{",
"}",
")",
"return",
"unless",
"encryption",
"tls_options",
"||=",
"{",
"}",
"case",
"encryption",
".",
"downcase",
".",
"to_sym",
"when",
":ssl",
",",
":simple_tls",
"{",
"method",
"... | Internal - Determine whether to use encryption or not.
encryption: is the encryption method, either 'ssl', 'tls', 'simple_tls' or 'start_tls'.
tls_options: is the options hash for tls encryption method
Returns the real encryption type. | [
"Internal",
"-",
"Determine",
"whether",
"to",
"use",
"encryption",
"or",
"not",
"."
] | 34c2685bd07ae79c6283f14f1263d1276a162f28 | https://github.com/github/github-ldap/blob/34c2685bd07ae79c6283f14f1263d1276a162f28/lib/github/ldap.rb#L245-L255 | valid |
github/github-ldap | lib/github/ldap.rb | GitHub.Ldap.configure_virtual_attributes | def configure_virtual_attributes(attributes)
@virtual_attributes = if attributes == true
VirtualAttributes.new(true)
elsif attributes.is_a?(Hash)
VirtualAttributes.new(true, attributes)
else
VirtualAttributes.new(false)
end
end | ruby | def configure_virtual_attributes(attributes)
@virtual_attributes = if attributes == true
VirtualAttributes.new(true)
elsif attributes.is_a?(Hash)
VirtualAttributes.new(true, attributes)
else
VirtualAttributes.new(false)
end
end | [
"def",
"configure_virtual_attributes",
"(",
"attributes",
")",
"@virtual_attributes",
"=",
"if",
"attributes",
"==",
"true",
"VirtualAttributes",
".",
"new",
"(",
"true",
")",
"elsif",
"attributes",
".",
"is_a?",
"(",
"Hash",
")",
"VirtualAttributes",
".",
"new",
... | Internal - Configure virtual attributes for this server.
If the option is `true`, we'll use the default virual attributes.
If it's a Hash we'll map the attributes in the hash.
attributes: is the option set when Ldap is initialized.
Returns a VirtualAttributes. | [
"Internal",
"-",
"Configure",
"virtual",
"attributes",
"for",
"this",
"server",
".",
"If",
"the",
"option",
"is",
"true",
"we",
"ll",
"use",
"the",
"default",
"virual",
"attributes",
".",
"If",
"it",
"s",
"a",
"Hash",
"we",
"ll",
"map",
"the",
"attribute... | 34c2685bd07ae79c6283f14f1263d1276a162f28 | https://github.com/github/github-ldap/blob/34c2685bd07ae79c6283f14f1263d1276a162f28/lib/github/ldap.rb#L264-L272 | valid |
detunized/lastpass-ruby | lib/lastpass/vault.rb | LastPass.Vault.complete? | def complete? chunks
!chunks.empty? && chunks.last.id == "ENDM" && chunks.last.payload == "OK"
end | ruby | def complete? chunks
!chunks.empty? && chunks.last.id == "ENDM" && chunks.last.payload == "OK"
end | [
"def",
"complete?",
"chunks",
"!",
"chunks",
".",
"empty?",
"&&",
"chunks",
".",
"last",
".",
"id",
"==",
"\"ENDM\"",
"&&",
"chunks",
".",
"last",
".",
"payload",
"==",
"\"OK\"",
"end"
] | This more of an internal method, use one of the static constructors instead | [
"This",
"more",
"of",
"an",
"internal",
"method",
"use",
"one",
"of",
"the",
"static",
"constructors",
"instead"
] | 3212ff17c7dd370807f688a3875a6f21b44dcb2a | https://github.com/detunized/lastpass-ruby/blob/3212ff17c7dd370807f688a3875a6f21b44dcb2a/lib/lastpass/vault.rb#L43-L45 | valid |
savonrb/gyoku | lib/gyoku/prettifier.rb | Gyoku.Prettifier.prettify | def prettify(xml)
result = ''
formatter = REXML::Formatters::Pretty.new indent
formatter.compact = compact
doc = REXML::Document.new xml
formatter.write doc, result
result
end | ruby | def prettify(xml)
result = ''
formatter = REXML::Formatters::Pretty.new indent
formatter.compact = compact
doc = REXML::Document.new xml
formatter.write doc, result
result
end | [
"def",
"prettify",
"(",
"xml",
")",
"result",
"=",
"''",
"formatter",
"=",
"REXML",
"::",
"Formatters",
"::",
"Pretty",
".",
"new",
"indent",
"formatter",
".",
"compact",
"=",
"compact",
"doc",
"=",
"REXML",
"::",
"Document",
".",
"new",
"xml",
"formatte... | Adds intendations and newlines to +xml+ to make it more readable | [
"Adds",
"intendations",
"and",
"newlines",
"to",
"+",
"xml",
"+",
"to",
"make",
"it",
"more",
"readable"
] | 954d002b7c88e826492a7989d44e2b08a8e980e4 | https://github.com/savonrb/gyoku/blob/954d002b7c88e826492a7989d44e2b08a8e980e4/lib/gyoku/prettifier.rb#L20-L27 | valid |
MindscapeHQ/raygun4ruby | lib/raygun/sidekiq.rb | Raygun.SidekiqMiddleware.call | def call(worker, message, queue)
begin
yield
rescue Exception => ex
raise ex if [Interrupt, SystemExit, SignalException].include?(ex.class)
SidekiqReporter.call(ex, worker: worker, message: message, queue: queue)
raise ex
end
end | ruby | def call(worker, message, queue)
begin
yield
rescue Exception => ex
raise ex if [Interrupt, SystemExit, SignalException].include?(ex.class)
SidekiqReporter.call(ex, worker: worker, message: message, queue: queue)
raise ex
end
end | [
"def",
"call",
"(",
"worker",
",",
"message",
",",
"queue",
")",
"begin",
"yield",
"rescue",
"Exception",
"=>",
"ex",
"raise",
"ex",
"if",
"[",
"Interrupt",
",",
"SystemExit",
",",
"SignalException",
"]",
".",
"include?",
"(",
"ex",
".",
"class",
")",
... | Used for Sidekiq 2.x only | [
"Used",
"for",
"Sidekiq",
"2",
".",
"x",
"only"
] | 62029ccab220ed6f5ef55399088fccfa8938aab6 | https://github.com/MindscapeHQ/raygun4ruby/blob/62029ccab220ed6f5ef55399088fccfa8938aab6/lib/raygun/sidekiq.rb#L9-L17 | valid |
mloughran/em-hiredis | lib/em-hiredis/lock.rb | EM::Hiredis.Lock.acquire | def acquire
df = EM::DefaultDeferrable.new
@redis.lock_acquire([@key], [@token, @timeout]).callback { |success|
if (success)
EM::Hiredis.logger.debug "#{to_s} acquired"
EM.cancel_timer(@expire_timer) if @expire_timer
@expire_timer = EM.add_timer(@timeout - 1) {
EM::Hiredis.logger.debug "#{to_s} Expires in 1s"
@onexpire.call if @onexpire
}
df.succeed
else
EM::Hiredis.logger.debug "#{to_s} failed to acquire"
df.fail("Lock is not available")
end
}.errback { |e|
EM::Hiredis.logger.error "#{to_s} Error acquiring lock #{e}"
df.fail(e)
}
df
end | ruby | def acquire
df = EM::DefaultDeferrable.new
@redis.lock_acquire([@key], [@token, @timeout]).callback { |success|
if (success)
EM::Hiredis.logger.debug "#{to_s} acquired"
EM.cancel_timer(@expire_timer) if @expire_timer
@expire_timer = EM.add_timer(@timeout - 1) {
EM::Hiredis.logger.debug "#{to_s} Expires in 1s"
@onexpire.call if @onexpire
}
df.succeed
else
EM::Hiredis.logger.debug "#{to_s} failed to acquire"
df.fail("Lock is not available")
end
}.errback { |e|
EM::Hiredis.logger.error "#{to_s} Error acquiring lock #{e}"
df.fail(e)
}
df
end | [
"def",
"acquire",
"df",
"=",
"EM",
"::",
"DefaultDeferrable",
".",
"new",
"@redis",
".",
"lock_acquire",
"(",
"[",
"@key",
"]",
",",
"[",
"@token",
",",
"@timeout",
"]",
")",
".",
"callback",
"{",
"|",
"success",
"|",
"if",
"(",
"success",
")",
"EM",... | Acquire the lock
This is a re-entrant lock, re-acquiring will succeed and extend the timeout
Returns a deferrable which either succeeds if the lock can be acquired, or fails if it cannot. | [
"Acquire",
"the",
"lock"
] | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/lock.rb#L28-L50 | valid |
mloughran/em-hiredis | lib/em-hiredis/lock.rb | EM::Hiredis.Lock.unlock | def unlock
EM.cancel_timer(@expire_timer) if @expire_timer
df = EM::DefaultDeferrable.new
@redis.lock_release([@key], [@token]).callback { |keys_removed|
if keys_removed > 0
EM::Hiredis.logger.debug "#{to_s} released"
df.succeed
else
EM::Hiredis.logger.debug "#{to_s} could not release, not held"
df.fail("Cannot release a lock we do not hold")
end
}.errback { |e|
EM::Hiredis.logger.error "#{to_s} Error releasing lock #{e}"
df.fail(e)
}
df
end | ruby | def unlock
EM.cancel_timer(@expire_timer) if @expire_timer
df = EM::DefaultDeferrable.new
@redis.lock_release([@key], [@token]).callback { |keys_removed|
if keys_removed > 0
EM::Hiredis.logger.debug "#{to_s} released"
df.succeed
else
EM::Hiredis.logger.debug "#{to_s} could not release, not held"
df.fail("Cannot release a lock we do not hold")
end
}.errback { |e|
EM::Hiredis.logger.error "#{to_s} Error releasing lock #{e}"
df.fail(e)
}
df
end | [
"def",
"unlock",
"EM",
".",
"cancel_timer",
"(",
"@expire_timer",
")",
"if",
"@expire_timer",
"df",
"=",
"EM",
"::",
"DefaultDeferrable",
".",
"new",
"@redis",
".",
"lock_release",
"(",
"[",
"@key",
"]",
",",
"[",
"@token",
"]",
")",
".",
"callback",
"{"... | Release the lock
Returns a deferrable | [
"Release",
"the",
"lock"
] | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/lock.rb#L55-L72 | valid |
mloughran/em-hiredis | spec/support/redis_mock.rb | RedisMock.Helper.redis_mock | def redis_mock(replies = {})
begin
pid = fork do
trap("TERM") { exit }
RedisMock.start do |command, *args|
(replies[command.to_sym] || lambda { |*_| "+OK" }).call(*args)
end
end
sleep 1 # Give time for the socket to start listening.
yield
ensure
if pid
Process.kill("TERM", pid)
Process.wait(pid)
end
end
end | ruby | def redis_mock(replies = {})
begin
pid = fork do
trap("TERM") { exit }
RedisMock.start do |command, *args|
(replies[command.to_sym] || lambda { |*_| "+OK" }).call(*args)
end
end
sleep 1 # Give time for the socket to start listening.
yield
ensure
if pid
Process.kill("TERM", pid)
Process.wait(pid)
end
end
end | [
"def",
"redis_mock",
"(",
"replies",
"=",
"{",
"}",
")",
"begin",
"pid",
"=",
"fork",
"do",
"trap",
"(",
"\"TERM\"",
")",
"{",
"exit",
"}",
"RedisMock",
".",
"start",
"do",
"|",
"command",
",",
"*",
"args",
"|",
"(",
"replies",
"[",
"command",
".",... | Forks the current process and starts a new mock Redis server on
port 6380.
The server will reply with a `+OK` to all commands, but you can
customize it by providing a hash. For example:
redis_mock(:ping => lambda { "+PONG" }) do
assert_equal "PONG", Redis.new(:port => 6380).ping
end | [
"Forks",
"the",
"current",
"process",
"and",
"starts",
"a",
"new",
"mock",
"Redis",
"server",
"on",
"port",
"6380",
"."
] | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/spec/support/redis_mock.rb#L43-L63 | valid |
mloughran/em-hiredis | lib/em-hiredis/base_client.rb | EventMachine::Hiredis.BaseClient.configure | def configure(uri_string)
uri = URI(uri_string)
if uri.scheme == "unix"
@host = uri.path
@port = nil
else
@host = uri.host
@port = uri.port
@password = uri.password
path = uri.path[1..-1]
@db = path.to_i # Empty path => 0
end
end | ruby | def configure(uri_string)
uri = URI(uri_string)
if uri.scheme == "unix"
@host = uri.path
@port = nil
else
@host = uri.host
@port = uri.port
@password = uri.password
path = uri.path[1..-1]
@db = path.to_i # Empty path => 0
end
end | [
"def",
"configure",
"(",
"uri_string",
")",
"uri",
"=",
"URI",
"(",
"uri_string",
")",
"if",
"uri",
".",
"scheme",
"==",
"\"unix\"",
"@host",
"=",
"uri",
".",
"path",
"@port",
"=",
"nil",
"else",
"@host",
"=",
"uri",
".",
"host",
"@port",
"=",
"uri",... | Configure the redis connection to use
In usual operation, the uri should be passed to initialize. This method
is useful for example when failing over to a slave connection at runtime | [
"Configure",
"the",
"redis",
"connection",
"to",
"use"
] | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/base_client.rb#L44-L57 | valid |
mloughran/em-hiredis | lib/em-hiredis/base_client.rb | EventMachine::Hiredis.BaseClient.reconnect! | def reconnect!(new_uri = nil)
@connection.close_connection
configure(new_uri) if new_uri
@auto_reconnect = true
EM.next_tick { reconnect_connection }
end | ruby | def reconnect!(new_uri = nil)
@connection.close_connection
configure(new_uri) if new_uri
@auto_reconnect = true
EM.next_tick { reconnect_connection }
end | [
"def",
"reconnect!",
"(",
"new_uri",
"=",
"nil",
")",
"@connection",
".",
"close_connection",
"configure",
"(",
"new_uri",
")",
"if",
"new_uri",
"@auto_reconnect",
"=",
"true",
"EM",
".",
"next_tick",
"{",
"reconnect_connection",
"}",
"end"
] | Disconnect then reconnect the redis connection.
Pass optional uri - e.g. to connect to a different redis server.
Any pending redis commands will be failed, but during the reconnection
new commands will be queued and sent after connected. | [
"Disconnect",
"then",
"reconnect",
"the",
"redis",
"connection",
"."
] | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/base_client.rb#L65-L70 | valid |
mloughran/em-hiredis | lib/em-hiredis/base_client.rb | EventMachine::Hiredis.BaseClient.configure_inactivity_check | def configure_inactivity_check(trigger_secs, response_timeout)
raise ArgumentError('trigger_secs must be > 0') unless trigger_secs.to_i > 0
raise ArgumentError('response_timeout must be > 0') unless response_timeout.to_i > 0
@inactivity_trigger_secs = trigger_secs.to_i
@inactivity_response_timeout = response_timeout.to_i
# Start the inactivity check now only if we're already conected, otherwise
# the connected event will schedule it.
schedule_inactivity_checks if @connected
end | ruby | def configure_inactivity_check(trigger_secs, response_timeout)
raise ArgumentError('trigger_secs must be > 0') unless trigger_secs.to_i > 0
raise ArgumentError('response_timeout must be > 0') unless response_timeout.to_i > 0
@inactivity_trigger_secs = trigger_secs.to_i
@inactivity_response_timeout = response_timeout.to_i
# Start the inactivity check now only if we're already conected, otherwise
# the connected event will schedule it.
schedule_inactivity_checks if @connected
end | [
"def",
"configure_inactivity_check",
"(",
"trigger_secs",
",",
"response_timeout",
")",
"raise",
"ArgumentError",
"(",
"'trigger_secs must be > 0'",
")",
"unless",
"trigger_secs",
".",
"to_i",
">",
"0",
"raise",
"ArgumentError",
"(",
"'response_timeout must be > 0'",
")",... | Starts an inactivity checker which will ping redis if nothing has been
heard on the connection for `trigger_secs` seconds and forces a reconnect
after a further `response_timeout` seconds if we still don't hear anything. | [
"Starts",
"an",
"inactivity",
"checker",
"which",
"will",
"ping",
"redis",
"if",
"nothing",
"has",
"been",
"heard",
"on",
"the",
"connection",
"for",
"trigger_secs",
"seconds",
"and",
"forces",
"a",
"reconnect",
"after",
"a",
"further",
"response_timeout",
"seco... | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/base_client.rb#L193-L203 | valid |
mloughran/em-hiredis | lib/em-hiredis/pubsub_client.rb | EventMachine::Hiredis.PubsubClient.subscribe | def subscribe(channel, proc = nil, &block)
if cb = proc || block
@sub_callbacks[channel] << cb
end
@subs << channel
raw_send_command(:subscribe, [channel])
return pubsub_deferrable(channel)
end | ruby | def subscribe(channel, proc = nil, &block)
if cb = proc || block
@sub_callbacks[channel] << cb
end
@subs << channel
raw_send_command(:subscribe, [channel])
return pubsub_deferrable(channel)
end | [
"def",
"subscribe",
"(",
"channel",
",",
"proc",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"cb",
"=",
"proc",
"||",
"block",
"@sub_callbacks",
"[",
"channel",
"]",
"<<",
"cb",
"end",
"@subs",
"<<",
"channel",
"raw_send_command",
"(",
":subscribe",
",",
... | Subscribe to a pubsub channel
If an optional proc / block is provided then it will be called when a
message is received on this channel
@return [Deferrable] Redis subscribe call | [
"Subscribe",
"to",
"a",
"pubsub",
"channel"
] | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L33-L40 | valid |
mloughran/em-hiredis | lib/em-hiredis/pubsub_client.rb | EventMachine::Hiredis.PubsubClient.unsubscribe | def unsubscribe(channel)
@sub_callbacks.delete(channel)
@subs.delete(channel)
raw_send_command(:unsubscribe, [channel])
return pubsub_deferrable(channel)
end | ruby | def unsubscribe(channel)
@sub_callbacks.delete(channel)
@subs.delete(channel)
raw_send_command(:unsubscribe, [channel])
return pubsub_deferrable(channel)
end | [
"def",
"unsubscribe",
"(",
"channel",
")",
"@sub_callbacks",
".",
"delete",
"(",
"channel",
")",
"@subs",
".",
"delete",
"(",
"channel",
")",
"raw_send_command",
"(",
":unsubscribe",
",",
"[",
"channel",
"]",
")",
"return",
"pubsub_deferrable",
"(",
"channel",... | Unsubscribe all callbacks for a given channel
@return [Deferrable] Redis unsubscribe call | [
"Unsubscribe",
"all",
"callbacks",
"for",
"a",
"given",
"channel"
] | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L46-L51 | valid |
mloughran/em-hiredis | lib/em-hiredis/pubsub_client.rb | EventMachine::Hiredis.PubsubClient.unsubscribe_proc | def unsubscribe_proc(channel, proc)
df = EM::DefaultDeferrable.new
if @sub_callbacks[channel].delete(proc)
if @sub_callbacks[channel].any?
# Succeed deferrable immediately - no need to unsubscribe
df.succeed
else
unsubscribe(channel).callback { |_|
df.succeed
}
end
else
df.fail
end
return df
end | ruby | def unsubscribe_proc(channel, proc)
df = EM::DefaultDeferrable.new
if @sub_callbacks[channel].delete(proc)
if @sub_callbacks[channel].any?
# Succeed deferrable immediately - no need to unsubscribe
df.succeed
else
unsubscribe(channel).callback { |_|
df.succeed
}
end
else
df.fail
end
return df
end | [
"def",
"unsubscribe_proc",
"(",
"channel",
",",
"proc",
")",
"df",
"=",
"EM",
"::",
"DefaultDeferrable",
".",
"new",
"if",
"@sub_callbacks",
"[",
"channel",
"]",
".",
"delete",
"(",
"proc",
")",
"if",
"@sub_callbacks",
"[",
"channel",
"]",
".",
"any?",
"... | Unsubscribe a given callback from a channel. Will unsubscribe from redis
if there are no remaining subscriptions on this channel
@return [Deferrable] Succeeds when the unsubscribe has completed or
fails if callback could not be found. Note that success may happen
immediately in the case that there are other callbacks for the same
channel (and therefore no unsubscription from redis is necessary) | [
"Unsubscribe",
"a",
"given",
"callback",
"from",
"a",
"channel",
".",
"Will",
"unsubscribe",
"from",
"redis",
"if",
"there",
"are",
"no",
"remaining",
"subscriptions",
"on",
"this",
"channel"
] | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L61-L76 | valid |
mloughran/em-hiredis | lib/em-hiredis/pubsub_client.rb | EventMachine::Hiredis.PubsubClient.psubscribe | def psubscribe(pattern, proc = nil, &block)
if cb = proc || block
@psub_callbacks[pattern] << cb
end
@psubs << pattern
raw_send_command(:psubscribe, [pattern])
return pubsub_deferrable(pattern)
end | ruby | def psubscribe(pattern, proc = nil, &block)
if cb = proc || block
@psub_callbacks[pattern] << cb
end
@psubs << pattern
raw_send_command(:psubscribe, [pattern])
return pubsub_deferrable(pattern)
end | [
"def",
"psubscribe",
"(",
"pattern",
",",
"proc",
"=",
"nil",
",",
"&",
"block",
")",
"if",
"cb",
"=",
"proc",
"||",
"block",
"@psub_callbacks",
"[",
"pattern",
"]",
"<<",
"cb",
"end",
"@psubs",
"<<",
"pattern",
"raw_send_command",
"(",
":psubscribe",
",... | Pattern subscribe to a pubsub channel
If an optional proc / block is provided then it will be called (with the
channel name and message) when a message is received on a matching
channel
@return [Deferrable] Redis psubscribe call | [
"Pattern",
"subscribe",
"to",
"a",
"pubsub",
"channel"
] | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L86-L93 | valid |
mloughran/em-hiredis | lib/em-hiredis/pubsub_client.rb | EventMachine::Hiredis.PubsubClient.punsubscribe | def punsubscribe(pattern)
@psub_callbacks.delete(pattern)
@psubs.delete(pattern)
raw_send_command(:punsubscribe, [pattern])
return pubsub_deferrable(pattern)
end | ruby | def punsubscribe(pattern)
@psub_callbacks.delete(pattern)
@psubs.delete(pattern)
raw_send_command(:punsubscribe, [pattern])
return pubsub_deferrable(pattern)
end | [
"def",
"punsubscribe",
"(",
"pattern",
")",
"@psub_callbacks",
".",
"delete",
"(",
"pattern",
")",
"@psubs",
".",
"delete",
"(",
"pattern",
")",
"raw_send_command",
"(",
":punsubscribe",
",",
"[",
"pattern",
"]",
")",
"return",
"pubsub_deferrable",
"(",
"patte... | Pattern unsubscribe all callbacks for a given pattern
@return [Deferrable] Redis punsubscribe call | [
"Pattern",
"unsubscribe",
"all",
"callbacks",
"for",
"a",
"given",
"pattern"
] | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L99-L104 | valid |
mloughran/em-hiredis | lib/em-hiredis/pubsub_client.rb | EventMachine::Hiredis.PubsubClient.punsubscribe_proc | def punsubscribe_proc(pattern, proc)
df = EM::DefaultDeferrable.new
if @psub_callbacks[pattern].delete(proc)
if @psub_callbacks[pattern].any?
# Succeed deferrable immediately - no need to punsubscribe
df.succeed
else
punsubscribe(pattern).callback { |_|
df.succeed
}
end
else
df.fail
end
return df
end | ruby | def punsubscribe_proc(pattern, proc)
df = EM::DefaultDeferrable.new
if @psub_callbacks[pattern].delete(proc)
if @psub_callbacks[pattern].any?
# Succeed deferrable immediately - no need to punsubscribe
df.succeed
else
punsubscribe(pattern).callback { |_|
df.succeed
}
end
else
df.fail
end
return df
end | [
"def",
"punsubscribe_proc",
"(",
"pattern",
",",
"proc",
")",
"df",
"=",
"EM",
"::",
"DefaultDeferrable",
".",
"new",
"if",
"@psub_callbacks",
"[",
"pattern",
"]",
".",
"delete",
"(",
"proc",
")",
"if",
"@psub_callbacks",
"[",
"pattern",
"]",
".",
"any?",
... | Unsubscribe a given callback from a pattern. Will unsubscribe from redis
if there are no remaining subscriptions on this pattern
@return [Deferrable] Succeeds when the punsubscribe has completed or
fails if callback could not be found. Note that success may happen
immediately in the case that there are other callbacks for the same
pattern (and therefore no punsubscription from redis is necessary) | [
"Unsubscribe",
"a",
"given",
"callback",
"from",
"a",
"pattern",
".",
"Will",
"unsubscribe",
"from",
"redis",
"if",
"there",
"are",
"no",
"remaining",
"subscriptions",
"on",
"this",
"pattern"
] | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L114-L129 | valid |
mloughran/em-hiredis | lib/em-hiredis/pubsub_client.rb | EventMachine::Hiredis.PubsubClient.raw_send_command | def raw_send_command(sym, args)
if @connected
@connection.send_command(sym, args)
else
callback do
@connection.send_command(sym, args)
end
end
return nil
end | ruby | def raw_send_command(sym, args)
if @connected
@connection.send_command(sym, args)
else
callback do
@connection.send_command(sym, args)
end
end
return nil
end | [
"def",
"raw_send_command",
"(",
"sym",
",",
"args",
")",
"if",
"@connected",
"@connection",
".",
"send_command",
"(",
"sym",
",",
"args",
")",
"else",
"callback",
"do",
"@connection",
".",
"send_command",
"(",
"sym",
",",
"args",
")",
"end",
"end",
"return... | Send a command to redis without adding a deferrable for it. This is
useful for commands for which replies work or need to be treated
differently | [
"Send",
"a",
"command",
"to",
"redis",
"without",
"adding",
"a",
"deferrable",
"for",
"it",
".",
"This",
"is",
"useful",
"for",
"commands",
"for",
"which",
"replies",
"work",
"or",
"need",
"to",
"be",
"treated",
"differently"
] | c9eac4b938a1c3d4fda1ccfad6e0373037fbee99 | https://github.com/mloughran/em-hiredis/blob/c9eac4b938a1c3d4fda1ccfad6e0373037fbee99/lib/em-hiredis/pubsub_client.rb#L149-L158 | valid |
alphagov/gds-api-adapters | lib/gds_api/search.rb | GdsApi.Search.batch_search | def batch_search(searches, additional_headers = {})
url_friendly_searches = searches.each_with_index.map do |search, index|
{ index => search }
end
searches_query = { search: url_friendly_searches }
request_url = "#{base_url}/batch_search.json?#{Rack::Utils.build_nested_query(searches_query)}"
get_json(request_url, additional_headers)
end | ruby | def batch_search(searches, additional_headers = {})
url_friendly_searches = searches.each_with_index.map do |search, index|
{ index => search }
end
searches_query = { search: url_friendly_searches }
request_url = "#{base_url}/batch_search.json?#{Rack::Utils.build_nested_query(searches_query)}"
get_json(request_url, additional_headers)
end | [
"def",
"batch_search",
"(",
"searches",
",",
"additional_headers",
"=",
"{",
"}",
")",
"url_friendly_searches",
"=",
"searches",
".",
"each_with_index",
".",
"map",
"do",
"|",
"search",
",",
"index",
"|",
"{",
"index",
"=>",
"search",
"}",
"end",
"searches_q... | Perform a batch search.
@param searches [Array] An array valid search queries. Maximum of 6. See search-api documentation for options.
# @see https://github.com/alphagov/search-api/blob/master/doc/search-api.md | [
"Perform",
"a",
"batch",
"search",
"."
] | 94bb27e154907939d4d96d3ab330a61c8bdf1fb5 | https://github.com/alphagov/gds-api-adapters/blob/94bb27e154907939d4d96d3ab330a61c8bdf1fb5/lib/gds_api/search.rb#L81-L88 | valid |
alphagov/gds-api-adapters | lib/gds_api/search.rb | GdsApi.Search.search_enum | def search_enum(args, page_size: 100, additional_headers: {})
Enumerator.new do |yielder|
(0..Float::INFINITY).step(page_size).each do |index|
search_params = args.merge(start: index.to_i, count: page_size)
results = search(search_params, additional_headers).to_h.fetch('results', [])
results.each do |result|
yielder << result
end
if results.count < page_size
break
end
end
end
end | ruby | def search_enum(args, page_size: 100, additional_headers: {})
Enumerator.new do |yielder|
(0..Float::INFINITY).step(page_size).each do |index|
search_params = args.merge(start: index.to_i, count: page_size)
results = search(search_params, additional_headers).to_h.fetch('results', [])
results.each do |result|
yielder << result
end
if results.count < page_size
break
end
end
end
end | [
"def",
"search_enum",
"(",
"args",
",",
"page_size",
":",
"100",
",",
"additional_headers",
":",
"{",
"}",
")",
"Enumerator",
".",
"new",
"do",
"|",
"yielder",
"|",
"(",
"0",
"..",
"Float",
"::",
"INFINITY",
")",
".",
"step",
"(",
"page_size",
")",
"... | Perform a search, returning the results as an enumerator.
The enumerator abstracts away search-api's pagination and fetches new pages when
necessary.
@param args [Hash] A valid search query. See search-api documentation for options.
@param page_size [Integer] Number of results in each page.
@see https://github.com/alphagov/search-api/blob/master/doc/search-api.md | [
"Perform",
"a",
"search",
"returning",
"the",
"results",
"as",
"an",
"enumerator",
"."
] | 94bb27e154907939d4d96d3ab330a61c8bdf1fb5 | https://github.com/alphagov/gds-api-adapters/blob/94bb27e154907939d4d96d3ab330a61c8bdf1fb5/lib/gds_api/search.rb#L99-L112 | valid |
alphagov/gds-api-adapters | lib/gds_api/search.rb | GdsApi.Search.advanced_search | def advanced_search(args)
raise ArgumentError.new("Args cannot be blank") if args.nil? || args.empty?
request_path = "#{base_url}/advanced_search?#{Rack::Utils.build_nested_query(args)}"
get_json(request_path)
end | ruby | def advanced_search(args)
raise ArgumentError.new("Args cannot be blank") if args.nil? || args.empty?
request_path = "#{base_url}/advanced_search?#{Rack::Utils.build_nested_query(args)}"
get_json(request_path)
end | [
"def",
"advanced_search",
"(",
"args",
")",
"raise",
"ArgumentError",
".",
"new",
"(",
"\"Args cannot be blank\"",
")",
"if",
"args",
".",
"nil?",
"||",
"args",
".",
"empty?",
"request_path",
"=",
"\"#{base_url}/advanced_search?#{Rack::Utils.build_nested_query(args)}\"",
... | Advanced search.
@deprecated Only in use by Whitehall. Use the `#search` method. | [
"Advanced",
"search",
"."
] | 94bb27e154907939d4d96d3ab330a61c8bdf1fb5 | https://github.com/alphagov/gds-api-adapters/blob/94bb27e154907939d4d96d3ab330a61c8bdf1fb5/lib/gds_api/search.rb#L117-L122 | valid |
bitpay/ruby-client | lib/bitpay/rest_connector.rb | BitPay.RestConnector.process_request | def process_request(request)
request['User-Agent'] = @user_agent
request['Content-Type'] = 'application/json'
request['X-BitPay-Plugin-Info'] = 'Rubylib' + VERSION
begin
response = @https.request request
rescue => error
raise BitPay::ConnectionError, "#{error.message}"
end
if response.kind_of? Net::HTTPSuccess
return JSON.parse(response.body)
elsif JSON.parse(response.body)["error"]
raise(BitPayError, "#{response.code}: #{JSON.parse(response.body)['error']}")
else
raise BitPayError, "#{response.code}: #{JSON.parse(response.body)}"
end
end | ruby | def process_request(request)
request['User-Agent'] = @user_agent
request['Content-Type'] = 'application/json'
request['X-BitPay-Plugin-Info'] = 'Rubylib' + VERSION
begin
response = @https.request request
rescue => error
raise BitPay::ConnectionError, "#{error.message}"
end
if response.kind_of? Net::HTTPSuccess
return JSON.parse(response.body)
elsif JSON.parse(response.body)["error"]
raise(BitPayError, "#{response.code}: #{JSON.parse(response.body)['error']}")
else
raise BitPayError, "#{response.code}: #{JSON.parse(response.body)}"
end
end | [
"def",
"process_request",
"(",
"request",
")",
"request",
"[",
"'User-Agent'",
"]",
"=",
"@user_agent",
"request",
"[",
"'Content-Type'",
"]",
"=",
"'application/json'",
"request",
"[",
"'X-BitPay-Plugin-Info'",
"]",
"=",
"'Rubylib'",
"+",
"VERSION",
"begin",
"res... | Processes HTTP Request and returns parsed response
Otherwise throws error | [
"Processes",
"HTTP",
"Request",
"and",
"returns",
"parsed",
"response",
"Otherwise",
"throws",
"error"
] | 019140f04959589e7137c9b81cc1b848e15ebbe6 | https://github.com/bitpay/ruby-client/blob/019140f04959589e7137c9b81cc1b848e15ebbe6/lib/bitpay/rest_connector.rb#L59-L78 | valid |
bitpay/ruby-client | lib/bitpay/rest_connector.rb | BitPay.RestConnector.refresh_tokens | def refresh_tokens
response = get(path: 'tokens')["data"]
token_array = response || {}
tokens = {}
token_array.each do |t|
tokens[t.keys.first] = t.values.first
end
@tokens = tokens
return tokens
end | ruby | def refresh_tokens
response = get(path: 'tokens')["data"]
token_array = response || {}
tokens = {}
token_array.each do |t|
tokens[t.keys.first] = t.values.first
end
@tokens = tokens
return tokens
end | [
"def",
"refresh_tokens",
"response",
"=",
"get",
"(",
"path",
":",
"'tokens'",
")",
"[",
"\"data\"",
"]",
"token_array",
"=",
"response",
"||",
"{",
"}",
"tokens",
"=",
"{",
"}",
"token_array",
".",
"each",
"do",
"|",
"t",
"|",
"tokens",
"[",
"t",
".... | Fetches the tokens hash from the server and
updates @tokens | [
"Fetches",
"the",
"tokens",
"hash",
"from",
"the",
"server",
"and",
"updates"
] | 019140f04959589e7137c9b81cc1b848e15ebbe6 | https://github.com/bitpay/ruby-client/blob/019140f04959589e7137c9b81cc1b848e15ebbe6/lib/bitpay/rest_connector.rb#L83-L92 | valid |
rdy/fixture_builder | lib/fixture_builder/builder.rb | FixtureBuilder.Builder.fixtures_class | def fixtures_class
if defined?(ActiveRecord::FixtureSet)
ActiveRecord::FixtureSet
elsif defined?(ActiveRecord::Fixtures)
ActiveRecord::Fixtures
else
::Fixtures
end
end | ruby | def fixtures_class
if defined?(ActiveRecord::FixtureSet)
ActiveRecord::FixtureSet
elsif defined?(ActiveRecord::Fixtures)
ActiveRecord::Fixtures
else
::Fixtures
end
end | [
"def",
"fixtures_class",
"if",
"defined?",
"(",
"ActiveRecord",
"::",
"FixtureSet",
")",
"ActiveRecord",
"::",
"FixtureSet",
"elsif",
"defined?",
"(",
"ActiveRecord",
"::",
"Fixtures",
")",
"ActiveRecord",
"::",
"Fixtures",
"else",
"::",
"Fixtures",
"end",
"end"
] | Rails 3.0 and 3.1+ support | [
"Rails",
"3",
".",
"0",
"and",
"3",
".",
"1",
"+",
"support"
] | 35d3ebd7851125bd1fcfd3a71b97dc71b8c64622 | https://github.com/rdy/fixture_builder/blob/35d3ebd7851125bd1fcfd3a71b97dc71b8c64622/lib/fixture_builder/builder.rb#L36-L44 | valid |
stevenallen05/osbourne | lib/osbourne/message.rb | Osbourne.Message.sns? | def sns?
json_body.is_a?(Hash) && (%w[Message Type TopicArn MessageId] - json_body.keys).empty?
end | ruby | def sns?
json_body.is_a?(Hash) && (%w[Message Type TopicArn MessageId] - json_body.keys).empty?
end | [
"def",
"sns?",
"json_body",
".",
"is_a?",
"(",
"Hash",
")",
"&&",
"(",
"%w[",
"Message",
"Type",
"TopicArn",
"MessageId",
"]",
"-",
"json_body",
".",
"keys",
")",
".",
"empty?",
"end"
] | Just because a message was recieved via SQS, doesn't mean it was originally broadcast via SNS
@return [Boolean] Was the message broadcast via SNS? | [
"Just",
"because",
"a",
"message",
"was",
"recieved",
"via",
"SQS",
"doesn",
"t",
"mean",
"it",
"was",
"originally",
"broadcast",
"via",
"SNS"
] | b28c46ceb6e60bd685e4063d7634f5ae2e7192c9 | https://github.com/stevenallen05/osbourne/blob/b28c46ceb6e60bd685e4063d7634f5ae2e7192c9/lib/osbourne/message.rb#L78-L80 | valid |
jemmyw/Qif | lib/qif/transaction.rb | Qif.Transaction.to_s | def to_s(format = 'dd/mm/yyyy')
SUPPORTED_FIELDS.collect do |k,v|
next unless current = instance_variable_get("@#{k}")
field = v.keys.first
case current.class.to_s
when "Time", "Date", "DateTime"
"#{field}#{DateFormat.new(format).format(current)}"
when "Float"
"#{field}#{'%.2f'%current}"
when "String"
current.split("\n").collect {|x| "#{field}#{x}" }
else
"#{field}#{current}"
end
end.concat(@splits.collect{|s| s.to_s}).flatten.compact.join("\n")
end | ruby | def to_s(format = 'dd/mm/yyyy')
SUPPORTED_FIELDS.collect do |k,v|
next unless current = instance_variable_get("@#{k}")
field = v.keys.first
case current.class.to_s
when "Time", "Date", "DateTime"
"#{field}#{DateFormat.new(format).format(current)}"
when "Float"
"#{field}#{'%.2f'%current}"
when "String"
current.split("\n").collect {|x| "#{field}#{x}" }
else
"#{field}#{current}"
end
end.concat(@splits.collect{|s| s.to_s}).flatten.compact.join("\n")
end | [
"def",
"to_s",
"(",
"format",
"=",
"'dd/mm/yyyy'",
")",
"SUPPORTED_FIELDS",
".",
"collect",
"do",
"|",
"k",
",",
"v",
"|",
"next",
"unless",
"current",
"=",
"instance_variable_get",
"(",
"\"@#{k}\"",
")",
"field",
"=",
"v",
".",
"keys",
".",
"first",
"ca... | Returns a representation of the transaction as it
would appear in a qif file. | [
"Returns",
"a",
"representation",
"of",
"the",
"transaction",
"as",
"it",
"would",
"appear",
"in",
"a",
"qif",
"file",
"."
] | 87fe5ba13b980617a8b517c3f49885c6ea1b3993 | https://github.com/jemmyw/Qif/blob/87fe5ba13b980617a8b517c3f49885c6ea1b3993/lib/qif/transaction.rb#L43-L58 | valid |
zendesk/samlr | lib/samlr/signature.rb | Samlr.Signature.verify_digests! | def verify_digests!
references.each do |reference|
node = referenced_node(reference.uri)
canoned = node.canonicalize(C14N, reference.namespaces)
digest = reference.digest_method.digest(canoned)
if digest != reference.decoded_digest_value
raise SignatureError.new("Reference validation error: Digest mismatch for #{reference.uri}")
end
end
end | ruby | def verify_digests!
references.each do |reference|
node = referenced_node(reference.uri)
canoned = node.canonicalize(C14N, reference.namespaces)
digest = reference.digest_method.digest(canoned)
if digest != reference.decoded_digest_value
raise SignatureError.new("Reference validation error: Digest mismatch for #{reference.uri}")
end
end
end | [
"def",
"verify_digests!",
"references",
".",
"each",
"do",
"|",
"reference",
"|",
"node",
"=",
"referenced_node",
"(",
"reference",
".",
"uri",
")",
"canoned",
"=",
"node",
".",
"canonicalize",
"(",
"C14N",
",",
"reference",
".",
"namespaces",
")",
"digest",... | Tests that the document content has not been edited | [
"Tests",
"that",
"the",
"document",
"content",
"has",
"not",
"been",
"edited"
] | 521b5bfe4a35b6d72a780ab610dc7229294b2ea8 | https://github.com/zendesk/samlr/blob/521b5bfe4a35b6d72a780ab610dc7229294b2ea8/lib/samlr/signature.rb#L68-L78 | valid |
zendesk/samlr | lib/samlr/signature.rb | Samlr.Signature.referenced_node | def referenced_node(id)
nodes = document.xpath("//*[@ID='#{id}']")
if nodes.size != 1
raise SignatureError.new("Reference validation error: Invalid element references", "Expected 1 element with id #{id}, found #{nodes.size}")
end
nodes.first
end | ruby | def referenced_node(id)
nodes = document.xpath("//*[@ID='#{id}']")
if nodes.size != 1
raise SignatureError.new("Reference validation error: Invalid element references", "Expected 1 element with id #{id}, found #{nodes.size}")
end
nodes.first
end | [
"def",
"referenced_node",
"(",
"id",
")",
"nodes",
"=",
"document",
".",
"xpath",
"(",
"\"//*[@ID='#{id}']\"",
")",
"if",
"nodes",
".",
"size",
"!=",
"1",
"raise",
"SignatureError",
".",
"new",
"(",
"\"Reference validation error: Invalid element references\"",
",",
... | Looks up node by id, checks that there's only a single node with a given id | [
"Looks",
"up",
"node",
"by",
"id",
"checks",
"that",
"there",
"s",
"only",
"a",
"single",
"node",
"with",
"a",
"given",
"id"
] | 521b5bfe4a35b6d72a780ab610dc7229294b2ea8 | https://github.com/zendesk/samlr/blob/521b5bfe4a35b6d72a780ab610dc7229294b2ea8/lib/samlr/signature.rb#L91-L99 | valid |
zendesk/samlr | lib/samlr/response.rb | Samlr.Response.verify! | def verify!
if signature.missing? && assertion.signature.missing?
raise Samlr::SignatureError.new("Neither response nor assertion signed with a certificate")
end
signature.verify! unless signature.missing?
assertion.verify!
true
end | ruby | def verify!
if signature.missing? && assertion.signature.missing?
raise Samlr::SignatureError.new("Neither response nor assertion signed with a certificate")
end
signature.verify! unless signature.missing?
assertion.verify!
true
end | [
"def",
"verify!",
"if",
"signature",
".",
"missing?",
"&&",
"assertion",
".",
"signature",
".",
"missing?",
"raise",
"Samlr",
"::",
"SignatureError",
".",
"new",
"(",
"\"Neither response nor assertion signed with a certificate\"",
")",
"end",
"signature",
".",
"verify... | The verification process assumes that all signatures are enveloped. Since this process
is destructive the document needs to verify itself first, and then any signed assertions | [
"The",
"verification",
"process",
"assumes",
"that",
"all",
"signatures",
"are",
"enveloped",
".",
"Since",
"this",
"process",
"is",
"destructive",
"the",
"document",
"needs",
"to",
"verify",
"itself",
"first",
"and",
"then",
"any",
"signed",
"assertions"
] | 521b5bfe4a35b6d72a780ab610dc7229294b2ea8 | https://github.com/zendesk/samlr/blob/521b5bfe4a35b6d72a780ab610dc7229294b2ea8/lib/samlr/response.rb#L20-L29 | valid |
saveriomiroddi/simple_scripting | lib/simple_scripting/argv.rb | SimpleScripting.Argv.decode_definition_and_options | def decode_definition_and_options(definition_and_options)
# Only a hash (commands)
if definition_and_options.size == 1 && definition_and_options.first.is_a?(Hash)
options = definition_and_options.first.each_with_object({}) do |(key, value), current_options|
current_options[key] = definition_and_options.first.delete(key) if key.is_a?(Symbol)
end
# If there is an empty hash left, we remove it, so it's not considered commands.
#
definition_and_options = [] if definition_and_options.first.empty?
# Options passed
elsif definition_and_options.last.is_a?(Hash)
options = definition_and_options.pop
# No options passed
else
options = {}
end
[definition_and_options, options]
end | ruby | def decode_definition_and_options(definition_and_options)
# Only a hash (commands)
if definition_and_options.size == 1 && definition_and_options.first.is_a?(Hash)
options = definition_and_options.first.each_with_object({}) do |(key, value), current_options|
current_options[key] = definition_and_options.first.delete(key) if key.is_a?(Symbol)
end
# If there is an empty hash left, we remove it, so it's not considered commands.
#
definition_and_options = [] if definition_and_options.first.empty?
# Options passed
elsif definition_and_options.last.is_a?(Hash)
options = definition_and_options.pop
# No options passed
else
options = {}
end
[definition_and_options, options]
end | [
"def",
"decode_definition_and_options",
"(",
"definition_and_options",
")",
"if",
"definition_and_options",
".",
"size",
"==",
"1",
"&&",
"definition_and_options",
".",
"first",
".",
"is_a?",
"(",
"Hash",
")",
"options",
"=",
"definition_and_options",
".",
"first",
... | This is trivial to define with named arguments, however, Ruby 2.6 removed the support for
mixing strings and symbols as argument keys, so we're forced to perform manual decoding.
The complexity of this code supports the rationale for the removal of the functionality. | [
"This",
"is",
"trivial",
"to",
"define",
"with",
"named",
"arguments",
"however",
"Ruby",
"2",
".",
"6",
"removed",
"the",
"support",
"for",
"mixing",
"strings",
"and",
"symbols",
"as",
"argument",
"keys",
"so",
"we",
"re",
"forced",
"to",
"perform",
"manu... | 41f16671fe0611598741c1e719f884e057d276cd | https://github.com/saveriomiroddi/simple_scripting/blob/41f16671fe0611598741c1e719f884e057d276cd/lib/simple_scripting/argv.rb#L80-L99 | valid |
saveriomiroddi/simple_scripting | lib/simple_scripting/tab_completion.rb | SimpleScripting.TabCompletion.complete | def complete(execution_target, source_commandline=ENV.fetch('COMP_LINE'), cursor_position=ENV.fetch('COMP_POINT').to_i)
commandline_processor = CommandlineProcessor.process_commandline(source_commandline, cursor_position, @switches_definition)
if commandline_processor.completing_an_option?
complete_option(commandline_processor, execution_target)
elsif commandline_processor.parsing_error?
return
else # completing_a_value?
complete_value(commandline_processor, execution_target)
end
end | ruby | def complete(execution_target, source_commandline=ENV.fetch('COMP_LINE'), cursor_position=ENV.fetch('COMP_POINT').to_i)
commandline_processor = CommandlineProcessor.process_commandline(source_commandline, cursor_position, @switches_definition)
if commandline_processor.completing_an_option?
complete_option(commandline_processor, execution_target)
elsif commandline_processor.parsing_error?
return
else # completing_a_value?
complete_value(commandline_processor, execution_target)
end
end | [
"def",
"complete",
"(",
"execution_target",
",",
"source_commandline",
"=",
"ENV",
".",
"fetch",
"(",
"'COMP_LINE'",
")",
",",
"cursor_position",
"=",
"ENV",
".",
"fetch",
"(",
"'COMP_POINT'",
")",
".",
"to_i",
")",
"commandline_processor",
"=",
"CommandlineProc... | Currently, any completion suffix is ignored and stripped. | [
"Currently",
"any",
"completion",
"suffix",
"is",
"ignored",
"and",
"stripped",
"."
] | 41f16671fe0611598741c1e719f884e057d276cd | https://github.com/saveriomiroddi/simple_scripting/blob/41f16671fe0611598741c1e719f884e057d276cd/lib/simple_scripting/tab_completion.rb#L28-L38 | valid |
Malinskiy/danger-jacoco | lib/jacoco/plugin.rb | Danger.DangerJacoco.report | def report(path, report_url = '', delimiter = %r{\/java\/|\/kotlin\/})
setup
classes = classes(delimiter)
parser = Jacoco::SAXParser.new(classes)
Nokogiri::XML::SAX::Parser.new(parser).parse(File.open(path))
total_covered = total_coverage(path)
report_markdown = "### JaCoCO Code Coverage #{total_covered[:covered]}% #{total_covered[:status]}\n"
report_markdown << "| Class | Covered | Meta | Status |\n"
report_markdown << "|:---|:---:|:---:|:---:|\n"
class_coverage_above_minimum = markdown_class(parser, report_markdown, report_url)
markdown(report_markdown)
report_fails(class_coverage_above_minimum, total_covered)
end | ruby | def report(path, report_url = '', delimiter = %r{\/java\/|\/kotlin\/})
setup
classes = classes(delimiter)
parser = Jacoco::SAXParser.new(classes)
Nokogiri::XML::SAX::Parser.new(parser).parse(File.open(path))
total_covered = total_coverage(path)
report_markdown = "### JaCoCO Code Coverage #{total_covered[:covered]}% #{total_covered[:status]}\n"
report_markdown << "| Class | Covered | Meta | Status |\n"
report_markdown << "|:---|:---:|:---:|:---:|\n"
class_coverage_above_minimum = markdown_class(parser, report_markdown, report_url)
markdown(report_markdown)
report_fails(class_coverage_above_minimum, total_covered)
end | [
"def",
"report",
"(",
"path",
",",
"report_url",
"=",
"''",
",",
"delimiter",
"=",
"%r{",
"\\/",
"\\/",
"\\/",
"\\/",
"}",
")",
"setup",
"classes",
"=",
"classes",
"(",
"delimiter",
")",
"parser",
"=",
"Jacoco",
"::",
"SAXParser",
".",
"new",
"(",
"c... | This is a fast report based on SAX parser
@path path to the xml output of jacoco
@report_url URL where html report hosted
@delimiter git.modified_files returns full paths to the
changed files. We need to get the class from this path to check the
Jacoco report,
e.g. src/java/com/example/SomeJavaClass.java -> com/example/SomeJavaClass
e.g. src/kotlin/com/example/SomeKotlinClass.kt -> com/example/SomeKotlinClass
The default value supposes that you're using gradle structure,
that is your path to source files is something like
Java => blah/blah/java/slashed_package/Source.java
Kotlin => blah/blah/kotlin/slashed_package/Source.kt | [
"This",
"is",
"a",
"fast",
"report",
"based",
"on",
"SAX",
"parser"
] | a3ef27173e5b231204409cb8a8eb40e9662cd161 | https://github.com/Malinskiy/danger-jacoco/blob/a3ef27173e5b231204409cb8a8eb40e9662cd161/lib/jacoco/plugin.rb#L47-L63 | valid |
Malinskiy/danger-jacoco | lib/jacoco/plugin.rb | Danger.DangerJacoco.classes | def classes(delimiter)
git = @dangerfile.git
affected_files = git.modified_files + git.added_files
affected_files.select { |file| files_extension.reduce(false) { |state, el| state || file.end_with?(el) } }
.map { |file| file.split('.').first.split(delimiter)[1] }
end | ruby | def classes(delimiter)
git = @dangerfile.git
affected_files = git.modified_files + git.added_files
affected_files.select { |file| files_extension.reduce(false) { |state, el| state || file.end_with?(el) } }
.map { |file| file.split('.').first.split(delimiter)[1] }
end | [
"def",
"classes",
"(",
"delimiter",
")",
"git",
"=",
"@dangerfile",
".",
"git",
"affected_files",
"=",
"git",
".",
"modified_files",
"+",
"git",
".",
"added_files",
"affected_files",
".",
"select",
"{",
"|",
"file",
"|",
"files_extension",
".",
"reduce",
"("... | Select modified and added files in this PR | [
"Select",
"modified",
"and",
"added",
"files",
"in",
"this",
"PR"
] | a3ef27173e5b231204409cb8a8eb40e9662cd161 | https://github.com/Malinskiy/danger-jacoco/blob/a3ef27173e5b231204409cb8a8eb40e9662cd161/lib/jacoco/plugin.rb#L66-L71 | valid |
Malinskiy/danger-jacoco | lib/jacoco/plugin.rb | Danger.DangerJacoco.report_class | def report_class(jacoco_class)
counter = coverage_counter(jacoco_class)
coverage = (counter.covered.fdiv(counter.covered + counter.missed) * 100).floor
required_coverage = minimum_class_coverage_map[jacoco_class.name]
required_coverage = minimum_class_coverage_percentage if required_coverage.nil?
status = coverage_status(coverage, required_coverage)
{
covered: coverage,
status: status,
required_coverage_percentage: required_coverage
}
end | ruby | def report_class(jacoco_class)
counter = coverage_counter(jacoco_class)
coverage = (counter.covered.fdiv(counter.covered + counter.missed) * 100).floor
required_coverage = minimum_class_coverage_map[jacoco_class.name]
required_coverage = minimum_class_coverage_percentage if required_coverage.nil?
status = coverage_status(coverage, required_coverage)
{
covered: coverage,
status: status,
required_coverage_percentage: required_coverage
}
end | [
"def",
"report_class",
"(",
"jacoco_class",
")",
"counter",
"=",
"coverage_counter",
"(",
"jacoco_class",
")",
"coverage",
"=",
"(",
"counter",
".",
"covered",
".",
"fdiv",
"(",
"counter",
".",
"covered",
"+",
"counter",
".",
"missed",
")",
"*",
"100",
")"... | It returns a specific class code coverage and an emoji status as well | [
"It",
"returns",
"a",
"specific",
"class",
"code",
"coverage",
"and",
"an",
"emoji",
"status",
"as",
"well"
] | a3ef27173e5b231204409cb8a8eb40e9662cd161 | https://github.com/Malinskiy/danger-jacoco/blob/a3ef27173e5b231204409cb8a8eb40e9662cd161/lib/jacoco/plugin.rb#L74-L86 | valid |
Malinskiy/danger-jacoco | lib/jacoco/plugin.rb | Danger.DangerJacoco.total_coverage | def total_coverage(report_path)
jacoco_report = Nokogiri::XML(File.open(report_path))
report = jacoco_report.xpath('report/counter').select { |item| item['type'] == 'INSTRUCTION' }
missed_instructions = report.first['missed'].to_f
covered_instructions = report.first['covered'].to_f
total_instructions = missed_instructions + covered_instructions
covered_percentage = (covered_instructions * 100 / total_instructions).round(2)
coverage_status = coverage_status(covered_percentage, minimum_project_coverage_percentage)
{
covered: covered_percentage,
status: coverage_status
}
end | ruby | def total_coverage(report_path)
jacoco_report = Nokogiri::XML(File.open(report_path))
report = jacoco_report.xpath('report/counter').select { |item| item['type'] == 'INSTRUCTION' }
missed_instructions = report.first['missed'].to_f
covered_instructions = report.first['covered'].to_f
total_instructions = missed_instructions + covered_instructions
covered_percentage = (covered_instructions * 100 / total_instructions).round(2)
coverage_status = coverage_status(covered_percentage, minimum_project_coverage_percentage)
{
covered: covered_percentage,
status: coverage_status
}
end | [
"def",
"total_coverage",
"(",
"report_path",
")",
"jacoco_report",
"=",
"Nokogiri",
"::",
"XML",
"(",
"File",
".",
"open",
"(",
"report_path",
")",
")",
"report",
"=",
"jacoco_report",
".",
"xpath",
"(",
"'report/counter'",
")",
".",
"select",
"{",
"|",
"i... | It returns total of project code coverage and an emoji status as well | [
"It",
"returns",
"total",
"of",
"project",
"code",
"coverage",
"and",
"an",
"emoji",
"status",
"as",
"well"
] | a3ef27173e5b231204409cb8a8eb40e9662cd161 | https://github.com/Malinskiy/danger-jacoco/blob/a3ef27173e5b231204409cb8a8eb40e9662cd161/lib/jacoco/plugin.rb#L97-L111 | valid |
matadon/mizuno | lib/mizuno/server.rb | Mizuno.Server.rewindable | def rewindable(request)
input = request.getInputStream
@options[:rewindable] ?
Rack::RewindableInput.new(input.to_io.binmode) :
RewindableInputStream.new(input).to_io.binmode
end | ruby | def rewindable(request)
input = request.getInputStream
@options[:rewindable] ?
Rack::RewindableInput.new(input.to_io.binmode) :
RewindableInputStream.new(input).to_io.binmode
end | [
"def",
"rewindable",
"(",
"request",
")",
"input",
"=",
"request",
".",
"getInputStream",
"@options",
"[",
":rewindable",
"]",
"?",
"Rack",
"::",
"RewindableInput",
".",
"new",
"(",
"input",
".",
"to_io",
".",
"binmode",
")",
":",
"RewindableInputStream",
".... | Wraps the Java InputStream for the level of Rack compliance
desired. | [
"Wraps",
"the",
"Java",
"InputStream",
"for",
"the",
"level",
"of",
"Rack",
"compliance",
"desired",
"."
] | 506beb09571f0398d5851366d3c9779c14b061fb | https://github.com/matadon/mizuno/blob/506beb09571f0398d5851366d3c9779c14b061fb/lib/mizuno/server.rb#L145-L151 | valid |
matadon/mizuno | lib/mizuno/rack_handler.rb | Mizuno.RackHandler.servlet_to_rack | def servlet_to_rack(request)
# The Rack request that we will pass on.
env = Hash.new
# Map Servlet bits to Rack bits.
env['REQUEST_METHOD'] = request.getMethod
env['QUERY_STRING'] = request.getQueryString.to_s
env['SERVER_NAME'] = request.getServerName
env['SERVER_PORT'] = request.getServerPort.to_s
env['rack.version'] = Rack::VERSION
env['rack.url_scheme'] = request.getScheme
env['HTTP_VERSION'] = request.getProtocol
env["SERVER_PROTOCOL"] = request.getProtocol
env['REMOTE_ADDR'] = request.getRemoteAddr
env['REMOTE_HOST'] = request.getRemoteHost
# request.getPathInfo seems to be blank, so we're using the URI.
env['REQUEST_PATH'] = request.getRequestURI
env['PATH_INFO'] = request.getRequestURI
env['SCRIPT_NAME'] = ""
# Rack says URI, but it hands off a URL.
env['REQUEST_URI'] = request.getRequestURL.to_s
# Java chops off the query string, but a Rack application will
# expect it, so we'll add it back if present
env['REQUEST_URI'] << "?#{env['QUERY_STRING']}" \
if env['QUERY_STRING']
# JRuby is like the matrix, only there's no spoon or fork().
env['rack.multiprocess'] = false
env['rack.multithread'] = true
env['rack.run_once'] = false
# The input stream is a wrapper around the Java InputStream.
env['rack.input'] = @server.rewindable(request)
# Force encoding if we're on Ruby 1.9
env['rack.input'].set_encoding(Encoding.find("ASCII-8BIT")) \
if env['rack.input'].respond_to?(:set_encoding)
# Populate the HTTP headers.
request.getHeaderNames.each do |header_name|
header = header_name.to_s.upcase.tr('-', '_')
env["HTTP_#{header}"] = request.getHeader(header_name)
end
# Rack Weirdness: HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH
# both need to have the HTTP_ part dropped.
env["CONTENT_TYPE"] = env.delete("HTTP_CONTENT_TYPE") \
if env["HTTP_CONTENT_TYPE"]
env["CONTENT_LENGTH"] = env.delete("HTTP_CONTENT_LENGTH") \
if env["HTTP_CONTENT_LENGTH"]
# Route errors through the logger.
env['rack.errors'] ||= @server.logger
env['rack.logger'] ||= @server.logger
# All done, hand back the Rack request.
return(env)
end | ruby | def servlet_to_rack(request)
# The Rack request that we will pass on.
env = Hash.new
# Map Servlet bits to Rack bits.
env['REQUEST_METHOD'] = request.getMethod
env['QUERY_STRING'] = request.getQueryString.to_s
env['SERVER_NAME'] = request.getServerName
env['SERVER_PORT'] = request.getServerPort.to_s
env['rack.version'] = Rack::VERSION
env['rack.url_scheme'] = request.getScheme
env['HTTP_VERSION'] = request.getProtocol
env["SERVER_PROTOCOL"] = request.getProtocol
env['REMOTE_ADDR'] = request.getRemoteAddr
env['REMOTE_HOST'] = request.getRemoteHost
# request.getPathInfo seems to be blank, so we're using the URI.
env['REQUEST_PATH'] = request.getRequestURI
env['PATH_INFO'] = request.getRequestURI
env['SCRIPT_NAME'] = ""
# Rack says URI, but it hands off a URL.
env['REQUEST_URI'] = request.getRequestURL.to_s
# Java chops off the query string, but a Rack application will
# expect it, so we'll add it back if present
env['REQUEST_URI'] << "?#{env['QUERY_STRING']}" \
if env['QUERY_STRING']
# JRuby is like the matrix, only there's no spoon or fork().
env['rack.multiprocess'] = false
env['rack.multithread'] = true
env['rack.run_once'] = false
# The input stream is a wrapper around the Java InputStream.
env['rack.input'] = @server.rewindable(request)
# Force encoding if we're on Ruby 1.9
env['rack.input'].set_encoding(Encoding.find("ASCII-8BIT")) \
if env['rack.input'].respond_to?(:set_encoding)
# Populate the HTTP headers.
request.getHeaderNames.each do |header_name|
header = header_name.to_s.upcase.tr('-', '_')
env["HTTP_#{header}"] = request.getHeader(header_name)
end
# Rack Weirdness: HTTP_CONTENT_TYPE and HTTP_CONTENT_LENGTH
# both need to have the HTTP_ part dropped.
env["CONTENT_TYPE"] = env.delete("HTTP_CONTENT_TYPE") \
if env["HTTP_CONTENT_TYPE"]
env["CONTENT_LENGTH"] = env.delete("HTTP_CONTENT_LENGTH") \
if env["HTTP_CONTENT_LENGTH"]
# Route errors through the logger.
env['rack.errors'] ||= @server.logger
env['rack.logger'] ||= @server.logger
# All done, hand back the Rack request.
return(env)
end | [
"def",
"servlet_to_rack",
"(",
"request",
")",
"env",
"=",
"Hash",
".",
"new",
"env",
"[",
"'REQUEST_METHOD'",
"]",
"=",
"request",
".",
"getMethod",
"env",
"[",
"'QUERY_STRING'",
"]",
"=",
"request",
".",
"getQueryString",
".",
"to_s",
"env",
"[",
"'SERVE... | Turns a Servlet request into a Rack request hash. | [
"Turns",
"a",
"Servlet",
"request",
"into",
"a",
"Rack",
"request",
"hash",
"."
] | 506beb09571f0398d5851366d3c9779c14b061fb | https://github.com/matadon/mizuno/blob/506beb09571f0398d5851366d3c9779c14b061fb/lib/mizuno/rack_handler.rb#L100-L160 | valid |
matadon/mizuno | lib/mizuno/rack_handler.rb | Mizuno.RackHandler.handle_exceptions | def handle_exceptions(response)
begin
yield
rescue => error
message = "Exception: #{error}"
message << "\n#{error.backtrace.join("\n")}" \
if (error.respond_to?(:backtrace))
Server.logger.error(message)
return if response.isCommitted
response.reset
response.setStatus(500)
end
end | ruby | def handle_exceptions(response)
begin
yield
rescue => error
message = "Exception: #{error}"
message << "\n#{error.backtrace.join("\n")}" \
if (error.respond_to?(:backtrace))
Server.logger.error(message)
return if response.isCommitted
response.reset
response.setStatus(500)
end
end | [
"def",
"handle_exceptions",
"(",
"response",
")",
"begin",
"yield",
"rescue",
"=>",
"error",
"message",
"=",
"\"Exception: #{error}\"",
"message",
"<<",
"\"\\n#{error.backtrace.join(\"\\n\")}\"",
"if",
"(",
"error",
".",
"respond_to?",
"(",
":backtrace",
")",
")",
"... | Handle exceptions, returning a generic 500 error response. | [
"Handle",
"exceptions",
"returning",
"a",
"generic",
"500",
"error",
"response",
"."
] | 506beb09571f0398d5851366d3c9779c14b061fb | https://github.com/matadon/mizuno/blob/506beb09571f0398d5851366d3c9779c14b061fb/lib/mizuno/rack_handler.rb#L244-L256 | valid |
matadon/mizuno | lib/mizuno/reloader.rb | Mizuno.Reloader.find_files_for_reload | def find_files_for_reload
paths = [ './', *$LOAD_PATH ].uniq
[ $0, *$LOADED_FEATURES ].uniq.map do |file|
next if file =~ /\.(so|bundle)$/
yield(find(file, paths))
end
end | ruby | def find_files_for_reload
paths = [ './', *$LOAD_PATH ].uniq
[ $0, *$LOADED_FEATURES ].uniq.map do |file|
next if file =~ /\.(so|bundle)$/
yield(find(file, paths))
end
end | [
"def",
"find_files_for_reload",
"paths",
"=",
"[",
"'./'",
",",
"*",
"$LOAD_PATH",
"]",
".",
"uniq",
"[",
"$0",
",",
"*",
"$LOADED_FEATURES",
"]",
".",
"uniq",
".",
"map",
"do",
"|",
"file",
"|",
"next",
"if",
"file",
"=~",
"/",
"\\.",
"/",
"yield",
... | Walk through the list of every file we've loaded. | [
"Walk",
"through",
"the",
"list",
"of",
"every",
"file",
"we",
"ve",
"loaded",
"."
] | 506beb09571f0398d5851366d3c9779c14b061fb | https://github.com/matadon/mizuno/blob/506beb09571f0398d5851366d3c9779c14b061fb/lib/mizuno/reloader.rb#L91-L97 | valid |
matadon/mizuno | lib/mizuno/reloader.rb | Mizuno.Reloader.find | def find(file, paths)
if(Pathname.new(file).absolute?)
return unless (timestamp = mtime(file))
@logger.debug("Found #{file}")
[ file, timestamp ]
else
paths.each do |path|
fullpath = File.expand_path((File.join(path, file)))
next unless (timestamp = mtime(fullpath))
@logger.debug("Found #{file} in #{fullpath}")
return([ fullpath, timestamp ])
end
return(nil)
end
end | ruby | def find(file, paths)
if(Pathname.new(file).absolute?)
return unless (timestamp = mtime(file))
@logger.debug("Found #{file}")
[ file, timestamp ]
else
paths.each do |path|
fullpath = File.expand_path((File.join(path, file)))
next unless (timestamp = mtime(fullpath))
@logger.debug("Found #{file} in #{fullpath}")
return([ fullpath, timestamp ])
end
return(nil)
end
end | [
"def",
"find",
"(",
"file",
",",
"paths",
")",
"if",
"(",
"Pathname",
".",
"new",
"(",
"file",
")",
".",
"absolute?",
")",
"return",
"unless",
"(",
"timestamp",
"=",
"mtime",
"(",
"file",
")",
")",
"@logger",
".",
"debug",
"(",
"\"Found #{file}\"",
"... | Takes a relative or absolute +file+ name, a couple possible
+paths+ that the +file+ might reside in. Returns a tuple of
the full path where the file was found and its modification
time, or nil if not found. | [
"Takes",
"a",
"relative",
"or",
"absolute",
"+",
"file",
"+",
"name",
"a",
"couple",
"possible",
"+",
"paths",
"+",
"that",
"the",
"+",
"file",
"+",
"might",
"reside",
"in",
".",
"Returns",
"a",
"tuple",
"of",
"the",
"full",
"path",
"where",
"the",
"... | 506beb09571f0398d5851366d3c9779c14b061fb | https://github.com/matadon/mizuno/blob/506beb09571f0398d5851366d3c9779c14b061fb/lib/mizuno/reloader.rb#L120-L134 | valid |
matadon/mizuno | lib/mizuno/reloader.rb | Mizuno.Reloader.mtime | def mtime(file)
begin
return unless file
stat = File.stat(file)
stat.file? ? stat.mtime.to_i : nil
rescue Errno::ENOENT, Errno::ENOTDIR, Errno::ESRCH
nil
end
end | ruby | def mtime(file)
begin
return unless file
stat = File.stat(file)
stat.file? ? stat.mtime.to_i : nil
rescue Errno::ENOENT, Errno::ENOTDIR, Errno::ESRCH
nil
end
end | [
"def",
"mtime",
"(",
"file",
")",
"begin",
"return",
"unless",
"file",
"stat",
"=",
"File",
".",
"stat",
"(",
"file",
")",
"stat",
".",
"file?",
"?",
"stat",
".",
"mtime",
".",
"to_i",
":",
"nil",
"rescue",
"Errno",
"::",
"ENOENT",
",",
"Errno",
":... | Returns the modification time of _file_. | [
"Returns",
"the",
"modification",
"time",
"of",
"_file_",
"."
] | 506beb09571f0398d5851366d3c9779c14b061fb | https://github.com/matadon/mizuno/blob/506beb09571f0398d5851366d3c9779c14b061fb/lib/mizuno/reloader.rb#L139-L147 | valid |
namely/ruby-client | lib/namely/collection.rb | Namely.Collection.find | def find(id)
build(resource_gateway.json_show(id))
rescue RestClient::ResourceNotFound
raise NoSuchModelError, "Can't find any #{endpoint} with id \"#{id}\""
end | ruby | def find(id)
build(resource_gateway.json_show(id))
rescue RestClient::ResourceNotFound
raise NoSuchModelError, "Can't find any #{endpoint} with id \"#{id}\""
end | [
"def",
"find",
"(",
"id",
")",
"build",
"(",
"resource_gateway",
".",
"json_show",
"(",
"id",
")",
")",
"rescue",
"RestClient",
"::",
"ResourceNotFound",
"raise",
"NoSuchModelError",
",",
"\"Can't find any #{endpoint} with id \\\"#{id}\\\"\"",
"end"
] | Fetch a model from the server by its ID.
@param [#to_s] id
@raise [NoSuchModelError] if the model wasn't found.
@return [Model] | [
"Fetch",
"a",
"model",
"from",
"the",
"server",
"by",
"its",
"ID",
"."
] | 6483b15ebbe12c1c1312cf558023f9244146e103 | https://github.com/namely/ruby-client/blob/6483b15ebbe12c1c1312cf558023f9244146e103/lib/namely/collection.rb#L68-L72 | valid |
namely/ruby-client | lib/namely/authenticator.rb | Namely.Authenticator.authorization_code_url | def authorization_code_url(options)
URL.new(options.merge(
path: "/api/v1/oauth2/authorize",
params: {
response_type: "code",
approve: "true",
client_id: client_id,
},
)).to_s
end | ruby | def authorization_code_url(options)
URL.new(options.merge(
path: "/api/v1/oauth2/authorize",
params: {
response_type: "code",
approve: "true",
client_id: client_id,
},
)).to_s
end | [
"def",
"authorization_code_url",
"(",
"options",
")",
"URL",
".",
"new",
"(",
"options",
".",
"merge",
"(",
"path",
":",
"\"/api/v1/oauth2/authorize\"",
",",
"params",
":",
"{",
"response_type",
":",
"\"code\"",
",",
"approve",
":",
"\"true\"",
",",
"client_id... | Return a new Authenticator instance.
@param [Hash] options
@option options [String] client_id
@option options [String] client_secret
@example
authenticator = Authenticator.new(
client_id: "my-client-id",
client_secret: "my-client-secret"
)
@return [Authenticator]
Returns a URL to begin the authorization code workflow. If you
provide a redirect_uri you can receive the server's response.
@param [Hash] options
@option options [String] host (optional)
@option options [String] protocol (optional, defaults to "https")
@option options [String] subdomain (required)
@option options [String] redirect_uri (optional)
@return [String] | [
"Return",
"a",
"new",
"Authenticator",
"instance",
"."
] | 6483b15ebbe12c1c1312cf558023f9244146e103 | https://github.com/namely/ruby-client/blob/6483b15ebbe12c1c1312cf558023f9244146e103/lib/namely/authenticator.rb#L33-L42 | valid |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.