id
int32
0
24.9k
repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
14,700
flyerhzm/rails_best_practices
lib/rails_best_practices/analyzer.rb
RailsBestPractices.Analyzer.analyze_source_codes
def analyze_source_codes @bar = ProgressBar.create(title: 'Source Code', total: parse_files.size * 3) if display_bar? %w[lexical prepare review].each { |process| send(:process, process) } @bar.finish if display_bar? end
ruby
def analyze_source_codes @bar = ProgressBar.create(title: 'Source Code', total: parse_files.size * 3) if display_bar? %w[lexical prepare review].each { |process| send(:process, process) } @bar.finish if display_bar? end
[ "def", "analyze_source_codes", "@bar", "=", "ProgressBar", ".", "create", "(", "title", ":", "'Source Code'", ",", "total", ":", "parse_files", ".", "size", "*", "3", ")", "if", "display_bar?", "%w[", "lexical", "prepare", "review", "]", ".", "each", "{", ...
analyze source codes.
[ "analyze", "source", "codes", "." ]
c1a4c1e111ec4c804ed3e7b194bf026d93523048
https://github.com/flyerhzm/rails_best_practices/blob/c1a4c1e111ec4c804ed3e7b194bf026d93523048/lib/rails_best_practices/analyzer.rb#L317-L321
14,701
wardencommunity/warden
lib/warden/hooks.rb
Warden.Hooks._run_callbacks
def _run_callbacks(kind, *args) #:nodoc: options = args.last # Last callback arg MUST be a Hash send("_#{kind}").each do |callback, conditions| invalid = conditions.find do |key, value| value.is_a?(Array) ? !value.include?(options[key]) : (value != options[key]) end callb...
ruby
def _run_callbacks(kind, *args) #:nodoc: options = args.last # Last callback arg MUST be a Hash send("_#{kind}").each do |callback, conditions| invalid = conditions.find do |key, value| value.is_a?(Array) ? !value.include?(options[key]) : (value != options[key]) end callb...
[ "def", "_run_callbacks", "(", "kind", ",", "*", "args", ")", "#:nodoc:", "options", "=", "args", ".", "last", "# Last callback arg MUST be a Hash", "send", "(", "\"_#{kind}\"", ")", ".", "each", "do", "|", "callback", ",", "conditions", "|", "invalid", "=", ...
Hook to _run_callbacks asserting for conditions.
[ "Hook", "to", "_run_callbacks", "asserting", "for", "conditions", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/hooks.rb#L7-L17
14,702
wardencommunity/warden
lib/warden/hooks.rb
Warden.Hooks.after_failed_fetch
def after_failed_fetch(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _after_failed_fetch.send(method, [block, options]) end
ruby
def after_failed_fetch(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _after_failed_fetch.send(method, [block, options]) end
[ "def", "after_failed_fetch", "(", "options", "=", "{", "}", ",", "method", "=", ":push", ",", "&", "block", ")", "raise", "BlockNotGiven", "unless", "block_given?", "_after_failed_fetch", ".", "send", "(", "method", ",", "[", "block", ",", "options", "]", ...
A callback that runs if no user could be fetched, meaning there is now no user logged in. Parameters: <options> Some options which specify when the callback should be executed scope - Executes the callback only if it matches the scope(s) given <block> A block to contain logic for the callback Block Parameter...
[ "A", "callback", "that", "runs", "if", "no", "user", "could", "be", "fetched", "meaning", "there", "is", "now", "no", "user", "logged", "in", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/hooks.rb#L138-L141
14,703
wardencommunity/warden
lib/warden/hooks.rb
Warden.Hooks.before_logout
def before_logout(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _before_logout.send(method, [block, options]) end
ruby
def before_logout(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _before_logout.send(method, [block, options]) end
[ "def", "before_logout", "(", "options", "=", "{", "}", ",", "method", "=", ":push", ",", "&", "block", ")", "raise", "BlockNotGiven", "unless", "block_given?", "_before_logout", ".", "send", "(", "method", ",", "[", "block", ",", "options", "]", ")", "en...
A callback that runs just prior to the logout of each scope. Parameters: <options> Some options which specify when the callback should be executed scope - Executes the callback only if it matches the scope(s) given <block> A block to contain logic for the callback Block Parameters: |user, auth, scope| u...
[ "A", "callback", "that", "runs", "just", "prior", "to", "the", "logout", "of", "each", "scope", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/hooks.rb#L166-L169
14,704
wardencommunity/warden
lib/warden/hooks.rb
Warden.Hooks.on_request
def on_request(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _on_request.send(method, [block, options]) end
ruby
def on_request(options = {}, method = :push, &block) raise BlockNotGiven unless block_given? _on_request.send(method, [block, options]) end
[ "def", "on_request", "(", "options", "=", "{", "}", ",", "method", "=", ":push", ",", "&", "block", ")", "raise", "BlockNotGiven", "unless", "block_given?", "_on_request", ".", "send", "(", "method", ",", "[", "block", ",", "options", "]", ")", "end" ]
A callback that runs on each request, just after the proxy is initialized Parameters: <block> A block to contain logic for the callback Block Parameters: |proxy| proxy - The warden proxy object for the request Example: user = "A User" Warden::Manager.on_request do |proxy| proxy.set_user = user ...
[ "A", "callback", "that", "runs", "on", "each", "request", "just", "after", "the", "proxy", "is", "initialized" ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/hooks.rb#L191-L194
14,705
wardencommunity/warden
lib/warden/proxy.rb
Warden.Proxy.user
def user(argument = {}) opts = argument.is_a?(Hash) ? argument : { :scope => argument } scope = (opts[:scope] ||= @config.default_scope) if @users.has_key?(scope) @users[scope] else unless user = session_serializer.fetch(scope) run_callbacks = opts.fetch(:run_callback...
ruby
def user(argument = {}) opts = argument.is_a?(Hash) ? argument : { :scope => argument } scope = (opts[:scope] ||= @config.default_scope) if @users.has_key?(scope) @users[scope] else unless user = session_serializer.fetch(scope) run_callbacks = opts.fetch(:run_callback...
[ "def", "user", "(", "argument", "=", "{", "}", ")", "opts", "=", "argument", ".", "is_a?", "(", "Hash", ")", "?", "argument", ":", "{", ":scope", "=>", "argument", "}", "scope", "=", "(", "opts", "[", ":scope", "]", "||=", "@config", ".", "default_...
Provides access to the user object in a given scope for a request. Will be nil if not logged in. Please notice that this method does not perform strategies. Example: # without scope (default user) env['warden'].user # with scope env['warden'].user(:admin) # as a Hash env['warden'].user(:scope =>...
[ "Provides", "access", "to", "the", "user", "object", "in", "a", "given", "scope", "for", "a", "request", ".", "Will", "be", "nil", "if", "not", "logged", "in", ".", "Please", "notice", "that", "this", "method", "does", "not", "perform", "strategies", "."...
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/proxy.rb#L217-L231
14,706
wardencommunity/warden
lib/warden/proxy.rb
Warden.Proxy.logout
def logout(*scopes) if scopes.empty? scopes = @users.keys reset_session = true end scopes.each do |scope| user = @users.delete(scope) manager._run_callbacks(:before_logout, user, self, :scope => scope) raw_session.delete("warden.user.#{scope}.session") unless ...
ruby
def logout(*scopes) if scopes.empty? scopes = @users.keys reset_session = true end scopes.each do |scope| user = @users.delete(scope) manager._run_callbacks(:before_logout, user, self, :scope => scope) raw_session.delete("warden.user.#{scope}.session") unless ...
[ "def", "logout", "(", "*", "scopes", ")", "if", "scopes", ".", "empty?", "scopes", "=", "@users", ".", "keys", "reset_session", "=", "true", "end", "scopes", ".", "each", "do", "|", "scope", "|", "user", "=", "@users", ".", "delete", "(", "scope", ")...
Provides logout functionality. The logout also manages any authenticated data storage and clears it when a user logs out. Parameters: scopes - a list of scopes to logout Example: # Logout everyone and clear the session env['warden'].logout # Logout the default user but leave the rest of the session alone...
[ "Provides", "logout", "functionality", ".", "The", "logout", "also", "manages", "any", "authenticated", "data", "storage", "and", "clears", "it", "when", "a", "user", "logs", "out", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/proxy.rb#L266-L281
14,707
wardencommunity/warden
lib/warden/proxy.rb
Warden.Proxy._run_strategies_for
def _run_strategies_for(scope, args) #:nodoc: self.winning_strategy = @winning_strategies[scope] return if winning_strategy && winning_strategy.halted? # Do not run any strategy if locked return if @locked if args.empty? defaults = @config[:default_strategies] strategie...
ruby
def _run_strategies_for(scope, args) #:nodoc: self.winning_strategy = @winning_strategies[scope] return if winning_strategy && winning_strategy.halted? # Do not run any strategy if locked return if @locked if args.empty? defaults = @config[:default_strategies] strategie...
[ "def", "_run_strategies_for", "(", "scope", ",", "args", ")", "#:nodoc:", "self", ".", "winning_strategy", "=", "@winning_strategies", "[", "scope", "]", "return", "if", "winning_strategy", "&&", "winning_strategy", ".", "halted?", "# Do not run any strategy if locked",...
Run the strategies for a given scope
[ "Run", "the", "strategies", "for", "a", "given", "scope" ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/proxy.rb#L353-L373
14,708
wardencommunity/warden
lib/warden/proxy.rb
Warden.Proxy._fetch_strategy
def _fetch_strategy(name, scope) @strategies[scope][name] ||= if klass = Warden::Strategies[name] klass.new(@env, scope) elsif @config.silence_missing_strategies? nil else raise "Invalid strategy #{name}" end end
ruby
def _fetch_strategy(name, scope) @strategies[scope][name] ||= if klass = Warden::Strategies[name] klass.new(@env, scope) elsif @config.silence_missing_strategies? nil else raise "Invalid strategy #{name}" end end
[ "def", "_fetch_strategy", "(", "name", ",", "scope", ")", "@strategies", "[", "scope", "]", "[", "name", "]", "||=", "if", "klass", "=", "Warden", "::", "Strategies", "[", "name", "]", "klass", ".", "new", "(", "@env", ",", "scope", ")", "elsif", "@c...
Fetches strategies and keep them in a hash cache.
[ "Fetches", "strategies", "and", "keep", "them", "in", "a", "hash", "cache", "." ]
b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c
https://github.com/wardencommunity/warden/blob/b7ff0f4ffacd7ad5a9b5a0191f1da0c7a64b2c2c/lib/warden/proxy.rb#L376-L384
14,709
qpowell/google_places
lib/google_places/request.rb
GooglePlaces.Request.parsed_response
def parsed_response return @response.headers["location"] if @response.code >= 300 && @response.code < 400 raise APIConnectionError.new(@response) if @response.code >= 500 && @response.code < 600 case @response.parsed_response['status'] when 'OK', 'ZERO_RESULTS' @response.parsed_response ...
ruby
def parsed_response return @response.headers["location"] if @response.code >= 300 && @response.code < 400 raise APIConnectionError.new(@response) if @response.code >= 500 && @response.code < 600 case @response.parsed_response['status'] when 'OK', 'ZERO_RESULTS' @response.parsed_response ...
[ "def", "parsed_response", "return", "@response", ".", "headers", "[", "\"location\"", "]", "if", "@response", ".", "code", ">=", "300", "&&", "@response", ".", "code", "<", "400", "raise", "APIConnectionError", ".", "new", "(", "@response", ")", "if", "@resp...
Parse errors from the server respons, if any @raise [OverQueryLimitError] when server response object includes status 'OVER_QUERY_LIMIT' @raise [RequestDeniedError] when server response object includes 'REQUEST_DENIED' @raise [InvalidRequestError] when server response object includes 'INVALID_REQUEST' @raise [Unkno...
[ "Parse", "errors", "from", "the", "server", "respons", "if", "any" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/request.rb#L361-L378
14,710
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots
def spots(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list(lat, lng, @api_key, options), detail ) end
ruby
def spots(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list(lat, lng, @api_key, options), detail ) end
[ "def", "spots", "(", "lat", ",", "lng", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list"...
Creates a new Client instance which proxies the requests to the certain classes @param [String] api_key The api key to use for the requests @param [Hash] options An options hash for requests. Is used as the query parameters on server requests @option options [String,Integer] lat the latitude for the search @opt...
[ "Creates", "a", "new", "Client", "instance", "which", "proxies", "the", "requests", "to", "the", "certain", "classes" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L95-L102
14,711
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots_by_query
def spots_by_query(query, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_query(query, @api_key, options), detail ) end
ruby
def spots_by_query(query, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_query(query, @api_key, options), detail ) end
[ "def", "spots_by_query", "(", "query", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list_by_qu...
Search for Spots with a query @return [Array<Spot>] @param [String] query the query to search for @param [Hash] options @option options [String,Integer] lat the latitude for the search @option options [String,Integer] lng the longitude for the search @option options [Integer] :radius (1000) Defines the distan...
[ "Search", "for", "Spots", "with", "a", "query" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L160-L167
14,712
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots_by_bounds
def spots_by_bounds(bounds, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_bounds(bounds, @api_key, options), detail ) end
ruby
def spots_by_bounds(bounds, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_bounds(bounds, @api_key, options), detail ) end
[ "def", "spots_by_bounds", "(", "bounds", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "list_by_...
Search for Spots within a give SW|NE bounds with query @return [Array<Spot>] @param [Hash] bounds @param [String] api_key the provided api key @param [Hash] options @option bounds [String, Array] :start_point An array that contains the lat/lng pair for the first point in the bounds (rectangle) @option bo...
[ "Search", "for", "Spots", "within", "a", "give", "SW|NE", "bounds", "with", "query" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L204-L211
14,713
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots_by_pagetoken
def spots_by_pagetoken(pagetoken, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_pagetoken(pagetoken, @api_key, options), detail ) end
ruby
def spots_by_pagetoken(pagetoken, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_pagetoken(pagetoken, @api_key, options), detail ) end
[ "def", "spots_by_pagetoken", "(", "pagetoken", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".", "li...
Search for Spots with a pagetoken @return [Array<Spot>] @param [String] pagetoken the next page token to search for @param [Hash] options @option options [String,Array<String>] :exclude ([]) A String or an Array of <b>types</b> to exclude from results @option options [Hash] :retry_options ({}) A Hash contai...
[ "Search", "for", "Spots", "with", "a", "pagetoken" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L229-L236
14,714
qpowell/google_places
lib/google_places/client.rb
GooglePlaces.Client.spots_by_radar
def spots_by_radar(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_radar(lat, lng, @api_key, options), detail ) end
ruby
def spots_by_radar(lat, lng, options = {}) options = @options.merge(options) detail = options.delete(:detail) collection_detail_level( Spot.list_by_radar(lat, lng, @api_key, options), detail ) end
[ "def", "spots_by_radar", "(", "lat", ",", "lng", ",", "options", "=", "{", "}", ")", "options", "=", "@options", ".", "merge", "(", "options", ")", "detail", "=", "options", ".", "delete", "(", ":detail", ")", "collection_detail_level", "(", "Spot", ".",...
Radar Search Service allows you to search for up to 200 Places at once, but with less detail than is typically returned from a Text Search or Nearby Search request. The search response will include up to 200 Places, identified only by their geographic coordinates and reference. You can send a Place Details request for ...
[ "Radar", "Search", "Service", "allows", "you", "to", "search", "for", "up", "to", "200", "Places", "at", "once", "but", "with", "less", "detail", "than", "is", "typically", "returned", "from", "a", "Text", "Search", "or", "Nearby", "Search", "request", "."...
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/client.rb#L274-L281
14,715
qpowell/google_places
lib/google_places/photo.rb
GooglePlaces.Photo.fetch_url
def fetch_url(maxwidth, options = {}) language = options.delete(:language) retry_options = options.delete(:retry_options) || {} unless @fetched_url @fetched_url = Request.photo_url( :maxwidth => maxwidth, :photoreference => @photo_reference, :key => @api_key, ...
ruby
def fetch_url(maxwidth, options = {}) language = options.delete(:language) retry_options = options.delete(:retry_options) || {} unless @fetched_url @fetched_url = Request.photo_url( :maxwidth => maxwidth, :photoreference => @photo_reference, :key => @api_key, ...
[ "def", "fetch_url", "(", "maxwidth", ",", "options", "=", "{", "}", ")", "language", "=", "options", ".", "delete", "(", ":language", ")", "retry_options", "=", "options", ".", "delete", "(", ":retry_options", ")", "||", "{", "}", "unless", "@fetched_url",...
Search for a Photo's url with its reference key @return [URL] @param [String] api_key the provided api key @param [Hash] options @option options [Hash] :retry_options ({}) A Hash containing parameters for search retries @option options [Object] :retry_options[:status] ([]) @option options [Integer] :retry_opt...
[ "Search", "for", "a", "Photo", "s", "url", "with", "its", "reference", "key" ]
6e1a5e7dc780641898f158ae8c310f1387f4aa01
https://github.com/qpowell/google_places/blob/6e1a5e7dc780641898f158ae8c310f1387f4aa01/lib/google_places/photo.rb#L23-L36
14,716
solnic/virtus
lib/virtus/const_missing_extensions.rb
Virtus.ConstMissingExtensions.const_missing
def const_missing(name) Attribute::Builder.determine_type(name) or Axiom::Types.const_defined?(name) && Axiom::Types.const_get(name) or super end
ruby
def const_missing(name) Attribute::Builder.determine_type(name) or Axiom::Types.const_defined?(name) && Axiom::Types.const_get(name) or super end
[ "def", "const_missing", "(", "name", ")", "Attribute", "::", "Builder", ".", "determine_type", "(", "name", ")", "or", "Axiom", "::", "Types", ".", "const_defined?", "(", "name", ")", "&&", "Axiom", "::", "Types", ".", "const_get", "(", "name", ")", "or"...
Hooks into const missing process to determine types of attributes @param [String] name @return [Class] @api private
[ "Hooks", "into", "const", "missing", "process", "to", "determine", "types", "of", "attributes" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/const_missing_extensions.rb#L11-L15
14,717
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.each
def each return to_enum unless block_given? @index.each { |name, attribute| yield attribute if name.kind_of?(Symbol) } self end
ruby
def each return to_enum unless block_given? @index.each { |name, attribute| yield attribute if name.kind_of?(Symbol) } self end
[ "def", "each", "return", "to_enum", "unless", "block_given?", "@index", ".", "each", "{", "|", "name", ",", "attribute", "|", "yield", "attribute", "if", "name", ".", "kind_of?", "(", "Symbol", ")", "}", "self", "end" ]
Initialize an AttributeSet @param [AttributeSet] parent @param [Array] attributes @return [undefined] @api private Iterate over each attribute in the set @example attribute_set = AttributeSet.new(attributes, parent) attribute_set.each { |attribute| ... } @yield [attribute] @yieldparam [Attribute] at...
[ "Initialize", "an", "AttributeSet" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L44-L48
14,718
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.define_reader_method
def define_reader_method(attribute, method_name, visibility) define_method(method_name) { attribute.get(self) } send(visibility, method_name) end
ruby
def define_reader_method(attribute, method_name, visibility) define_method(method_name) { attribute.get(self) } send(visibility, method_name) end
[ "def", "define_reader_method", "(", "attribute", ",", "method_name", ",", "visibility", ")", "define_method", "(", "method_name", ")", "{", "attribute", ".", "get", "(", "self", ")", "}", "send", "(", "visibility", ",", "method_name", ")", "end" ]
Defines an attribute reader method @param [Attribute] attribute @param [Symbol] method_name @param [Symbol] visibility @return [undefined] @api private
[ "Defines", "an", "attribute", "reader", "method" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L131-L134
14,719
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.define_writer_method
def define_writer_method(attribute, method_name, visibility) define_method(method_name) { |value| attribute.set(self, value) } send(visibility, method_name) end
ruby
def define_writer_method(attribute, method_name, visibility) define_method(method_name) { |value| attribute.set(self, value) } send(visibility, method_name) end
[ "def", "define_writer_method", "(", "attribute", ",", "method_name", ",", "visibility", ")", "define_method", "(", "method_name", ")", "{", "|", "value", "|", "attribute", ".", "set", "(", "self", ",", "value", ")", "}", "send", "(", "visibility", ",", "me...
Defines an attribute writer method @param [Attribute] attribute @param [Symbol] method_name @param [Symbol] visibility @return [undefined] @api private
[ "Defines", "an", "attribute", "writer", "method" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L145-L148
14,720
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.get
def get(object) each_with_object({}) do |attribute, attributes| name = attribute.name attributes[name] = object.__send__(name) if attribute.public_reader? end end
ruby
def get(object) each_with_object({}) do |attribute, attributes| name = attribute.name attributes[name] = object.__send__(name) if attribute.public_reader? end end
[ "def", "get", "(", "object", ")", "each_with_object", "(", "{", "}", ")", "do", "|", "attribute", ",", "attributes", "|", "name", "=", "attribute", ".", "name", "attributes", "[", "name", "]", "=", "object", ".", "__send__", "(", "name", ")", "if", "...
Get values of all attributes defined for this class, ignoring privacy @return [Hash] @api private
[ "Get", "values", "of", "all", "attributes", "defined", "for", "this", "class", "ignoring", "privacy" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L155-L160
14,721
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.set
def set(object, attributes) coerce(attributes).each do |name, value| writer_name = "#{name}=" if object.allowed_writer_methods.include?(writer_name) object.__send__(writer_name, value) end end end
ruby
def set(object, attributes) coerce(attributes).each do |name, value| writer_name = "#{name}=" if object.allowed_writer_methods.include?(writer_name) object.__send__(writer_name, value) end end end
[ "def", "set", "(", "object", ",", "attributes", ")", "coerce", "(", "attributes", ")", ".", "each", "do", "|", "name", ",", "value", "|", "writer_name", "=", "\"#{name}=\"", "if", "object", ".", "allowed_writer_methods", ".", "include?", "(", "writer_name", ...
Mass-assign attribute values @see Virtus::InstanceMethods#attributes= @return [Hash] @api private
[ "Mass", "-", "assign", "attribute", "values" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L169-L176
14,722
solnic/virtus
lib/virtus/attribute_set.rb
Virtus.AttributeSet.set_defaults
def set_defaults(object, filter = method(:skip_default?)) each do |attribute| next if filter.call(object, attribute) attribute.set_default_value(object) end end
ruby
def set_defaults(object, filter = method(:skip_default?)) each do |attribute| next if filter.call(object, attribute) attribute.set_default_value(object) end end
[ "def", "set_defaults", "(", "object", ",", "filter", "=", "method", "(", ":skip_default?", ")", ")", "each", "do", "|", "attribute", "|", "next", "if", "filter", ".", "call", "(", "object", ",", "attribute", ")", "attribute", ".", "set_default_value", "(",...
Set default attributes @return [self] @api private
[ "Set", "default", "attributes" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/attribute_set.rb#L183-L188
14,723
solnic/virtus
lib/virtus/support/type_lookup.rb
Virtus.TypeLookup.determine_type_from_primitive
def determine_type_from_primitive(primitive) type = nil descendants.select(&:primitive).reverse_each do |descendant| descendant_primitive = descendant.primitive next unless primitive <= descendant_primitive type = descendant if type.nil? or type.primitive > descendant_primitive ...
ruby
def determine_type_from_primitive(primitive) type = nil descendants.select(&:primitive).reverse_each do |descendant| descendant_primitive = descendant.primitive next unless primitive <= descendant_primitive type = descendant if type.nil? or type.primitive > descendant_primitive ...
[ "def", "determine_type_from_primitive", "(", "primitive", ")", "type", "=", "nil", "descendants", ".", "select", "(", ":primitive", ")", ".", "reverse_each", "do", "|", "descendant", "|", "descendant_primitive", "=", "descendant", ".", "primitive", "next", "unless...
Return the class given a primitive @param [Class] primitive @return [Class] @return [nil] nil if the type cannot be determined by the primitive @api private
[ "Return", "the", "class", "given", "a", "primitive" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/support/type_lookup.rb#L82-L90
14,724
solnic/virtus
lib/virtus/support/type_lookup.rb
Virtus.TypeLookup.determine_type_from_string
def determine_type_from_string(string) if string =~ TYPE_FORMAT and const_defined?(string, *EXTRA_CONST_ARGS) const_get(string, *EXTRA_CONST_ARGS) end end
ruby
def determine_type_from_string(string) if string =~ TYPE_FORMAT and const_defined?(string, *EXTRA_CONST_ARGS) const_get(string, *EXTRA_CONST_ARGS) end end
[ "def", "determine_type_from_string", "(", "string", ")", "if", "string", "=~", "TYPE_FORMAT", "and", "const_defined?", "(", "string", ",", "EXTRA_CONST_ARGS", ")", "const_get", "(", "string", ",", "EXTRA_CONST_ARGS", ")", "end", "end" ]
Return the class given a string @param [String] string @return [Class] @return [nil] nil if the type cannot be determined by the string @api private
[ "Return", "the", "class", "given", "a", "string" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/support/type_lookup.rb#L102-L106
14,725
solnic/virtus
lib/virtus/module_extensions.rb
Virtus.ModuleExtensions.extended
def extended(object) super @inclusions.each { |mod| object.extend(mod) } define_attributes(object) object.set_default_attributes end
ruby
def extended(object) super @inclusions.each { |mod| object.extend(mod) } define_attributes(object) object.set_default_attributes end
[ "def", "extended", "(", "object", ")", "super", "@inclusions", ".", "each", "{", "|", "mod", "|", "object", ".", "extend", "(", "mod", ")", "}", "define_attributes", "(", "object", ")", "object", ".", "set_default_attributes", "end" ]
Extend an object with Virtus methods and define attributes @param [Object] object @return [undefined] @api private
[ "Extend", "an", "object", "with", "Virtus", "methods", "and", "define", "attributes" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/module_extensions.rb#L44-L49
14,726
solnic/virtus
lib/virtus/module_extensions.rb
Virtus.ModuleExtensions.included
def included(object) super if Class === object @inclusions.reject do |mod| object.ancestors.include?(mod) end.each do |mod| object.send(:include, mod) end define_attributes(object) else object.extend(ModuleExtensions) ModuleExtension...
ruby
def included(object) super if Class === object @inclusions.reject do |mod| object.ancestors.include?(mod) end.each do |mod| object.send(:include, mod) end define_attributes(object) else object.extend(ModuleExtensions) ModuleExtension...
[ "def", "included", "(", "object", ")", "super", "if", "Class", "===", "object", "@inclusions", ".", "reject", "do", "|", "mod", "|", "object", ".", "ancestors", ".", "include?", "(", "mod", ")", "end", ".", "each", "do", "|", "mod", "|", "object", "....
Extend a class with Virtus methods and define attributes @param [Object] object @return [undefined] @api private
[ "Extend", "a", "class", "with", "Virtus", "methods", "and", "define", "attributes" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/module_extensions.rb#L58-L72
14,727
solnic/virtus
lib/virtus/builder.rb
Virtus.Builder.add_included_hook
def add_included_hook with_hook_context do |context| mod.define_singleton_method :included do |object| Builder.pending << object unless context.finalize? context.modules.each { |mod| object.send(:include, mod) } object.define_singleton_method(:attribute, context.attribute_met...
ruby
def add_included_hook with_hook_context do |context| mod.define_singleton_method :included do |object| Builder.pending << object unless context.finalize? context.modules.each { |mod| object.send(:include, mod) } object.define_singleton_method(:attribute, context.attribute_met...
[ "def", "add_included_hook", "with_hook_context", "do", "|", "context", "|", "mod", ".", "define_singleton_method", ":included", "do", "|", "object", "|", "Builder", ".", "pending", "<<", "object", "unless", "context", ".", "finalize?", "context", ".", "modules", ...
Adds the .included hook to the anonymous module which then defines the .attribute method to override the default. @return [Module] @api private
[ "Adds", "the", ".", "included", "hook", "to", "the", "anonymous", "module", "which", "then", "defines", "the", ".", "attribute", "method", "to", "override", "the", "default", "." ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/builder.rb#L68-L76
14,728
solnic/virtus
lib/virtus/support/options.rb
Virtus.Options.options
def options accepted_options.each_with_object({}) do |option_name, options| option_value = send(option_name) options[option_name] = option_value unless option_value.nil? end end
ruby
def options accepted_options.each_with_object({}) do |option_name, options| option_value = send(option_name) options[option_name] = option_value unless option_value.nil? end end
[ "def", "options", "accepted_options", ".", "each_with_object", "(", "{", "}", ")", "do", "|", "option_name", ",", "options", "|", "option_value", "=", "send", "(", "option_name", ")", "options", "[", "option_name", "]", "=", "option_value", "unless", "option_v...
Returns default options hash for a given attribute class @example Virtus::Attribute::String.options # => {:primitive => String} @return [Hash] a hash of default option values @api public
[ "Returns", "default", "options", "hash", "for", "a", "given", "attribute", "class" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/support/options.rb#L16-L21
14,729
solnic/virtus
lib/virtus/support/options.rb
Virtus.Options.accept_options
def accept_options(*new_options) add_accepted_options(new_options) new_options.each { |option| define_option_method(option) } descendants.each { |descendant| descendant.add_accepted_options(new_options) } self end
ruby
def accept_options(*new_options) add_accepted_options(new_options) new_options.each { |option| define_option_method(option) } descendants.each { |descendant| descendant.add_accepted_options(new_options) } self end
[ "def", "accept_options", "(", "*", "new_options", ")", "add_accepted_options", "(", "new_options", ")", "new_options", ".", "each", "{", "|", "option", "|", "define_option_method", "(", "option", ")", "}", "descendants", ".", "each", "{", "|", "descendant", "|...
Defines which options are valid for a given attribute class @example class MyAttribute < Virtus::Attribute accept_options :foo, :bar end @return [self] @api public
[ "Defines", "which", "options", "are", "valid", "for", "a", "given", "attribute", "class" ]
a6f8969841247462bb05c456458baa66fce29ed8
https://github.com/solnic/virtus/blob/a6f8969841247462bb05c456458baa66fce29ed8/lib/virtus/support/options.rb#L47-L52
14,730
mdp/rotp
lib/rotp/totp.rb
ROTP.TOTP.verify
def verify(otp, drift_ahead: 0, drift_behind: 0, after: nil, at: Time.now) timecodes = get_timecodes(at, drift_behind, drift_ahead) timecodes = timecodes.select { |t| t > timecode(after) } if after result = nil timecodes.each do |t| result = t * interval if super(otp, generate_otp(t)) ...
ruby
def verify(otp, drift_ahead: 0, drift_behind: 0, after: nil, at: Time.now) timecodes = get_timecodes(at, drift_behind, drift_ahead) timecodes = timecodes.select { |t| t > timecode(after) } if after result = nil timecodes.each do |t| result = t * interval if super(otp, generate_otp(t)) ...
[ "def", "verify", "(", "otp", ",", "drift_ahead", ":", "0", ",", "drift_behind", ":", "0", ",", "after", ":", "nil", ",", "at", ":", "Time", ".", "now", ")", "timecodes", "=", "get_timecodes", "(", "at", ",", "drift_behind", ",", "drift_ahead", ")", "...
Verifies the OTP passed in against the current time OTP and adjacent intervals up to +drift+. Excludes OTPs from `after` and earlier. Returns time value of matching OTP code for use in subsequent call. @param otp [String] the one time password to verify @param drift_behind [Integer] how many seconds to look back...
[ "Verifies", "the", "OTP", "passed", "in", "against", "the", "current", "time", "OTP", "and", "adjacent", "intervals", "up", "to", "+", "drift", "+", ".", "Excludes", "OTPs", "from", "after", "and", "earlier", ".", "Returns", "time", "value", "of", "matchin...
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/totp.rb#L39-L49
14,731
mdp/rotp
lib/rotp/totp.rb
ROTP.TOTP.get_timecodes
def get_timecodes(at, drift_behind, drift_ahead) now = timeint(at) timecode_start = timecode(now - drift_behind) timecode_end = timecode(now + drift_ahead) (timecode_start..timecode_end).step(1).to_a end
ruby
def get_timecodes(at, drift_behind, drift_ahead) now = timeint(at) timecode_start = timecode(now - drift_behind) timecode_end = timecode(now + drift_ahead) (timecode_start..timecode_end).step(1).to_a end
[ "def", "get_timecodes", "(", "at", ",", "drift_behind", ",", "drift_ahead", ")", "now", "=", "timeint", "(", "at", ")", "timecode_start", "=", "timecode", "(", "now", "-", "drift_behind", ")", "timecode_end", "=", "timecode", "(", "now", "+", "drift_ahead", ...
Get back an array of timecodes for a period
[ "Get", "back", "an", "array", "of", "timecodes", "for", "a", "period" ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/totp.rb#L75-L80
14,732
mdp/rotp
lib/rotp/otp.rb
ROTP.OTP.encode_params
def encode_params(uri, params) params_str = String.new('?') params.each do |k, v| params_str << "#{k}=#{CGI.escape(v.to_s)}&" if v end params_str.chop! uri + params_str end
ruby
def encode_params(uri, params) params_str = String.new('?') params.each do |k, v| params_str << "#{k}=#{CGI.escape(v.to_s)}&" if v end params_str.chop! uri + params_str end
[ "def", "encode_params", "(", "uri", ",", "params", ")", "params_str", "=", "String", ".", "new", "(", "'?'", ")", "params", ".", "each", "do", "|", "k", ",", "v", "|", "params_str", "<<", "\"#{k}=#{CGI.escape(v.to_s)}&\"", "if", "v", "end", "params_str", ...
A very simple param encoder
[ "A", "very", "simple", "param", "encoder" ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/otp.rb#L70-L77
14,733
mdp/rotp
lib/rotp/otp.rb
ROTP.OTP.time_constant_compare
def time_constant_compare(a, b) return false if a.empty? || b.empty? || a.bytesize != b.bytesize l = a.unpack "C#{a.bytesize}" res = 0 b.each_byte { |byte| res |= byte ^ l.shift } res == 0 end
ruby
def time_constant_compare(a, b) return false if a.empty? || b.empty? || a.bytesize != b.bytesize l = a.unpack "C#{a.bytesize}" res = 0 b.each_byte { |byte| res |= byte ^ l.shift } res == 0 end
[ "def", "time_constant_compare", "(", "a", ",", "b", ")", "return", "false", "if", "a", ".", "empty?", "||", "b", ".", "empty?", "||", "a", ".", "bytesize", "!=", "b", ".", "bytesize", "l", "=", "a", ".", "unpack", "\"C#{a.bytesize}\"", "res", "=", "0...
constant-time compare the strings
[ "constant", "-", "time", "compare", "the", "strings" ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/otp.rb#L80-L87
14,734
mdp/rotp
lib/rotp/hotp.rb
ROTP.HOTP.verify
def verify(otp, counter, retries: 0) counters = (counter..counter + retries).to_a counters.find do |c| super(otp, at(c)) end end
ruby
def verify(otp, counter, retries: 0) counters = (counter..counter + retries).to_a counters.find do |c| super(otp, at(c)) end end
[ "def", "verify", "(", "otp", ",", "counter", ",", "retries", ":", "0", ")", "counters", "=", "(", "counter", "..", "counter", "+", "retries", ")", ".", "to_a", "counters", ".", "find", "do", "|", "c", "|", "super", "(", "otp", ",", "at", "(", "c"...
Verifies the OTP passed in against the current time OTP @param otp [String/Integer] the OTP to check against @param counter [Integer] the counter of the OTP @param retries [Integer] number of counters to incrementally retry
[ "Verifies", "the", "OTP", "passed", "in", "against", "the", "current", "time", "OTP" ]
2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc
https://github.com/mdp/rotp/blob/2698c91539cfb868790e8bb7d5d4d8cf78f0bbfc/lib/rotp/hotp.rb#L14-L19
14,735
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.ec2_metadata
def ec2_metadata raise "Called ec2_metadata with platform=#{@platform}" unless @platform == Platform::EC2 unless @ec2_metadata # See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html open('http://' + METADATA_SERVICE_ADDR + '/latest/dynamic/in...
ruby
def ec2_metadata raise "Called ec2_metadata with platform=#{@platform}" unless @platform == Platform::EC2 unless @ec2_metadata # See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html open('http://' + METADATA_SERVICE_ADDR + '/latest/dynamic/in...
[ "def", "ec2_metadata", "raise", "\"Called ec2_metadata with platform=#{@platform}\"", "unless", "@platform", "==", "Platform", "::", "EC2", "unless", "@ec2_metadata", "# See http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html", "open", "(", "'http://'", "+",...
EC2 Metadata server returns everything in one call. Store it after the first fetch to avoid making multiple calls.
[ "EC2", "Metadata", "server", "returns", "everything", "in", "one", "call", ".", "Store", "it", "after", "the", "first", "fetch", "to", "avoid", "making", "multiple", "calls", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1081-L1094
14,736
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.set_required_metadata_variables
def set_required_metadata_variables set_project_id set_vm_id set_vm_name set_location # All metadata parameters must now be set. missing = [] missing << 'project_id' unless @project_id if @platform != Platform::OTHER missing << 'zone' unless @zone missing...
ruby
def set_required_metadata_variables set_project_id set_vm_id set_vm_name set_location # All metadata parameters must now be set. missing = [] missing << 'project_id' unless @project_id if @platform != Platform::OTHER missing << 'zone' unless @zone missing...
[ "def", "set_required_metadata_variables", "set_project_id", "set_vm_id", "set_vm_name", "set_location", "# All metadata parameters must now be set.", "missing", "=", "[", "]", "missing", "<<", "'project_id'", "unless", "@project_id", "if", "@platform", "!=", "Platform", "::",...
Set required variables like @project_id, @vm_id, @vm_name and @zone.
[ "Set", "required", "variables", "like" ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1114-L1130
14,737
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.set_vm_id
def set_vm_id @vm_id ||= fetch_gce_metadata('instance/id') if @platform == Platform::GCE @vm_id ||= ec2_metadata['instanceId'] if @platform == Platform::EC2 rescue StandardError => e @log.error 'Failed to obtain vm_id: ', error: e end
ruby
def set_vm_id @vm_id ||= fetch_gce_metadata('instance/id') if @platform == Platform::GCE @vm_id ||= ec2_metadata['instanceId'] if @platform == Platform::EC2 rescue StandardError => e @log.error 'Failed to obtain vm_id: ', error: e end
[ "def", "set_vm_id", "@vm_id", "||=", "fetch_gce_metadata", "(", "'instance/id'", ")", "if", "@platform", "==", "Platform", "::", "GCE", "@vm_id", "||=", "ec2_metadata", "[", "'instanceId'", "]", "if", "@platform", "==", "Platform", "::", "EC2", "rescue", "Standa...
1. Return the value if it is explicitly set in the config already. 2. If not, try to retrieve it by calling metadata servers directly.
[ "1", ".", "Return", "the", "value", "if", "it", "is", "explicitly", "set", "in", "the", "config", "already", ".", "2", ".", "If", "not", "try", "to", "retrieve", "it", "by", "calling", "metadata", "servers", "directly", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1143-L1148
14,738
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.set_location
def set_location # Response format: "projects/<number>/zones/<zone>" @zone ||= fetch_gce_metadata('instance/zone').rpartition('/')[2] if @platform == Platform::GCE aws_location_key = if @use_aws_availability_zone 'availabilityZone' else ...
ruby
def set_location # Response format: "projects/<number>/zones/<zone>" @zone ||= fetch_gce_metadata('instance/zone').rpartition('/')[2] if @platform == Platform::GCE aws_location_key = if @use_aws_availability_zone 'availabilityZone' else ...
[ "def", "set_location", "# Response format: \"projects/<number>/zones/<zone>\"", "@zone", "||=", "fetch_gce_metadata", "(", "'instance/zone'", ")", ".", "rpartition", "(", "'/'", ")", "[", "2", "]", "if", "@platform", "==", "Platform", "::", "GCE", "aws_location_key", ...
1. Return the value if it is explicitly set in the config already. 2. If not, try to retrieve it locally.
[ "1", ".", "Return", "the", "value", "if", "it", "is", "explicitly", "set", "in", "the", "config", "already", ".", "2", ".", "If", "not", "try", "to", "retrieve", "it", "locally", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1160-L1173
14,739
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_agent_level_monitored_resource_via_legacy
def determine_agent_level_monitored_resource_via_legacy resource = Google::Apis::LoggingV2::MonitoredResource.new( labels: {}) resource.type = determine_agent_level_monitored_resource_type resource.labels = determine_agent_level_monitored_resource_labels( resource.type) resource ...
ruby
def determine_agent_level_monitored_resource_via_legacy resource = Google::Apis::LoggingV2::MonitoredResource.new( labels: {}) resource.type = determine_agent_level_monitored_resource_type resource.labels = determine_agent_level_monitored_resource_labels( resource.type) resource ...
[ "def", "determine_agent_level_monitored_resource_via_legacy", "resource", "=", "Google", "::", "Apis", "::", "LoggingV2", "::", "MonitoredResource", ".", "new", "(", "labels", ":", "{", "}", ")", "resource", ".", "type", "=", "determine_agent_level_monitored_resource_ty...
Retrieve monitored resource via the legacy way. Note: This is just a failover plan if we fail to get metadata from Metadata Agent. Thus it should be equivalent to what Metadata Agent returns.
[ "Retrieve", "monitored", "resource", "via", "the", "legacy", "way", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1180-L1187
14,740
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_agent_level_monitored_resource_type
def determine_agent_level_monitored_resource_type case @platform when Platform::OTHER # Unknown platform will be defaulted to GCE instance. return COMPUTE_CONSTANTS[:resource_type] when Platform::EC2 return EC2_CONSTANTS[:resource_type] when Platform::GCE # Reso...
ruby
def determine_agent_level_monitored_resource_type case @platform when Platform::OTHER # Unknown platform will be defaulted to GCE instance. return COMPUTE_CONSTANTS[:resource_type] when Platform::EC2 return EC2_CONSTANTS[:resource_type] when Platform::GCE # Reso...
[ "def", "determine_agent_level_monitored_resource_type", "case", "@platform", "when", "Platform", "::", "OTHER", "# Unknown platform will be defaulted to GCE instance.", "return", "COMPUTE_CONSTANTS", "[", ":resource_type", "]", "when", "Platform", "::", "EC2", "return", "EC2_CO...
Determine agent level monitored resource type.
[ "Determine", "agent", "level", "monitored", "resource", "type", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1190-L1218
14,741
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_agent_level_monitored_resource_labels
def determine_agent_level_monitored_resource_labels(type) case type # GAE app. when APPENGINE_CONSTANTS[:resource_type] return { 'module_id' => fetch_gce_metadata('instance/attributes/gae_backend_name'), 'version_id' => fetch_gce_metadata('instance/a...
ruby
def determine_agent_level_monitored_resource_labels(type) case type # GAE app. when APPENGINE_CONSTANTS[:resource_type] return { 'module_id' => fetch_gce_metadata('instance/attributes/gae_backend_name'), 'version_id' => fetch_gce_metadata('instance/a...
[ "def", "determine_agent_level_monitored_resource_labels", "(", "type", ")", "case", "type", "# GAE app.", "when", "APPENGINE_CONSTANTS", "[", ":resource_type", "]", "return", "{", "'module_id'", "=>", "fetch_gce_metadata", "(", "'instance/attributes/gae_backend_name'", ")", ...
Determine agent level monitored resource labels based on the resource type. Each resource type has its own labels that need to be filled in.
[ "Determine", "agent", "level", "monitored", "resource", "labels", "based", "on", "the", "resource", "type", ".", "Each", "resource", "type", "has", "its", "own", "labels", "that", "need", "to", "be", "filled", "in", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1222-L1282
14,742
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_agent_level_common_labels
def determine_agent_level_common_labels labels = {} # User can specify labels via config. We want to capture those as well. labels.merge!(@labels) if @labels case @resource.type # GAE, Cloud Dataflow, Cloud Dataproc and Cloud ML. when APPENGINE_CONSTANTS[:resource_type], ...
ruby
def determine_agent_level_common_labels labels = {} # User can specify labels via config. We want to capture those as well. labels.merge!(@labels) if @labels case @resource.type # GAE, Cloud Dataflow, Cloud Dataproc and Cloud ML. when APPENGINE_CONSTANTS[:resource_type], ...
[ "def", "determine_agent_level_common_labels", "labels", "=", "{", "}", "# User can specify labels via config. We want to capture those as well.", "labels", ".", "merge!", "(", "@labels", ")", "if", "@labels", "case", "@resource", ".", "type", "# GAE, Cloud Dataflow, Cloud Datap...
Determine the common labels that should be added to all log entries processed by this logging agent.
[ "Determine", "the", "common", "labels", "that", "should", "be", "added", "to", "all", "log", "entries", "processed", "by", "this", "logging", "agent", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1286-L1313
14,743
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.group_log_entries_by_tag_and_local_resource_id
def group_log_entries_by_tag_and_local_resource_id(chunk) groups = {} chunk.msgpack_each do |tag, time, record| unless record.is_a?(Hash) @log.warn 'Dropping log entries with malformed record: ' \ "'#{record.inspect}'. " \ 'A log record should be in ...
ruby
def group_log_entries_by_tag_and_local_resource_id(chunk) groups = {} chunk.msgpack_each do |tag, time, record| unless record.is_a?(Hash) @log.warn 'Dropping log entries with malformed record: ' \ "'#{record.inspect}'. " \ 'A log record should be in ...
[ "def", "group_log_entries_by_tag_and_local_resource_id", "(", "chunk", ")", "groups", "=", "{", "}", "chunk", ".", "msgpack_each", "do", "|", "tag", ",", "time", ",", "record", "|", "unless", "record", ".", "is_a?", "(", "Hash", ")", "@log", ".", "warn", "...
Group the log entries by tag and local_resource_id pairs. Also filter out invalid non-Hash entries.
[ "Group", "the", "log", "entries", "by", "tag", "and", "local_resource_id", "pairs", ".", "Also", "filter", "out", "invalid", "non", "-", "Hash", "entries", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1317-L1339
14,744
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_group_level_monitored_resource_and_labels
def determine_group_level_monitored_resource_and_labels(tag, local_resource_id) resource = @resource.dup resource.labels = @resource.labels.dup common_labels = @common_labels.dup # Change the resource type and set matched_regexp_group ...
ruby
def determine_group_level_monitored_resource_and_labels(tag, local_resource_id) resource = @resource.dup resource.labels = @resource.labels.dup common_labels = @common_labels.dup # Change the resource type and set matched_regexp_group ...
[ "def", "determine_group_level_monitored_resource_and_labels", "(", "tag", ",", "local_resource_id", ")", "resource", "=", "@resource", ".", "dup", "resource", ".", "labels", "=", "@resource", ".", "labels", ".", "dup", "common_labels", "=", "@common_labels", ".", "d...
Determine the group level monitored resource and common labels shared by a collection of entries.
[ "Determine", "the", "group", "level", "monitored", "resource", "and", "common", "labels", "shared", "by", "a", "collection", "of", "entries", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1343-L1452
14,745
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.monitored_resource_from_local_resource_id
def monitored_resource_from_local_resource_id(local_resource_id) return unless local_resource_id if @enable_metadata_agent @log.debug 'Calling metadata agent with local_resource_id: ' \ "#{local_resource_id}." resource = query_metadata_agent_for_monitored_resource( ...
ruby
def monitored_resource_from_local_resource_id(local_resource_id) return unless local_resource_id if @enable_metadata_agent @log.debug 'Calling metadata agent with local_resource_id: ' \ "#{local_resource_id}." resource = query_metadata_agent_for_monitored_resource( ...
[ "def", "monitored_resource_from_local_resource_id", "(", "local_resource_id", ")", "return", "unless", "local_resource_id", "if", "@enable_metadata_agent", "@log", ".", "debug", "'Calling metadata agent with local_resource_id: '", "\"#{local_resource_id}.\"", "resource", "=", "quer...
Take a locally unique resource id and convert it to the globally unique monitored resource.
[ "Take", "a", "locally", "unique", "resource", "id", "and", "convert", "it", "to", "the", "globally", "unique", "monitored", "resource", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1456-L1478
14,746
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.determine_entry_level_monitored_resource_and_labels
def determine_entry_level_monitored_resource_and_labels( group_level_resource, group_level_common_labels, record) resource = group_level_resource.dup resource.labels = group_level_resource.labels.dup common_labels = group_level_common_labels.dup case resource.type # Cloud Functions....
ruby
def determine_entry_level_monitored_resource_and_labels( group_level_resource, group_level_common_labels, record) resource = group_level_resource.dup resource.labels = group_level_resource.labels.dup common_labels = group_level_common_labels.dup case resource.type # Cloud Functions....
[ "def", "determine_entry_level_monitored_resource_and_labels", "(", "group_level_resource", ",", "group_level_common_labels", ",", "record", ")", "resource", "=", "group_level_resource", ".", "dup", "resource", ".", "labels", "=", "group_level_resource", ".", "labels", ".", ...
Extract entry level monitored resource and common labels that should be applied to individual entries.
[ "Extract", "entry", "level", "monitored", "resource", "and", "common", "labels", "that", "should", "be", "applied", "to", "individual", "entries", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1482-L1552
14,747
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.query_metadata_agent
def query_metadata_agent(path) url = "#{@metadata_agent_url}/#{path}" @log.debug("Calling Metadata Agent: #{url}") open(url) do |f| response = f.read parsed_hash = parse_json_or_nil(response) if parsed_hash.nil? @log.error 'Response from Metadata Agent is not in valid...
ruby
def query_metadata_agent(path) url = "#{@metadata_agent_url}/#{path}" @log.debug("Calling Metadata Agent: #{url}") open(url) do |f| response = f.read parsed_hash = parse_json_or_nil(response) if parsed_hash.nil? @log.error 'Response from Metadata Agent is not in valid...
[ "def", "query_metadata_agent", "(", "path", ")", "url", "=", "\"#{@metadata_agent_url}/#{path}\"", "@log", ".", "debug", "(", "\"Calling Metadata Agent: #{url}\"", ")", "open", "(", "url", ")", "do", "|", "f", "|", "response", "=", "f", ".", "read", "parsed_hash...
Issue a request to the Metadata Agent's local API and parse the response to JSON. Return nil in case of failure.
[ "Issue", "a", "request", "to", "the", "Metadata", "Agent", "s", "local", "API", "and", "parse", "the", "response", "to", "JSON", ".", "Return", "nil", "in", "case", "of", "failure", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1578-L1595
14,748
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.parse_labels
def parse_labels(record) payload_labels = record.delete(@labels_key) return nil unless payload_labels unless payload_labels.is_a?(Hash) @log.error "Invalid value of '#{@labels_key}' in the payload: " \ "#{payload_labels}. Labels need to be a JSON object." return nil ...
ruby
def parse_labels(record) payload_labels = record.delete(@labels_key) return nil unless payload_labels unless payload_labels.is_a?(Hash) @log.error "Invalid value of '#{@labels_key}' in the payload: " \ "#{payload_labels}. Labels need to be a JSON object." return nil ...
[ "def", "parse_labels", "(", "record", ")", "payload_labels", "=", "record", ".", "delete", "(", "@labels_key", ")", "return", "nil", "unless", "payload_labels", "unless", "payload_labels", ".", "is_a?", "(", "Hash", ")", "@log", ".", "error", "\"Invalid value of...
Parse labels. Return nil if not set.
[ "Parse", "labels", ".", "Return", "nil", "if", "not", "set", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1797-L1819
14,749
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.sanitize_tag
def sanitize_tag(tag) if @require_valid_tags && (!tag.is_a?(String) || tag == '' || convert_to_utf8(tag) != tag) return nil end tag = convert_to_utf8(tag.to_s) tag = '_' if tag == '' tag end
ruby
def sanitize_tag(tag) if @require_valid_tags && (!tag.is_a?(String) || tag == '' || convert_to_utf8(tag) != tag) return nil end tag = convert_to_utf8(tag.to_s) tag = '_' if tag == '' tag end
[ "def", "sanitize_tag", "(", "tag", ")", "if", "@require_valid_tags", "&&", "(", "!", "tag", ".", "is_a?", "(", "String", ")", "||", "tag", "==", "''", "||", "convert_to_utf8", "(", "tag", ")", "!=", "tag", ")", "return", "nil", "end", "tag", "=", "co...
Given a tag, returns the corresponding valid tag if possible, or nil if the tag should be rejected. If 'require_valid_tags' is false, non-string tags are converted to strings, and invalid characters are sanitized; otherwise such tags are rejected.
[ "Given", "a", "tag", "returns", "the", "corresponding", "valid", "tag", "if", "possible", "or", "nil", "if", "the", "tag", "should", "be", "rejected", ".", "If", "require_valid_tags", "is", "false", "non", "-", "string", "tags", "are", "converted", "to", "...
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1976-L1984
14,750
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.delete_and_extract_labels
def delete_and_extract_labels(hash, label_map) return {} if label_map.nil? || !label_map.is_a?(Hash) || hash.nil? || !hash.is_a?(Hash) label_map.each_with_object({}) \ do |(original_label, new_label), extracted_labels| value = hash.delete(original_label) extracted_...
ruby
def delete_and_extract_labels(hash, label_map) return {} if label_map.nil? || !label_map.is_a?(Hash) || hash.nil? || !hash.is_a?(Hash) label_map.each_with_object({}) \ do |(original_label, new_label), extracted_labels| value = hash.delete(original_label) extracted_...
[ "def", "delete_and_extract_labels", "(", "hash", ",", "label_map", ")", "return", "{", "}", "if", "label_map", ".", "nil?", "||", "!", "label_map", ".", "is_a?", "(", "Hash", ")", "||", "hash", ".", "nil?", "||", "!", "hash", ".", "is_a?", "(", "Hash",...
For every original_label => new_label pair in the label_map, delete the original_label from the hash map if it exists, and extract the value to form a map with the new_label as the key.
[ "For", "every", "original_label", "=", ">", "new_label", "pair", "in", "the", "label_map", "delete", "the", "original_label", "from", "the", "hash", "map", "if", "it", "exists", "and", "extract", "the", "value", "to", "form", "a", "map", "with", "the", "ne...
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L1989-L1997
14,751
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.convert_to_utf8
def convert_to_utf8(input) if @coerce_to_utf8 input.encode( 'utf-8', invalid: :replace, undef: :replace, replace: @non_utf8_replacement_string) else begin input.encode('utf-8') rescue EncodingError @log.error 'Encountered en...
ruby
def convert_to_utf8(input) if @coerce_to_utf8 input.encode( 'utf-8', invalid: :replace, undef: :replace, replace: @non_utf8_replacement_string) else begin input.encode('utf-8') rescue EncodingError @log.error 'Encountered en...
[ "def", "convert_to_utf8", "(", "input", ")", "if", "@coerce_to_utf8", "input", ".", "encode", "(", "'utf-8'", ",", "invalid", ":", ":replace", ",", "undef", ":", ":replace", ",", "replace", ":", "@non_utf8_replacement_string", ")", "else", "begin", "input", "....
Encode as UTF-8. If 'coerce_to_utf8' is set to true in the config, any non-UTF-8 character would be replaced by the string specified by 'non_utf8_replacement_string'. If 'coerce_to_utf8' is set to false, any non-UTF-8 character would trigger the plugin to error out.
[ "Encode", "as", "UTF", "-", "8", ".", "If", "coerce_to_utf8", "is", "set", "to", "true", "in", "the", "config", "any", "non", "-", "UTF", "-", "8", "character", "would", "be", "replaced", "by", "the", "string", "specified", "by", "non_utf8_replacement_stri...
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L2162-L2180
14,752
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/out_google_cloud.rb
Fluent.GoogleCloudOutput.construct_k8s_resource_locally
def construct_k8s_resource_locally(local_resource_id) return unless /^ (?<resource_type>k8s_container) \.(?<namespace_name>[0-9a-z-]+) \.(?<pod_name>[.0-9a-z-]+) \.(?<container_name>[0-9a-z-]+)$/x =~ local_resource_id || /^ (?<resource_type>k8s_pod...
ruby
def construct_k8s_resource_locally(local_resource_id) return unless /^ (?<resource_type>k8s_container) \.(?<namespace_name>[0-9a-z-]+) \.(?<pod_name>[.0-9a-z-]+) \.(?<container_name>[0-9a-z-]+)$/x =~ local_resource_id || /^ (?<resource_type>k8s_pod...
[ "def", "construct_k8s_resource_locally", "(", "local_resource_id", ")", "return", "unless", "/", "\\.", "\\.", "\\.", "/x", "=~", "local_resource_id", "||", "/", "\\.", "\\.", "/x", "=~", "local_resource_id", "||", "/", "\\.", "/x", "=~", "local_resource_id", "#...
Construct monitored resource locally for k8s resources.
[ "Construct", "monitored", "resource", "locally", "for", "k8s", "resources", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/out_google_cloud.rb#L2349-L2415
14,753
GoogleCloudPlatform/fluent-plugin-google-cloud
lib/fluent/plugin/monitoring.rb
Monitoring.PrometheusMonitoringRegistry.counter
def counter(name, desc) return @registry.counter(name, desc) rescue Prometheus::Client::Registry::AlreadyRegisteredError return @registry.get(name) end
ruby
def counter(name, desc) return @registry.counter(name, desc) rescue Prometheus::Client::Registry::AlreadyRegisteredError return @registry.get(name) end
[ "def", "counter", "(", "name", ",", "desc", ")", "return", "@registry", ".", "counter", "(", "name", ",", "desc", ")", "rescue", "Prometheus", "::", "Client", "::", "Registry", "::", "AlreadyRegisteredError", "return", "@registry", ".", "get", "(", "name", ...
Exception-driven behavior to avoid synchronization errors.
[ "Exception", "-", "driven", "behavior", "to", "avoid", "synchronization", "errors", "." ]
ab10cdc2b5a25bc70e9969ef422f9bcf85f94990
https://github.com/GoogleCloudPlatform/fluent-plugin-google-cloud/blob/ab10cdc2b5a25bc70e9969ef422f9bcf85f94990/lib/fluent/plugin/monitoring.rb#L36-L40
14,754
rossta/serviceworker-rails
lib/serviceworker/middleware.rb
ServiceWorker.Middleware.call
def call(env) case env[REQUEST_METHOD] when GET, HEAD route_match = @router.match_route(env) return respond_to_match(route_match, env) if route_match end @app.call(env) end
ruby
def call(env) case env[REQUEST_METHOD] when GET, HEAD route_match = @router.match_route(env) return respond_to_match(route_match, env) if route_match end @app.call(env) end
[ "def", "call", "(", "env", ")", "case", "env", "[", "REQUEST_METHOD", "]", "when", "GET", ",", "HEAD", "route_match", "=", "@router", ".", "match_route", "(", "env", ")", "return", "respond_to_match", "(", "route_match", ",", "env", ")", "if", "route_match...
Initialize the Rack middleware for responding to serviceworker asset requests @app [#call] middleware stack @opts [Hash] options to inject @param opts [#match_route] :routes matches routes on PATH_INFO @param opts [Hash] :headers default headers to use for matched routes @param opts [#call] :handler resolves res...
[ "Initialize", "the", "Rack", "middleware", "for", "responding", "to", "serviceworker", "asset", "requests" ]
757db5354c9e47a144397c4655f3d1cab6046bc0
https://github.com/rossta/serviceworker-rails/blob/757db5354c9e47a144397c4655f3d1cab6046bc0/lib/serviceworker/middleware.rb#L28-L36
14,755
glebm/i18n-tasks
lib/i18n/tasks/used_keys.rb
I18n::Tasks.UsedKeys.used_tree
def used_tree(key_filter: nil, strict: nil, include_raw_references: false) src_tree = used_in_source_tree(key_filter: key_filter, strict: strict) raw_refs, resolved_refs, used_refs = process_references(src_tree['used'].children) raw_refs.leaves { |node| node.data[:ref_type] = :reference_usage } ...
ruby
def used_tree(key_filter: nil, strict: nil, include_raw_references: false) src_tree = used_in_source_tree(key_filter: key_filter, strict: strict) raw_refs, resolved_refs, used_refs = process_references(src_tree['used'].children) raw_refs.leaves { |node| node.data[:ref_type] = :reference_usage } ...
[ "def", "used_tree", "(", "key_filter", ":", "nil", ",", "strict", ":", "nil", ",", "include_raw_references", ":", "false", ")", "src_tree", "=", "used_in_source_tree", "(", "key_filter", ":", "key_filter", ",", "strict", ":", "strict", ")", "raw_refs", ",", ...
Find all keys in the source and return a forest with the keys in absolute form and their occurrences. @param key_filter [String] only return keys matching this pattern. @param strict [Boolean] if true, dynamic keys are excluded (e.g. `t("category.#{ category.key }")`) @param include_raw_references [Boolean] if true...
[ "Find", "all", "keys", "in", "the", "source", "and", "return", "a", "forest", "with", "the", "keys", "in", "absolute", "form", "and", "their", "occurrences", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/used_keys.rb#L36-L48
14,756
glebm/i18n-tasks
lib/i18n/tasks/scanners/ruby_key_literals.rb
I18n::Tasks::Scanners.RubyKeyLiterals.strip_literal
def strip_literal(literal) literal = literal[1..-1] if literal[0] == ':' literal = literal[1..-2] if literal[0] == "'" || literal[0] == '"' literal end
ruby
def strip_literal(literal) literal = literal[1..-1] if literal[0] == ':' literal = literal[1..-2] if literal[0] == "'" || literal[0] == '"' literal end
[ "def", "strip_literal", "(", "literal", ")", "literal", "=", "literal", "[", "1", "..", "-", "1", "]", "if", "literal", "[", "0", "]", "==", "':'", "literal", "=", "literal", "[", "1", "..", "-", "2", "]", "if", "literal", "[", "0", "]", "==", ...
remove the leading colon and unwrap quotes from the key match @param literal [String] e.g: "key", 'key', or :key. @return [String] key
[ "remove", "the", "leading", "colon", "and", "unwrap", "quotes", "from", "the", "key", "match" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/ruby_key_literals.rb#L17-L21
14,757
glebm/i18n-tasks
lib/i18n/tasks/missing_keys.rb
I18n::Tasks.MissingKeys.load_rails_i18n_pluralization!
def load_rails_i18n_pluralization!(locale) path = File.join(Gem::Specification.find_by_name('rails-i18n').gem_dir, 'rails', 'pluralization', "#{locale}.rb") eval(File.read(path), binding, path) # rubocop:disable Security/Eval end
ruby
def load_rails_i18n_pluralization!(locale) path = File.join(Gem::Specification.find_by_name('rails-i18n').gem_dir, 'rails', 'pluralization', "#{locale}.rb") eval(File.read(path), binding, path) # rubocop:disable Security/Eval end
[ "def", "load_rails_i18n_pluralization!", "(", "locale", ")", "path", "=", "File", ".", "join", "(", "Gem", "::", "Specification", ".", "find_by_name", "(", "'rails-i18n'", ")", ".", "gem_dir", ",", "'rails'", ",", "'pluralization'", ",", "\"#{locale}.rb\"", ")",...
Loads rails-i18n pluralization config for the given locale.
[ "Loads", "rails", "-", "i18n", "pluralization", "config", "for", "the", "given", "locale", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/missing_keys.rb#L91-L94
14,758
glebm/i18n-tasks
lib/i18n/tasks/missing_keys.rb
I18n::Tasks.MissingKeys.missing_diff_tree
def missing_diff_tree(locale, compared_to = base_locale) data[compared_to].select_keys do |key, _node| locale_key_missing? locale, depluralize_key(key, compared_to) end.set_root_key!(locale, type: :missing_diff).keys do |_key, node| # change path and locale to base data = { locale: l...
ruby
def missing_diff_tree(locale, compared_to = base_locale) data[compared_to].select_keys do |key, _node| locale_key_missing? locale, depluralize_key(key, compared_to) end.set_root_key!(locale, type: :missing_diff).keys do |_key, node| # change path and locale to base data = { locale: l...
[ "def", "missing_diff_tree", "(", "locale", ",", "compared_to", "=", "base_locale", ")", "data", "[", "compared_to", "]", ".", "select_keys", "do", "|", "key", ",", "_node", "|", "locale_key_missing?", "locale", ",", "depluralize_key", "(", "key", ",", "compare...
keys present in compared_to, but not in locale
[ "keys", "present", "in", "compared_to", "but", "not", "in", "locale" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/missing_keys.rb#L97-L108
14,759
glebm/i18n-tasks
lib/i18n/tasks/missing_keys.rb
I18n::Tasks.MissingKeys.missing_used_tree
def missing_used_tree(locale) used_tree(strict: true).select_keys do |key, _node| locale_key_missing?(locale, key) end.set_root_key!(locale, type: :missing_used) end
ruby
def missing_used_tree(locale) used_tree(strict: true).select_keys do |key, _node| locale_key_missing?(locale, key) end.set_root_key!(locale, type: :missing_used) end
[ "def", "missing_used_tree", "(", "locale", ")", "used_tree", "(", "strict", ":", "true", ")", ".", "select_keys", "do", "|", "key", ",", "_node", "|", "locale_key_missing?", "(", "locale", ",", "key", ")", "end", ".", "set_root_key!", "(", "locale", ",", ...
keys used in the code missing translations in locale
[ "keys", "used", "in", "the", "code", "missing", "translations", "in", "locale" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/missing_keys.rb#L111-L115
14,760
glebm/i18n-tasks
lib/i18n/tasks/scanners/pattern_scanner.rb
I18n::Tasks::Scanners.PatternScanner.scan_file
def scan_file(path) keys = [] text = read_file(path) text.scan(@pattern) do |match| src_pos = Regexp.last_match.offset(0).first location = occurrence_from_position(path, text, src_pos, raw_key: strip_literal(match[0])) next if exclude_line?(location.line, path) key = ma...
ruby
def scan_file(path) keys = [] text = read_file(path) text.scan(@pattern) do |match| src_pos = Regexp.last_match.offset(0).first location = occurrence_from_position(path, text, src_pos, raw_key: strip_literal(match[0])) next if exclude_line?(location.line, path) key = ma...
[ "def", "scan_file", "(", "path", ")", "keys", "=", "[", "]", "text", "=", "read_file", "(", "path", ")", "text", ".", "scan", "(", "@pattern", ")", "do", "|", "match", "|", "src_pos", "=", "Regexp", ".", "last_match", ".", "offset", "(", "0", ")", ...
Extract i18n keys from file based on the pattern which must capture the key literal. @return [Array<[key, Results::Occurrence]>] each occurrence found in the file
[ "Extract", "i18n", "keys", "from", "file", "based", "on", "the", "pattern", "which", "must", "capture", "the", "key", "literal", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/pattern_scanner.rb#L39-L55
14,761
glebm/i18n-tasks
lib/i18n/tasks/translators/google_translator.rb
I18n::Tasks::Translators.GoogleTranslator.to_google_translate_compatible_locale
def to_google_translate_compatible_locale(locale) return locale unless locale.include?('-') && !SUPPORTED_LOCALES_WITH_REGION.include?(locale) locale.split('-', 2).first end
ruby
def to_google_translate_compatible_locale(locale) return locale unless locale.include?('-') && !SUPPORTED_LOCALES_WITH_REGION.include?(locale) locale.split('-', 2).first end
[ "def", "to_google_translate_compatible_locale", "(", "locale", ")", "return", "locale", "unless", "locale", ".", "include?", "(", "'-'", ")", "&&", "!", "SUPPORTED_LOCALES_WITH_REGION", ".", "include?", "(", "locale", ")", "locale", ".", "split", "(", "'-'", ","...
Convert 'es-ES' to 'es'
[ "Convert", "es", "-", "ES", "to", "es" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/translators/google_translator.rb#L47-L50
14,762
glebm/i18n-tasks
lib/i18n/tasks/scanners/ruby_ast_scanner.rb
I18n::Tasks::Scanners.RubyAstScanner.scan_file
def scan_file(path) @parser.reset ast, comments = @parser.parse_with_comments(make_buffer(path)) results = @call_finder.collect_calls ast do |send_node, method_name| send_node_to_key_occurrence(send_node, method_name) end magic_comments = comments.select { |comment| comment.text...
ruby
def scan_file(path) @parser.reset ast, comments = @parser.parse_with_comments(make_buffer(path)) results = @call_finder.collect_calls ast do |send_node, method_name| send_node_to_key_occurrence(send_node, method_name) end magic_comments = comments.select { |comment| comment.text...
[ "def", "scan_file", "(", "path", ")", "@parser", ".", "reset", "ast", ",", "comments", "=", "@parser", ".", "parse_with_comments", "(", "make_buffer", "(", "path", ")", ")", "results", "=", "@call_finder", ".", "collect_calls", "ast", "do", "|", "send_node",...
Extract all occurrences of translate calls from the file at the given path. @return [Array<[key, Results::KeyOccurrence]>] each occurrence found in the file
[ "Extract", "all", "occurrences", "of", "translate", "calls", "from", "the", "file", "at", "the", "given", "path", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/ruby_ast_scanner.rb#L34-L59
14,763
glebm/i18n-tasks
lib/i18n/tasks/scanners/ruby_ast_scanner.rb
I18n::Tasks::Scanners.RubyAstScanner.extract_hash_pair
def extract_hash_pair(node, key) node.children.detect do |child| next unless child.type == :pair key_node = child.children[0] %i[sym str].include?(key_node.type) && key_node.children[0].to_s == key end end
ruby
def extract_hash_pair(node, key) node.children.detect do |child| next unless child.type == :pair key_node = child.children[0] %i[sym str].include?(key_node.type) && key_node.children[0].to_s == key end end
[ "def", "extract_hash_pair", "(", "node", ",", "key", ")", "node", ".", "children", ".", "detect", "do", "|", "child", "|", "next", "unless", "child", ".", "type", "==", ":pair", "key_node", "=", "child", ".", "children", "[", "0", "]", "%i[", "sym", ...
Extract a hash pair with a given literal key. @param node [AST::Node] a node of type `:hash`. @param key [String] node key as a string (indifferent symbol-string matching). @return [AST::Node, nil] a node of type `:pair` or nil.
[ "Extract", "a", "hash", "pair", "with", "a", "given", "literal", "key", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/ruby_ast_scanner.rb#L95-L101
14,764
glebm/i18n-tasks
lib/i18n/tasks/scanners/ruby_ast_scanner.rb
I18n::Tasks::Scanners.RubyAstScanner.extract_array_as_string
def extract_array_as_string(node, array_join_with:, array_flatten: false, array_reject_blank: false) children_strings = node.children.map do |child| if %i[sym str int true false].include?(child.type) # rubocop:disable Lint/BooleanSymbol extract_string child else # ignore dynami...
ruby
def extract_array_as_string(node, array_join_with:, array_flatten: false, array_reject_blank: false) children_strings = node.children.map do |child| if %i[sym str int true false].include?(child.type) # rubocop:disable Lint/BooleanSymbol extract_string child else # ignore dynami...
[ "def", "extract_array_as_string", "(", "node", ",", "array_join_with", ":", ",", "array_flatten", ":", "false", ",", "array_reject_blank", ":", "false", ")", "children_strings", "=", "node", ".", "children", ".", "map", "do", "|", "child", "|", "if", "%i[", ...
Extract an array as a single string. @param array_join_with [String] joiner of the array elements. @param array_flatten [Boolean] if true, nested arrays are flattened, otherwise their source is copied and surrounded by #{}. @param array_reject_blank [Boolean] if true, empty strings and `nil`s are skipped. @re...
[ "Extract", "an", "array", "as", "a", "single", "string", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/ruby_ast_scanner.rb#L150-L171
14,765
glebm/i18n-tasks
lib/i18n/tasks/data/tree/siblings.rb
I18n::Tasks::Data::Tree.Siblings.add_ancestors_that_only_contain_nodes!
def add_ancestors_that_only_contain_nodes!(nodes) levels.reverse_each do |level_nodes| level_nodes.each { |node| nodes << node if node.children? && node.children.all? { |c| nodes.include?(c) } } end end
ruby
def add_ancestors_that_only_contain_nodes!(nodes) levels.reverse_each do |level_nodes| level_nodes.each { |node| nodes << node if node.children? && node.children.all? { |c| nodes.include?(c) } } end end
[ "def", "add_ancestors_that_only_contain_nodes!", "(", "nodes", ")", "levels", ".", "reverse_each", "do", "|", "level_nodes", "|", "level_nodes", ".", "each", "{", "|", "node", "|", "nodes", "<<", "node", "if", "node", ".", "children?", "&&", "node", ".", "ch...
Adds all the ancestors that only contain the given nodes as descendants to the given nodes. @param nodes [Set] Modified in-place.
[ "Adds", "all", "the", "ancestors", "that", "only", "contain", "the", "given", "nodes", "as", "descendants", "to", "the", "given", "nodes", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/data/tree/siblings.rb#L226-L230
14,766
glebm/i18n-tasks
lib/i18n/tasks/reports/base.rb
I18n::Tasks::Reports.Base.sort_by_attr!
def sort_by_attr!(objects, order = { locale: :asc, key: :asc }) order_keys = order.keys objects.sort! do |a, b| by = order_keys.detect { |k| a[k] != b[k] } order[by] == :desc ? b[by] <=> a[by] : a[by] <=> b[by] end objects end
ruby
def sort_by_attr!(objects, order = { locale: :asc, key: :asc }) order_keys = order.keys objects.sort! do |a, b| by = order_keys.detect { |k| a[k] != b[k] } order[by] == :desc ? b[by] <=> a[by] : a[by] <=> b[by] end objects end
[ "def", "sort_by_attr!", "(", "objects", ",", "order", "=", "{", "locale", ":", ":asc", ",", "key", ":", ":asc", "}", ")", "order_keys", "=", "order", ".", "keys", "objects", ".", "sort!", "do", "|", "a", ",", "b", "|", "by", "=", "order_keys", ".",...
Sort keys by their attributes in order @param [Hash] order e.g. {locale: :asc, type: :desc, key: :asc}
[ "Sort", "keys", "by", "their", "attributes", "in", "order" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/reports/base.rb#L44-L51
14,767
glebm/i18n-tasks
lib/i18n/tasks/data.rb
I18n::Tasks.Data.data
def data @data ||= begin data_config = (config[:data] || {}).deep_symbolize_keys data_config[:base_locale] = base_locale data_config[:locales] = config[:locales] adapter_class = data_config[:adapter].presence || data_config[:class].presence || DATA_DEFAULTS[:adapter] adapte...
ruby
def data @data ||= begin data_config = (config[:data] || {}).deep_symbolize_keys data_config[:base_locale] = base_locale data_config[:locales] = config[:locales] adapter_class = data_config[:adapter].presence || data_config[:class].presence || DATA_DEFAULTS[:adapter] adapte...
[ "def", "data", "@data", "||=", "begin", "data_config", "=", "(", "config", "[", ":data", "]", "||", "{", "}", ")", ".", "deep_symbolize_keys", "data_config", "[", ":base_locale", "]", "=", "base_locale", "data_config", "[", ":locales", "]", "=", "config", ...
I18n data provider @see I18n::Tasks::Data::FileSystem
[ "I18n", "data", "provider" ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/data.rb#L13-L24
14,768
glebm/i18n-tasks
lib/i18n/tasks/references.rb
I18n::Tasks.References.merge_reference_trees
def merge_reference_trees(roots) roots.inject(empty_forest) do |forest, root| root.keys do |full_key, node| if full_key == node.value.to_s log_warn( "Self-referencing key #{node.full_key(root: false).inspect} in #{node.data[:locale].inspect}" ) end...
ruby
def merge_reference_trees(roots) roots.inject(empty_forest) do |forest, root| root.keys do |full_key, node| if full_key == node.value.to_s log_warn( "Self-referencing key #{node.full_key(root: false).inspect} in #{node.data[:locale].inspect}" ) end...
[ "def", "merge_reference_trees", "(", "roots", ")", "roots", ".", "inject", "(", "empty_forest", ")", "do", "|", "forest", ",", "root", "|", "root", ".", "keys", "do", "|", "full_key", ",", "node", "|", "if", "full_key", "==", "node", ".", "value", ".",...
Given a forest of references, merge trees into one tree, ensuring there are no conflicting references. @param roots [I18n::Tasks::Data::Tree::Siblings] @return [I18n::Tasks::Data::Tree::Siblings]
[ "Given", "a", "forest", "of", "references", "merge", "trees", "into", "one", "tree", "ensuring", "there", "are", "no", "conflicting", "references", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/references.rb#L77-L99
14,769
glebm/i18n-tasks
lib/i18n/tasks/scanners/files/file_reader.rb
I18n::Tasks::Scanners::Files.FileReader.read_file
def read_file(path) result = nil File.open(path, 'rb', encoding: 'UTF-8') { |f| result = f.read } result end
ruby
def read_file(path) result = nil File.open(path, 'rb', encoding: 'UTF-8') { |f| result = f.read } result end
[ "def", "read_file", "(", "path", ")", "result", "=", "nil", "File", ".", "open", "(", "path", ",", "'rb'", ",", "encoding", ":", "'UTF-8'", ")", "{", "|", "f", "|", "result", "=", "f", ".", "read", "}", "result", "end" ]
Return the contents of the file at the given path. The file is read in the 'rb' mode and UTF-8 encoding. @param path [String] Path to the file, absolute or relative to the working directory. @return [String] file contents
[ "Return", "the", "contents", "of", "the", "file", "at", "the", "given", "path", ".", "The", "file", "is", "read", "in", "the", "rb", "mode", "and", "UTF", "-", "8", "encoding", "." ]
56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5
https://github.com/glebm/i18n-tasks/blob/56b45e459d7d07bb19d613a17ffc1ce6f6f43cf5/lib/i18n/tasks/scanners/files/file_reader.rb#L13-L17
14,770
SciRuby/daru
lib/daru/index/categorical_index.rb
Daru.CategoricalIndex.pos
def pos *indexes positions = indexes.map do |index| if include? index @cat_hash[index] elsif index.is_a?(Numeric) && index < @array.size index else raise IndexError, "#{index.inspect} is neither a valid category"\ ' nor a valid position' en...
ruby
def pos *indexes positions = indexes.map do |index| if include? index @cat_hash[index] elsif index.is_a?(Numeric) && index < @array.size index else raise IndexError, "#{index.inspect} is neither a valid category"\ ' nor a valid position' en...
[ "def", "pos", "*", "indexes", "positions", "=", "indexes", ".", "map", "do", "|", "index", "|", "if", "include?", "index", "@cat_hash", "[", "index", "]", "elsif", "index", ".", "is_a?", "(", "Numeric", ")", "&&", "index", "<", "@array", ".", "size", ...
Returns positions given categories or positions @note If the argument does not a valid category it treats it as position value and return it as it is. @param indexes [Array<object>] categories or positions @example x = Daru::CategoricalIndex.new [:a, 1, :a, 1, :c] x.pos :a, 1 # => [0, 1, 2, 3]
[ "Returns", "positions", "given", "categories", "or", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/categorical_index.rb#L53-L67
14,771
SciRuby/daru
lib/daru/index/categorical_index.rb
Daru.CategoricalIndex.subset
def subset *indexes positions = pos(*indexes) new_index = positions.map { |pos| index_from_pos pos } Daru::CategoricalIndex.new new_index.flatten end
ruby
def subset *indexes positions = pos(*indexes) new_index = positions.map { |pos| index_from_pos pos } Daru::CategoricalIndex.new new_index.flatten end
[ "def", "subset", "*", "indexes", "positions", "=", "pos", "(", "indexes", ")", "new_index", "=", "positions", ".", "map", "{", "|", "pos", "|", "index_from_pos", "pos", "}", "Daru", "::", "CategoricalIndex", ".", "new", "new_index", ".", "flatten", "end" ]
Return subset given categories or positions @param indexes [Array<object>] categories or positions @return [Daru::CategoricalIndex] subset of the self containing the mentioned categories or positions @example idx = Daru::CategoricalIndex.new [:a, :b, :a, :b, :c] idx.subset :a, :b # => #<Daru::Categorical...
[ "Return", "subset", "given", "categories", "or", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/categorical_index.rb#L155-L160
14,772
SciRuby/daru
lib/daru/index/categorical_index.rb
Daru.CategoricalIndex.at
def at *positions positions = preprocess_positions(*positions) validate_positions(*positions) if positions.is_a? Integer index_from_pos(positions) else Daru::CategoricalIndex.new positions.map(&method(:index_from_pos)) end end
ruby
def at *positions positions = preprocess_positions(*positions) validate_positions(*positions) if positions.is_a? Integer index_from_pos(positions) else Daru::CategoricalIndex.new positions.map(&method(:index_from_pos)) end end
[ "def", "at", "*", "positions", "positions", "=", "preprocess_positions", "(", "positions", ")", "validate_positions", "(", "positions", ")", "if", "positions", ".", "is_a?", "Integer", "index_from_pos", "(", "positions", ")", "else", "Daru", "::", "CategoricalInde...
Takes positional values and returns subset of the self capturing the categories at mentioned positions @param positions [Array<Integer>] positional values @return [object] index object @example idx = Daru::CategoricalIndex.new [:a, :b, :a, :b, :c] idx.at 0, 1 # => #<Daru::CategoricalIndex(2): {a, b}>
[ "Takes", "positional", "values", "and", "returns", "subset", "of", "the", "self", "capturing", "the", "categories", "at", "mentioned", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/categorical_index.rb#L170-L178
14,773
SciRuby/daru
lib/daru/index/multi_index.rb
Daru.MultiIndex.validate_name
def validate_name names, levels error_msg = "'names' and 'levels' should be of same size. Size of the "\ "'name' array is #{names.size} and size of the MultiIndex 'levels' and "\ "'labels' is #{labels.size}." suggestion_msg = "If you don\'t want to set name for particular level " \ "(say l...
ruby
def validate_name names, levels error_msg = "'names' and 'levels' should be of same size. Size of the "\ "'name' array is #{names.size} and size of the MultiIndex 'levels' and "\ "'labels' is #{labels.size}." suggestion_msg = "If you don\'t want to set name for particular level " \ "(say l...
[ "def", "validate_name", "names", ",", "levels", "error_msg", "=", "\"'names' and 'levels' should be of same size. Size of the \"", "\"'name' array is #{names.size} and size of the MultiIndex 'levels' and \"", "\"'labels' is #{labels.size}.\"", "suggestion_msg", "=", "\"If you don\\'t want to...
Array `name` must have same length as levels and labels.
[ "Array", "name", "must", "have", "same", "length", "as", "levels", "and", "labels", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/index/multi_index.rb#L266-L275
14,774
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.[]
def [](*input_indexes) # Get array of positions indexes positions = @index.pos(*input_indexes) # If one object is asked return it return @data[positions] if positions.is_a? Numeric # Form a new Vector using positional indexes Daru::Vector.new( positions.map { |loc| @data[lo...
ruby
def [](*input_indexes) # Get array of positions indexes positions = @index.pos(*input_indexes) # If one object is asked return it return @data[positions] if positions.is_a? Numeric # Form a new Vector using positional indexes Daru::Vector.new( positions.map { |loc| @data[lo...
[ "def", "[]", "(", "*", "input_indexes", ")", "# Get array of positions indexes", "positions", "=", "@index", ".", "pos", "(", "input_indexes", ")", "# If one object is asked return it", "return", "@data", "[", "positions", "]", "if", "positions", ".", "is_a?", "Nume...
Get one or more elements with specified index or a range. == Usage # For vectors employing single layer Index v[:one, :two] # => Daru::Vector with indexes :one and :two v[:one] # => Single element v[:one..:three] # => Daru::Vector with indexes :one, :two and :three # For vectors employing hiera...
[ "Get", "one", "or", "more", "elements", "with", "specified", "index", "or", "a", "range", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L238-L251
14,775
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.at
def at *positions # to be used to form index original_positions = positions positions = coerce_positions(*positions) validate_positions(*positions) if positions.is_a? Integer @data[positions] else values = positions.map { |pos| @data[pos] } Daru::Vector.new v...
ruby
def at *positions # to be used to form index original_positions = positions positions = coerce_positions(*positions) validate_positions(*positions) if positions.is_a? Integer @data[positions] else values = positions.map { |pos| @data[pos] } Daru::Vector.new v...
[ "def", "at", "*", "positions", "# to be used to form index", "original_positions", "=", "positions", "positions", "=", "coerce_positions", "(", "positions", ")", "validate_positions", "(", "positions", ")", "if", "positions", ".", "is_a?", "Integer", "@data", "[", "...
Returns vector of values given positional values @param positions [Array<object>] positional values @return [object] vector @example dv = Daru::Vector.new 'a'..'e' dv.at 0, 1, 2 # => #<Daru::Vector(3)> # 0 a # 1 b # 2 c
[ "Returns", "vector", "of", "values", "given", "positional", "values" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L263-L275
14,776
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.set_at
def set_at positions, val validate_positions(*positions) positions.map { |pos| @data[pos] = val } update_position_cache end
ruby
def set_at positions, val validate_positions(*positions) positions.map { |pos| @data[pos] = val } update_position_cache end
[ "def", "set_at", "positions", ",", "val", "validate_positions", "(", "positions", ")", "positions", ".", "map", "{", "|", "pos", "|", "@data", "[", "pos", "]", "=", "val", "}", "update_position_cache", "end" ]
Change value at given positions @param positions [Array<object>] positional values @param [object] val value to assign @example dv = Daru::Vector.new 'a'..'e' dv.set_at [0, 1], 'x' dv # => #<Daru::Vector(5)> # 0 x # 1 x # 2 c # 3 d # 4 e
[ "Change", "value", "at", "given", "positions" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L290-L294
14,777
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.concat
def concat element, index raise IndexError, 'Expected new unique index' if @index.include? index @index |= [index] @data[@index[index]] = element update_position_cache end
ruby
def concat element, index raise IndexError, 'Expected new unique index' if @index.include? index @index |= [index] @data[@index[index]] = element update_position_cache end
[ "def", "concat", "element", ",", "index", "raise", "IndexError", ",", "'Expected new unique index'", "if", "@index", ".", "include?", "index", "@index", "|=", "[", "index", "]", "@data", "[", "@index", "[", "index", "]", "]", "=", "element", "update_position_c...
Append an element to the vector by specifying the element and index
[ "Append", "an", "element", "to", "the", "vector", "by", "specifying", "the", "element", "and", "index" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L509-L516
14,778
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.cast
def cast opts={} dt = opts[:dtype] raise ArgumentError, "Unsupported dtype #{opts[:dtype]}" unless %i[array nmatrix gsl].include?(dt) @data = cast_vector_to dt unless @dtype == dt end
ruby
def cast opts={} dt = opts[:dtype] raise ArgumentError, "Unsupported dtype #{opts[:dtype]}" unless %i[array nmatrix gsl].include?(dt) @data = cast_vector_to dt unless @dtype == dt end
[ "def", "cast", "opts", "=", "{", "}", "dt", "=", "opts", "[", ":dtype", "]", "raise", "ArgumentError", ",", "\"Unsupported dtype #{opts[:dtype]}\"", "unless", "%i[", "array", "nmatrix", "gsl", "]", ".", "include?", "(", "dt", ")", "@data", "=", "cast_vector_...
Cast a vector to a new data type. == Options * +:dtype+ - :array for Ruby Array. :nmatrix for NMatrix.
[ "Cast", "a", "vector", "to", "a", "new", "data", "type", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L525-L530
14,779
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.delete_at
def delete_at index @data.delete_at @index[index] @index = Daru::Index.new(@index.to_a - [index]) update_position_cache end
ruby
def delete_at index @data.delete_at @index[index] @index = Daru::Index.new(@index.to_a - [index]) update_position_cache end
[ "def", "delete_at", "index", "@data", ".", "delete_at", "@index", "[", "index", "]", "@index", "=", "Daru", "::", "Index", ".", "new", "(", "@index", ".", "to_a", "-", "[", "index", "]", ")", "update_position_cache", "end" ]
Delete element by index
[ "Delete", "element", "by", "index" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L538-L543
14,780
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.index_of
def index_of element case dtype when :array then @index.key(@data.index { |x| x.eql? element }) else @index.key @data.index(element) end end
ruby
def index_of element case dtype when :array then @index.key(@data.index { |x| x.eql? element }) else @index.key @data.index(element) end end
[ "def", "index_of", "element", "case", "dtype", "when", ":array", "then", "@index", ".", "key", "(", "@data", ".", "index", "{", "|", "x", "|", "x", ".", "eql?", "element", "}", ")", "else", "@index", ".", "key", "@data", ".", "index", "(", "element",...
Get index of element
[ "Get", "index", "of", "element" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L578-L583
14,781
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.uniq
def uniq uniq_vector = @data.uniq new_index = uniq_vector.map { |element| index_of(element) } Daru::Vector.new uniq_vector, name: @name, index: new_index, dtype: @dtype end
ruby
def uniq uniq_vector = @data.uniq new_index = uniq_vector.map { |element| index_of(element) } Daru::Vector.new uniq_vector, name: @name, index: new_index, dtype: @dtype end
[ "def", "uniq", "uniq_vector", "=", "@data", ".", "uniq", "new_index", "=", "uniq_vector", ".", "map", "{", "|", "element", "|", "index_of", "(", "element", ")", "}", "Daru", "::", "Vector", ".", "new", "uniq_vector", ",", "name", ":", "@name", ",", "in...
Keep only unique elements of the vector alongwith their indexes.
[ "Keep", "only", "unique", "elements", "of", "the", "vector", "alongwith", "their", "indexes", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L586-L591
14,782
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.sort_by_index
def sort_by_index opts={} opts = {ascending: true}.merge(opts) _, new_order = resort_index(@index.each_with_index, opts).transpose reorder new_order end
ruby
def sort_by_index opts={} opts = {ascending: true}.merge(opts) _, new_order = resort_index(@index.each_with_index, opts).transpose reorder new_order end
[ "def", "sort_by_index", "opts", "=", "{", "}", "opts", "=", "{", "ascending", ":", "true", "}", ".", "merge", "(", "opts", ")", "_", ",", "new_order", "=", "resort_index", "(", "@index", ".", "each_with_index", ",", "opts", ")", ".", "transpose", "reor...
Sorts the vector according to it's`Index` values. Defaults to ascending order sorting. @param [Hash] opts the options for sort_by_index method. @option opts [Boolean] :ascending false, will sort `index` in descending order. @return [Vector] new sorted `Vector` according to the index values. @example dv = ...
[ "Sorts", "the", "vector", "according", "to", "it", "s", "Index", "values", ".", "Defaults", "to", "ascending", "order", "sorting", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L646-L651
14,783
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.recode!
def recode! dt=nil, &block return to_enum(:recode!) unless block_given? @data.map!(&block).data @data = cast_vector_to(dt || @dtype) self end
ruby
def recode! dt=nil, &block return to_enum(:recode!) unless block_given? @data.map!(&block).data @data = cast_vector_to(dt || @dtype) self end
[ "def", "recode!", "dt", "=", "nil", ",", "&", "block", "return", "to_enum", "(", ":recode!", ")", "unless", "block_given?", "@data", ".", "map!", "(", "block", ")", ".", "data", "@data", "=", "cast_vector_to", "(", "dt", "||", "@dtype", ")", "self", "e...
Destructive version of recode!
[ "Destructive", "version", "of", "recode!" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L682-L688
14,784
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.delete_if
def delete_if return to_enum(:delete_if) unless block_given? keep_e, keep_i = each_with_index.reject { |n, _i| yield(n) }.transpose @data = cast_vector_to @dtype, keep_e @index = Daru::Index.new(keep_i) update_position_cache self end
ruby
def delete_if return to_enum(:delete_if) unless block_given? keep_e, keep_i = each_with_index.reject { |n, _i| yield(n) }.transpose @data = cast_vector_to @dtype, keep_e @index = Daru::Index.new(keep_i) update_position_cache self end
[ "def", "delete_if", "return", "to_enum", "(", ":delete_if", ")", "unless", "block_given?", "keep_e", ",", "keep_i", "=", "each_with_index", ".", "reject", "{", "|", "n", ",", "_i", "|", "yield", "(", "n", ")", "}", ".", "transpose", "@data", "=", "cast_v...
Delete an element if block returns true. Destructive.
[ "Delete", "an", "element", "if", "block", "returns", "true", ".", "Destructive", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L691-L702
14,785
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.verify
def verify (0...size) .map { |i| [i, @data[i]] } .reject { |_i, val| yield(val) } .to_h end
ruby
def verify (0...size) .map { |i| [i, @data[i]] } .reject { |_i, val| yield(val) } .to_h end
[ "def", "verify", "(", "0", "...", "size", ")", ".", "map", "{", "|", "i", "|", "[", "i", ",", "@data", "[", "i", "]", "]", "}", ".", "reject", "{", "|", "_i", ",", "val", "|", "yield", "(", "val", ")", "}", ".", "to_h", "end" ]
Reports all values that doesn't comply with a condition. Returns a hash with the index of data and the invalid data.
[ "Reports", "all", "values", "that", "doesn", "t", "comply", "with", "a", "condition", ".", "Returns", "a", "hash", "with", "the", "index", "of", "data", "and", "the", "invalid", "data", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L713-L718
14,786
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.lag
def lag k=1 case k when 0 then dup when 1...size copy([nil] * k + data.to_a) when -size..-1 copy(data.to_a[k.abs...size]) else copy([]) end end
ruby
def lag k=1 case k when 0 then dup when 1...size copy([nil] * k + data.to_a) when -size..-1 copy(data.to_a[k.abs...size]) else copy([]) end end
[ "def", "lag", "k", "=", "1", "case", "k", "when", "0", "then", "dup", "when", "1", "...", "size", "copy", "(", "[", "nil", "]", "*", "k", "+", "data", ".", "to_a", ")", "when", "-", "size", "..", "-", "1", "copy", "(", "data", ".", "to_a", ...
Lags the series by `k` periods. Lags the series by `k` periods, "shifting" data and inserting `nil`s from beginning or end of a vector, while preserving original vector's size. `k` can be positive or negative integer. If `k` is positive, `nil`s are inserted at the beginning of the vector, otherwise they are ins...
[ "Lags", "the", "series", "by", "k", "periods", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L851-L861
14,787
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.to_matrix
def to_matrix axis=:horizontal if axis == :horizontal Matrix[to_a] elsif axis == :vertical Matrix.columns([to_a]) else raise ArgumentError, "axis should be either :horizontal or :vertical, not #{axis}" end end
ruby
def to_matrix axis=:horizontal if axis == :horizontal Matrix[to_a] elsif axis == :vertical Matrix.columns([to_a]) else raise ArgumentError, "axis should be either :horizontal or :vertical, not #{axis}" end end
[ "def", "to_matrix", "axis", "=", ":horizontal", "if", "axis", "==", ":horizontal", "Matrix", "[", "to_a", "]", "elsif", "axis", "==", ":vertical", "Matrix", ".", "columns", "(", "[", "to_a", "]", ")", "else", "raise", "ArgumentError", ",", "\"axis should be ...
Convert Vector to a horizontal or vertical Ruby Matrix. == Arguments * +axis+ - Specify whether you want a *:horizontal* or a *:vertical* matrix.
[ "Convert", "Vector", "to", "a", "horizontal", "or", "vertical", "Ruby", "Matrix", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L920-L928
14,788
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.to_nmatrix
def to_nmatrix axis=:horizontal unless numeric? && !include?(nil) raise ArgumentError, 'Can not convert to nmatrix'\ 'because the vector is numeric' end case axis when :horizontal NMatrix.new [1, size], to_a when :vertical NMatrix.new [size, 1], to_a ...
ruby
def to_nmatrix axis=:horizontal unless numeric? && !include?(nil) raise ArgumentError, 'Can not convert to nmatrix'\ 'because the vector is numeric' end case axis when :horizontal NMatrix.new [1, size], to_a when :vertical NMatrix.new [size, 1], to_a ...
[ "def", "to_nmatrix", "axis", "=", ":horizontal", "unless", "numeric?", "&&", "!", "include?", "(", "nil", ")", "raise", "ArgumentError", ",", "'Can not convert to nmatrix'", "'because the vector is numeric'", "end", "case", "axis", "when", ":horizontal", "NMatrix", "....
Convert vector to nmatrix object @param [Symbol] axis :horizontal or :vertical @return [NMatrix] NMatrix object containing all values of the vector @example dv = Daru::Vector.new [1, 2, 3] dv.to_nmatrix # => # [ # [1, 2, 3] ]
[ "Convert", "vector", "to", "nmatrix", "object" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L939-L954
14,789
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.object_summary
def object_summary nval = count_values(*Daru::MISSING_VALUES) summary = "\n factors: #{factors.to_a.join(',')}" \ "\n mode: #{mode.to_a.join(',')}" \ "\n Distribution\n" data = frequencies.sort.each_with_index.map do |v, k| [k, v, '%0.2f%%' % ((nval.zero? ? ...
ruby
def object_summary nval = count_values(*Daru::MISSING_VALUES) summary = "\n factors: #{factors.to_a.join(',')}" \ "\n mode: #{mode.to_a.join(',')}" \ "\n Distribution\n" data = frequencies.sort.each_with_index.map do |v, k| [k, v, '%0.2f%%' % ((nval.zero? ? ...
[ "def", "object_summary", "nval", "=", "count_values", "(", "Daru", "::", "MISSING_VALUES", ")", "summary", "=", "\"\\n factors: #{factors.to_a.join(',')}\"", "\"\\n mode: #{mode.to_a.join(',')}\"", "\"\\n Distribution\\n\"", "data", "=", "frequencies", ".", "sort", ".", ...
Displays summary for an object type Vector @return [String] String containing object vector summary
[ "Displays", "summary", "for", "an", "object", "type", "Vector" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1050-L1061
14,790
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.numeric_summary
def numeric_summary summary = "\n median: #{median}" + "\n mean: %0.4f" % mean if sd summary << "\n std.dev.: %0.4f" % sd + "\n std.err.: %0.4f" % se end if count_values(*Daru::MISSING_VALUES).zero? summary << "\n skew: %0.4f" % skew + ...
ruby
def numeric_summary summary = "\n median: #{median}" + "\n mean: %0.4f" % mean if sd summary << "\n std.dev.: %0.4f" % sd + "\n std.err.: %0.4f" % se end if count_values(*Daru::MISSING_VALUES).zero? summary << "\n skew: %0.4f" % skew + ...
[ "def", "numeric_summary", "summary", "=", "\"\\n median: #{median}\"", "+", "\"\\n mean: %0.4f\"", "%", "mean", "if", "sd", "summary", "<<", "\"\\n std.dev.: %0.4f\"", "%", "sd", "+", "\"\\n std.err.: %0.4f\"", "%", "se", "end", "if", "count_values", "(", "Daru", ...
Displays summary for an numeric type Vector @return [String] String containing numeric vector summary
[ "Displays", "summary", "for", "an", "numeric", "type", "Vector" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1065-L1078
14,791
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.inspect
def inspect spacing=20, threshold=15 row_headers = index.is_a?(MultiIndex) ? index.sparse_tuples : index.to_a "#<#{self.class}(#{size})#{':category' if category?}>\n" + Formatters::Table.format( to_a.lazy.map { |v| [v] }, headers: @name && [@name], row_headers: row_hea...
ruby
def inspect spacing=20, threshold=15 row_headers = index.is_a?(MultiIndex) ? index.sparse_tuples : index.to_a "#<#{self.class}(#{size})#{':category' if category?}>\n" + Formatters::Table.format( to_a.lazy.map { |v| [v] }, headers: @name && [@name], row_headers: row_hea...
[ "def", "inspect", "spacing", "=", "20", ",", "threshold", "=", "15", "row_headers", "=", "index", ".", "is_a?", "(", "MultiIndex", ")", "?", "index", ".", "sparse_tuples", ":", "index", ".", "to_a", "\"#<#{self.class}(#{size})#{':category' if category?}>\\n\"", "+...
Over rides original inspect for pretty printing in irb
[ "Over", "rides", "original", "inspect", "for", "pretty", "printing", "in", "irb" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1081-L1092
14,792
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.reindex!
def reindex! new_index values = [] each_with_index do |val, i| values[new_index[i]] = val if new_index.include?(i) end values.fill(nil, values.size, new_index.size - values.size) @data = cast_vector_to @dtype, values @index = new_index update_position_cache sel...
ruby
def reindex! new_index values = [] each_with_index do |val, i| values[new_index[i]] = val if new_index.include?(i) end values.fill(nil, values.size, new_index.size - values.size) @data = cast_vector_to @dtype, values @index = new_index update_position_cache sel...
[ "def", "reindex!", "new_index", "values", "=", "[", "]", "each_with_index", "do", "|", "val", ",", "i", "|", "values", "[", "new_index", "[", "i", "]", "]", "=", "val", "if", "new_index", ".", "include?", "(", "i", ")", "end", "values", ".", "fill", ...
Sets new index for vector. Preserves index->value correspondence. Sets nil for new index keys absent from original index. @note Unlike #reorder! which takes positions as input it takes index as an input to reorder the vector @param [Daru::Index, Daru::MultiIndex] new_index new index to order with @return [Daru::...
[ "Sets", "new", "index", "for", "vector", ".", "Preserves", "index", "-", ">", "value", "correspondence", ".", "Sets", "nil", "for", "new", "index", "keys", "absent", "from", "original", "index", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1100-L1113
14,793
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.only_valid
def only_valid as_a=:vector, _duplicate=true # FIXME: Now duplicate is just ignored. # There are no spec that fail on this case, so I'll leave it # this way for now - zverok, 2016-05-07 new_index = @index.to_a - indexes(*Daru::MISSING_VALUES) new_vector = new_index.map { |idx| self[id...
ruby
def only_valid as_a=:vector, _duplicate=true # FIXME: Now duplicate is just ignored. # There are no spec that fail on this case, so I'll leave it # this way for now - zverok, 2016-05-07 new_index = @index.to_a - indexes(*Daru::MISSING_VALUES) new_vector = new_index.map { |idx| self[id...
[ "def", "only_valid", "as_a", "=", ":vector", ",", "_duplicate", "=", "true", "# FIXME: Now duplicate is just ignored.", "# There are no spec that fail on this case, so I'll leave it", "# this way for now - zverok, 2016-05-07", "new_index", "=", "@index", ".", "to_a", "-", "in...
Creates a new vector consisting only of non-nil data == Arguments @param as_a [Symbol] Passing :array will return only the elements as an Array. Otherwise will return a Daru::Vector. @param _duplicate [Symbol] In case no missing data is found in the vector, setting this to false will return the same vector. Ot...
[ "Creates", "a", "new", "vector", "consisting", "only", "of", "non", "-", "nil", "data" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1267-L1280
14,794
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.only_numerics
def only_numerics numeric_indexes = each_with_index .select { |v, _i| v.is_a?(Numeric) || v.nil? } .map(&:last) self[*numeric_indexes] end
ruby
def only_numerics numeric_indexes = each_with_index .select { |v, _i| v.is_a?(Numeric) || v.nil? } .map(&:last) self[*numeric_indexes] end
[ "def", "only_numerics", "numeric_indexes", "=", "each_with_index", ".", "select", "{", "|", "v", ",", "_i", "|", "v", ".", "is_a?", "(", "Numeric", ")", "||", "v", ".", "nil?", "}", ".", "map", "(", ":last", ")", "self", "[", "numeric_indexes", "]", ...
Returns a Vector with only numerical data. Missing data is included but non-Numeric objects are excluded. Preserves index.
[ "Returns", "a", "Vector", "with", "only", "numerical", "data", ".", "Missing", "data", "is", "included", "but", "non", "-", "Numeric", "objects", "are", "excluded", ".", "Preserves", "index", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1353-L1360
14,795
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.db_type
def db_type # first, detect any character not number case when @data.any? { |v| v.to_s =~ DATE_REGEXP } 'DATE' when @data.any? { |v| v.to_s =~ /[^0-9e.-]/ } 'VARCHAR (255)' when @data.any? { |v| v.to_s =~ /\./ } 'DOUBLE' else 'INTEGER' end en...
ruby
def db_type # first, detect any character not number case when @data.any? { |v| v.to_s =~ DATE_REGEXP } 'DATE' when @data.any? { |v| v.to_s =~ /[^0-9e.-]/ } 'VARCHAR (255)' when @data.any? { |v| v.to_s =~ /\./ } 'DOUBLE' else 'INTEGER' end en...
[ "def", "db_type", "# first, detect any character not number", "case", "when", "@data", ".", "any?", "{", "|", "v", "|", "v", ".", "to_s", "=~", "DATE_REGEXP", "}", "'DATE'", "when", "@data", ".", "any?", "{", "|", "v", "|", "v", ".", "to_s", "=~", "/", ...
Returns the database type for the vector, according to its content
[ "Returns", "the", "database", "type", "for", "the", "vector", "according", "to", "its", "content" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1365-L1377
14,796
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.to_category
def to_category opts={} dv = Daru::Vector.new to_a, type: :category, name: @name, index: @index dv.ordered = opts[:ordered] || false dv.categories = opts[:categories] if opts[:categories] dv end
ruby
def to_category opts={} dv = Daru::Vector.new to_a, type: :category, name: @name, index: @index dv.ordered = opts[:ordered] || false dv.categories = opts[:categories] if opts[:categories] dv end
[ "def", "to_category", "opts", "=", "{", "}", "dv", "=", "Daru", "::", "Vector", ".", "new", "to_a", ",", "type", ":", ":category", ",", "name", ":", "@name", ",", "index", ":", "@index", "dv", ".", "ordered", "=", "opts", "[", ":ordered", "]", "||"...
Converts a non category type vector to category type vector. @param [Hash] opts options to convert to category @option opts [true, false] :ordered Specify if vector is ordered or not. If it is ordered, it can be sorted and min, max like functions would work @option opts [Array] :categories set categories in the s...
[ "Converts", "a", "non", "category", "type", "vector", "to", "category", "type", "vector", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1417-L1422
14,797
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.cut
def cut partitions, opts={} close_at, labels = opts[:close_at] || :right, opts[:labels] partitions = partitions.to_a values = to_a.map { |val| cut_find_category partitions, val, close_at } cats = cut_categories(partitions, close_at) dv = Daru::Vector.new values, index: @index, ...
ruby
def cut partitions, opts={} close_at, labels = opts[:close_at] || :right, opts[:labels] partitions = partitions.to_a values = to_a.map { |val| cut_find_category partitions, val, close_at } cats = cut_categories(partitions, close_at) dv = Daru::Vector.new values, index: @index, ...
[ "def", "cut", "partitions", ",", "opts", "=", "{", "}", "close_at", ",", "labels", "=", "opts", "[", ":close_at", "]", "||", ":right", ",", "opts", "[", ":labels", "]", "partitions", "=", "partitions", ".", "to_a", "values", "=", "to_a", ".", "map", ...
Partition a numeric variable into categories. @param [Array<Numeric>] partitions an array whose consecutive elements provide intervals for categories @param [Hash] opts options to cut the partition @option opts [:left, :right] :close_at specifies whether the interval closes at the right side of left side @opt...
[ "Partition", "a", "numeric", "variable", "into", "categories", "." ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1458-L1475
14,798
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.valid_value?
def valid_value?(v) v.respond_to?(:nan?) && v.nan? || v.nil? ? false : true end
ruby
def valid_value?(v) v.respond_to?(:nan?) && v.nan? || v.nil? ? false : true end
[ "def", "valid_value?", "(", "v", ")", "v", ".", "respond_to?", "(", ":nan?", ")", "&&", "v", ".", "nan?", "||", "v", ".", "nil?", "?", "false", ":", "true", "end" ]
Helper method returning validity of arbitrary value
[ "Helper", "method", "returning", "validity", "of", "arbitrary", "value" ]
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1520-L1522
14,799
SciRuby/daru
lib/daru/vector.rb
Daru.Vector.prepare_bootstrap
def prepare_bootstrap(estimators) h_est = estimators h_est = [h_est] unless h_est.is_a?(Array) || h_est.is_a?(Hash) if h_est.is_a? Array h_est = h_est.map do |est| [est, ->(v) { Daru::Vector.new(v).send(est) }] end.to_h end bss = h_est.keys.map { |v| [v, []] }.to...
ruby
def prepare_bootstrap(estimators) h_est = estimators h_est = [h_est] unless h_est.is_a?(Array) || h_est.is_a?(Hash) if h_est.is_a? Array h_est = h_est.map do |est| [est, ->(v) { Daru::Vector.new(v).send(est) }] end.to_h end bss = h_est.keys.map { |v| [v, []] }.to...
[ "def", "prepare_bootstrap", "(", "estimators", ")", "h_est", "=", "estimators", "h_est", "=", "[", "h_est", "]", "unless", "h_est", ".", "is_a?", "(", "Array", ")", "||", "h_est", ".", "is_a?", "(", "Hash", ")", "if", "h_est", ".", "is_a?", "Array", "h...
For an array or hash of estimators methods, returns an array with three elements 1.- A hash with estimators names as keys and lambdas as values 2.- An array with estimators names 3.- A Hash with estimators names as keys and empty arrays as values
[ "For", "an", "array", "or", "hash", "of", "estimators", "methods", "returns", "an", "array", "with", "three", "elements", "1", ".", "-", "A", "hash", "with", "estimators", "names", "as", "keys", "and", "lambdas", "as", "values", "2", ".", "-", "An", "a...
d17887e279c27e2b2ec7a252627c04b4b03c0a7a
https://github.com/SciRuby/daru/blob/d17887e279c27e2b2ec7a252627c04b4b03c0a7a/lib/daru/vector.rb#L1572-L1584