idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
4,400
def get_all_schedules schedules = { } if SidekiqScheduler :: RedisManager . schedule_exist? SidekiqScheduler :: RedisManager . get_all_schedules . tap do | h | h . each do | name , config | schedules [ name ] = JSON . parse ( config ) end end end schedules end
gets the schedule as it exists in redis
4,401
def set_schedule ( name , config ) existing_config = get_schedule ( name ) unless existing_config && existing_config == config SidekiqScheduler :: RedisManager . set_job_schedule ( name , config ) SidekiqScheduler :: RedisManager . add_schedule_change ( name ) end config end
Create or update a schedule with the provided name and configuration .
4,402
def remove_schedule ( name ) SidekiqScheduler :: RedisManager . remove_job_schedule ( name ) SidekiqScheduler :: RedisManager . add_schedule_change ( name ) end
remove a given schedule by name
4,403
def load_schedule! if enabled Sidekiq . logger . info 'Loading Schedule' if dynamic Sidekiq . reload_schedule! @current_changed_score = Time . now . to_f rufus_scheduler . every ( dynamic_every ) do update_schedule end end Sidekiq . logger . info 'Schedule empty! Set Sidekiq.schedule' if Sidekiq . schedule . empty? @sc...
Pulls the schedule from Sidekiq . schedule and loads it into the rufus scheduler instance
4,404
def idempotent_job_enqueue ( job_name , time , config ) registered = SidekiqScheduler :: RedisManager . register_job_instance ( job_name , time ) if registered Sidekiq . logger . info "queueing #{config['class']} (#{job_name})" handle_errors { enqueue_job ( config , time ) } SidekiqScheduler :: RedisManager . remove_el...
Pushes the job into Sidekiq if not already pushed for the given time
4,405
def enqueue_job ( job_config , time = Time . now ) config = prepare_arguments ( job_config . dup ) if config . delete ( 'include_metadata' ) config [ 'args' ] = arguments_with_metadata ( config [ 'args' ] , scheduled_at : time . to_f ) end if active_job_enqueue? ( config [ 'class' ] ) SidekiqScheduler :: Utils . enqueu...
Enqueue a job based on a config hash
4,406
def schedule_state ( name ) state = SidekiqScheduler :: RedisManager . get_job_state ( name ) state ? JSON . parse ( state ) : { } end
Retrieves a schedule state
4,407
def arguments_with_metadata ( args , metadata ) if args . is_a? Array [ * args , metadata ] else [ args , metadata ] end end
Adds a Hash with schedule metadata as the last argument to call the worker . It currently returns the schedule time as a Float number representing the milisencods since epoch .
4,408
def active_job_enqueue? ( klass ) klass . is_a? ( Class ) && defined? ( ActiveJob :: Enqueuing ) && klass . included_modules . include? ( ActiveJob :: Enqueuing ) end
Returns true if the enqueuing needs to be done for an ActiveJob class false otherwise .
4,409
def prepare_arguments ( config ) config [ 'class' ] = SidekiqScheduler :: Utils . try_to_constantize ( config [ 'class' ] ) if config [ 'args' ] . is_a? ( Hash ) config [ 'args' ] . symbolize_keys! if config [ 'args' ] . respond_to? ( :symbolize_keys! ) else config [ 'args' ] = Array ( config [ 'args' ] ) end config en...
Convert the given arguments in the format expected to be enqueued .
4,410
def next_time execution_time = SidekiqScheduler :: RedisManager . get_job_next_time ( name ) relative_time ( Time . parse ( execution_time ) ) if execution_time end
Returns the next time execution for the job
4,411
def last_time execution_time = SidekiqScheduler :: RedisManager . get_job_last_time ( name ) relative_time ( Time . parse ( execution_time ) ) if execution_time end
Returns the last execution time for the job
4,412
def deprecated ( gone_on : , & block ) response . set_header ( "Sunset" , Date . parse ( gone_on ) . in_time_zone ( "GMT" ) . midnight . strftime ( "%a, %e %b %Y %H:%M:%S %Z" ) ) Rails . logger . info ( "DEPRECATED ENDPOINT #{request.method} to #{request.fullpath} requested by #{current_user.id}" ) block . ( ) end
Indicate that this endpoint is deprecated and will go away on the given date .
4,413
def align_column n , alignment r = rows column ( n ) . each_with_index do | col , i | cell = r [ i ] [ n ] next unless cell cell . alignment = alignment unless cell . alignment? end end
Generates a ASCII table with the given _options_ .
4,414
def add_row array row = array == :separator ? Separator . new ( self ) : Row . new ( self , array ) @rows << row require_column_widths_recalc unless row . is_a? ( Separator ) end
Add a row .
4,415
def column n , method = :value , array = rows array . map { | row | index = col = 0 row . cells . each do | cell | break if index > n index += cell . colspan col += 1 end cell = row [ col - 1 ] cell && method ? cell . __send__ ( method ) : cell } . compact end
Return column _n_ .
4,416
def headings = arrays arrays = [ arrays ] unless arrays . first . is_a? ( Array ) @headings = arrays . map do | array | row = Row . new ( self , array ) require_column_widths_recalc row end end
Set the headings
4,417
def render separator = Separator . new ( self ) buffer = style . border_top ? [ separator ] : [ ] unless @title . nil? buffer << Row . new ( self , [ title_cell_options ] ) buffer << separator end @headings . each do | row | unless row . cells . empty? buffer << row buffer << separator end end if style . all_separators...
Render the table .
4,418
def analyze Core :: Runner . base_path = @path Core :: Runner . config_path = @options [ 'config' ] @runner = Core :: Runner . new analyze_source_codes analyze_vcs end
Analyze rails codes .
4,419
def process ( process ) parse_files . each do | file | begin puts file if @options [ 'debug' ] @runner . send ( process , file , File . read ( file ) ) rescue StandardError if @options [ 'debug' ] warning = "#{file} looks like it's not a valid Ruby file. Skipping..." plain_output ( warning , 'red' ) end end @bar . inc...
process lexical prepare or reivew .
4,420
def parse_files @parse_files ||= begin files = expand_dirs_to_files ( @path ) files = file_sort ( files ) if @options [ 'only' ] . present? files = file_accept ( files , @options [ 'only' ] ) end %w[ vendor spec test features tmp ] . each do | dir | files = file_ignore ( files , File . join ( @path , dir ) ) unless @op...
get all files for parsing .
4,421
def expand_dirs_to_files ( * dirs ) extensions = %w[ rb erb rake rhtml haml slim builder rxml rabl ] dirs . flatten . map do | entry | next unless File . exist? entry if File . directory? entry Dir [ File . join ( entry , '**' , "*.{#{extensions.join(',')}}" ) ] else entry end end . flatten end
expand all files with extenstion rb erb haml slim builder and rxml under the dirs
4,422
def file_sort ( files ) models = files . find_all { | file | file =~ Core :: Check :: MODEL_FILES } mailers = files . find_all { | file | file =~ Core :: Check :: MAILER_FILES } helpers = files . find_all { | file | file =~ Core :: Check :: HELPER_FILES } others = files . find_all { | file | file !~ Core :: Check :: MA...
sort files models first mailers helpers and then sort other files by characters .
4,423
def file_accept ( files , patterns ) files . select { | file | patterns . any? { | pattern | file =~ pattern } } end
accept specific files .
4,424
def output_json_errors errors_as_hashes = errors . map do | err | { filename : err . filename , line_number : err . line_number , message : err . message } end File . open ( @options [ 'output-file' ] , 'w+' ) do | file | file . write JSON . dump ( errors_as_hashes ) end end
output errors with json format .
4,425
def plain_output ( message , color ) if @options [ 'without-color' ] puts message else puts Colorize . send ( color , message ) end end
plain output with color .
4,426
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
analyze source codes .
4,427
def _run_callbacks ( kind , * args ) options = args . last send ( "_#{kind}" ) . each do | callback , conditions | invalid = conditions . find do | key , value | value . is_a? ( Array ) ? ! value . include? ( options [ key ] ) : ( value != options [ key ] ) end callback . call ( * args ) unless invalid end end
Hook to _run_callbacks asserting for conditions .
4,428
def after_failed_fetch ( options = { } , method = :push , & block ) raise BlockNotGiven unless block_given? _after_failed_fetch . send ( method , [ block , options ] ) end
A callback that runs if no user could be fetched meaning there is now no user logged in .
4,429
def before_logout ( options = { } , method = :push , & block ) raise BlockNotGiven unless block_given? _before_logout . send ( method , [ block , options ] ) end
A callback that runs just prior to the logout of each scope .
4,430
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
4,431
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_callbacks , true ) manager ...
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 .
4,432
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 raw_session . nil? session_ser...
Provides logout functionality . The logout also manages any authenticated data storage and clears it when a user logs out .
4,433
def _run_strategies_for ( scope , args ) self . winning_strategy = @winning_strategies [ scope ] return if winning_strategy && winning_strategy . halted? return if @locked if args . empty? defaults = @config [ :default_strategies ] strategies = defaults [ scope ] || defaults [ :_all ] end ( strategies || args ) . each ...
Run the strategies for a given scope
4,434
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
Fetches strategies and keep them in a hash cache .
4,435
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 when '...
Parse errors from the server respons if any
4,436
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
Creates a new Client instance which proxies the requests to the certain classes
4,437
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
Search for Spots with a query
4,438
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
Search for Spots within a give SW|NE bounds with query
4,439
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
Search for Spots with a pagetoken
4,440
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
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 ...
4,441
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 , :retry_options => retry_options ) end ...
Search for a Photo s url with its reference key
4,442
def const_missing ( name ) Attribute :: Builder . determine_type ( name ) or Axiom :: Types . const_defined? ( name ) && Axiom :: Types . const_get ( name ) or super end
Hooks into const missing process to determine types of attributes
4,443
def each return to_enum unless block_given? @index . each { | name , attribute | yield attribute if name . kind_of? ( Symbol ) } self end
Initialize an AttributeSet
4,444
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
4,445
def define_writer_method ( attribute , method_name , visibility ) define_method ( method_name ) { | value | attribute . set ( self , value ) } send ( visibility , method_name ) end
Defines an attribute writer method
4,446
def get ( object ) each_with_object ( { } ) do | attribute , attributes | name = attribute . name attributes [ name ] = object . __send__ ( name ) if attribute . public_reader? end end
Get values of all attributes defined for this class ignoring privacy
4,447
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
Mass - assign attribute values
4,448
def set_defaults ( object , filter = method ( :skip_default? ) ) each do | attribute | next if filter . call ( object , attribute ) attribute . set_default_value ( object ) end end
Set default attributes
4,449
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 end type end
Return the class given a primitive
4,450
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
4,451
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
4,452
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 ) ModuleExtensions . setup ( object , @inclusions , @attribute_definitio...
Extend a class with Virtus methods and define attributes
4,453
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_method ) end end e...
Adds the . included hook to the anonymous module which then defines the . attribute method to override the default .
4,454
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
Returns default options hash for a given attribute class
4,455
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
Defines which options are valid for a given attribute class
4,456
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 ) ...
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 .
4,457
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
Get back an array of timecodes for a period
4,458
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
A very simple param encoder
4,459
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
constant - time compare the strings
4,460
def verify ( otp , counter , retries : 0 ) counters = ( counter .. counter + retries ) . to_a counters . find do | c | super ( otp , at ( c ) ) end end
Verifies the OTP passed in against the current time OTP
4,461
def ec2_metadata raise "Called ec2_metadata with platform=#{@platform}" unless @platform == Platform :: EC2 unless @ec2_metadata open ( 'http://' + METADATA_SERVICE_ADDR + '/latest/dynamic/instance-identity/document' ) do | f | contents = f . read @ec2_metadata = JSON . parse ( contents ) end end @ec2_metadata end
EC2 Metadata server returns everything in one call . Store it after the first fetch to avoid making multiple calls .
4,462
def set_required_metadata_variables set_project_id set_vm_id set_vm_name set_location missing = [ ] missing << 'project_id' unless @project_id if @platform != Platform :: OTHER missing << 'zone' unless @zone missing << 'vm_id' unless @vm_id end return if missing . empty? raise Fluent :: ConfigError , "Unable to obtain ...
Set required variables like
4,463
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
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 .
4,464
def set_location @zone ||= fetch_gce_metadata ( 'instance/zone' ) . rpartition ( '/' ) [ 2 ] if @platform == Platform :: GCE aws_location_key = if @use_aws_availability_zone 'availabilityZone' else 'region' end @zone ||= 'aws:' + ec2_metadata [ aws_location_key ] if @platform == Platform :: EC2 && ec2_metadata . key? (...
1 . Return the value if it is explicitly set in the config already . 2 . If not try to retrieve it locally .
4,465
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 end
Retrieve monitored resource via the legacy way .
4,466
def determine_agent_level_monitored_resource_type case @platform when Platform :: OTHER return COMPUTE_CONSTANTS [ :resource_type ] when Platform :: EC2 return EC2_CONSTANTS [ :resource_type ] when Platform :: GCE return SUBSERVICE_MAP [ @subservice_name ] if @subservice_name if @detect_subservice begin attributes = fe...
Determine agent level monitored resource type .
4,467
def determine_agent_level_monitored_resource_labels ( type ) case type when APPENGINE_CONSTANTS [ :resource_type ] return { 'module_id' => fetch_gce_metadata ( 'instance/attributes/gae_backend_name' ) , 'version_id' => fetch_gce_metadata ( 'instance/attributes/gae_backend_version' ) } when COMPUTE_CONSTANTS [ :resource...
Determine agent level monitored resource labels based on the resource type . Each resource type has its own labels that need to be filled in .
4,468
def determine_agent_level_common_labels labels = { } labels . merge! ( @labels ) if @labels case @resource . type when APPENGINE_CONSTANTS [ :resource_type ] , DATAFLOW_CONSTANTS [ :resource_type ] , DATAPROC_CONSTANTS [ :resource_type ] , ML_CONSTANTS [ :resource_type ] labels . merge! ( "#{COMPUTE_CONSTANTS[:service]...
Determine the common labels that should be added to all log entries processed by this logging agent .
4,469
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 JSON format.' next end sanitized_tag = sanitize_tag ( tag...
Group the log entries by tag and local_resource_id pairs . Also filter out invalid non - Hash entries .
4,470
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 matched_regexp_group = nil @tag_regexp_list . each do | derived_type , tag_regexp | matched_regexp_group = tag_regexp . match (...
Determine the group level monitored resource and common labels shared by a collection of entries .
4,471
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 ( local_resource_id ) @log . debug 'Retrieved monito...
Take a locally unique resource id and convert it to the globally unique monitored resource .
4,472
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 when CLOUDFUNCTIONS_CONSTANTS [ :resour...
Extract entry level monitored resource and common labels that should be applied to individual entries .
4,473
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 json ' "format: '#{response.i...
Issue a request to the Metadata Agent s local API and parse the response to JSON . Return nil in case of failure .
4,474
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 end non_string_keys = payload_labels . e...
Parse labels . Return nil if not set .
4,475
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
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 .
4,476
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_labels [ new_label ...
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 .
4,477
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 encoding issues potentially due to non ' 'UTF-8 characters. To allow non-UTF-8...
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 .
4,478
def construct_k8s_resource_locally ( local_resource_id ) return unless / \. \. \. /x =~ local_resource_id || / \. \. /x =~ local_resource_id || / \. /x =~ local_resource_id @k8s_cluster_name = nil if @k8s_cluster_name == '' @k8s_cluster_location = nil if @k8s_cluster_location == '' begin @k8s_cluster_name ||= fetch_gce...
Construct monitored resource locally for k8s resources .
4,479
def counter ( name , desc ) return @registry . counter ( name , desc ) rescue Prometheus :: Client :: Registry :: AlreadyRegisteredError return @registry . get ( name ) end
Exception - driven behavior to avoid synchronization errors .
4,480
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
Initialize the Rack middleware for responding to serviceworker asset requests
4,481
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...
Find all keys in the source and return a forest with the keys in absolute form and their occurrences .
4,482
def strip_literal ( literal ) literal = literal [ 1 .. - 1 ] if literal [ 0 ] == ':' literal = literal [ 1 .. - 2 ] if literal [ 0 ] == "'" || literal [ 0 ] == '"' literal end
remove the leading colon and unwrap quotes from the key match
4,483
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 ) end
Loads rails - i18n pluralization config for the given locale .
4,484
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 | data = { locale : locale , missing_diff_locale : node . da...
keys present in compared_to but not in locale
4,485
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
keys used in the code missing translations in locale
4,486
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 = match_to_k...
Extract i18n keys from file based on the pattern which must capture the key literal .
4,487
def to_google_translate_compatible_locale ( locale ) return locale unless locale . include? ( '-' ) && ! SUPPORTED_LOCALES_WITH_REGION . include? ( locale ) locale . split ( '-' , 2 ) . first end
Convert es - ES to es
4,488
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 =~ MAGIC_CO...
Extract all occurrences of translate calls from the file at the given path .
4,489
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
Extract a hash pair with a given literal key .
4,490
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 ) extract_string child else return nil if config [ :strict ] if %i[ dsym dstr ] . include? ( child...
Extract an array as a single string .
4,491
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
Adds all the ancestors that only contain the given nodes as descendants to the given nodes .
4,492
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
Sort keys by their attributes in order
4,493
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 ] adapter_class = adapte...
I18n data provider
4,494
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 end forest . merge! ( root . children , on_leaves_...
Given a forest of references merge trees into one tree ensuring there are no conflicting references .
4,495
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 .
4,496
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' end end positions . flatten! positions . size == 1 ? positions . fi...
Returns positions given categories or positions
4,497
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
4,498
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
Takes positional values and returns subset of the self capturing the categories at mentioned positions
4,499
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 level 'i') then put empty string o...
Array name must have same length as levels and labels .