idx int64 0 24.9k | question stringlengths 68 4.14k | target stringlengths 9 749 |
|---|---|---|
6,600 | def send ( notice , promise ) return will_not_deliver ( notice ) if @unsent . size >= @unsent . max @unsent << [ notice , promise ] promise end | Asynchronously sends a notice to Airbrake . |
6,601 | def []= ( key , value ) raise_if_ignored unless WRITABLE_KEYS . include? ( key ) raise Airbrake :: Error , ":#{key} is not recognized among #{WRITABLE_KEYS}" end unless value . respond_to? ( :to_hash ) raise Airbrake :: Error , "Got #{value.class} value, wanted a Hash" end @payload [ key ] = value . to_hash end | Writes a value to the payload hash . Restricts unrecognized writes . |
6,602 | def run_swiftlint ( files , lint_all_files , options , additional_swiftlint_args ) if lint_all_files result = swiftlint . lint ( options , additional_swiftlint_args ) if result == '' { } else JSON . parse ( result ) . flatten end else files . map { | file | options . merge ( path : file ) } . map { | full_options | swi... | Run swiftlint on each file and aggregate collect the issues |
6,603 | def find_swift_files ( dir_selected , files = nil , excluded_paths = [ ] , included_paths = [ ] ) dir_selected = Shellwords . escape ( dir_selected ) files = if files . nil? ( git . modified_files - git . deleted_files ) + git . added_files else Dir . glob ( files ) end files . select { | file | file . end_with? ( '.sw... | Find swift files from the files glob If files are not provided it will use git modifield and added files |
6,604 | def load_config ( filepath ) return { } if filepath . nil? || ! File . exist? ( filepath ) config_file = File . open ( filepath ) . read config_file = parse_environment_variables ( config_file ) YAML . safe_load ( config_file ) end | Get the configuration file |
6,605 | def parse_environment_variables ( file_contents ) file_contents . gsub ( / \$ \{ \} / ) do | env_var | return env_var if ENV [ Regexp . last_match [ 1 ] ] . nil? ENV [ Regexp . last_match [ 1 ] ] end end | Find all requested environment variables in the given string and replace them with the correct values . |
6,606 | def file_exists? ( paths , file ) paths . any? do | path | Find . find ( path ) . map { | path_file | Shellwords . escape ( path_file ) } . include? ( file ) end end | Return whether the file exists within a specified collection of paths |
6,607 | def format_paths ( paths , filepath ) paths . map { | path | File . join ( File . dirname ( filepath ) , path ) } . map { | path | File . expand_path ( path ) } . select { | path | File . exist? ( path ) || Dir . exist? ( path ) } end | Parses the configuration file and return the specified files in path |
6,608 | def markdown_issues ( results , heading ) message = "#### #{heading}\n\n" . dup message << "File | Line | Reason |\n" message << "| --- | ----- | ----- |\n" results . each do | r | filename = r [ 'file' ] . split ( '/' ) . last line = r [ 'line' ] reason = r [ 'reason' ] rule = r [ 'rule_id' ] message << "#{filename} |... | Create a markdown table from swiftlint issues |
6,609 | def check_signature ( secret ) digest = OpenSSL :: Digest :: SHA256 . new expected = OpenSSL :: HMAC . hexdigest ( digest , secret , @body ) if @signature == expected return true else Pusher . logger . warn "Received WebHook with invalid signature: got #{@signature}, expected #{expected}" return false end end | Checks signature against secret and returns boolean |
6,610 | def url = ( url ) uri = URI . parse ( url ) @scheme = uri . scheme @app_id = uri . path . split ( '/' ) . last @key = uri . user @secret = uri . password @host = uri . host @port = uri . port end | Configure Pusher connection by providing a url rather than specifying scheme key secret and app_id separately . |
6,611 | def trigger ( channels , event_name , data , params = { } ) post ( '/events' , trigger_params ( channels , event_name , data , params ) ) end | Trigger an event on one or more channels |
6,612 | def trigger ( event_name , data , socket_id = nil ) trigger! ( event_name , data , socket_id ) rescue Pusher :: Error => e Pusher . logger . error ( "#{e.message} (#{e.class})" ) Pusher . logger . debug ( e . backtrace . join ( "\n" ) ) end | Trigger event catching and logging any errors . |
6,613 | def authentication_string ( socket_id , custom_string = nil ) validate_socket_id ( socket_id ) unless custom_string . nil? || custom_string . kind_of? ( String ) raise Error , 'Custom argument must be a string' end string_to_sign = [ socket_id , name , custom_string ] . compact . map ( & :to_s ) . join ( ':' ) Pusher .... | Compute authentication string required as part of the authentication endpoint response . Generally the authenticate method should be used in preference to this one |
6,614 | def render ( template , entry ) template . render ( File . join ( 'pageflow' , name , 'widget' ) , entry : entry ) end | Override to return html as string . |
6,615 | def has_at_least_role? ( role ) @user . memberships . where ( role : Roles . at_least ( role ) ) . where ( '(entity_id = :account_id AND ' "entity_type = 'Pageflow::Account')" , account_id : @account . id ) . any? end | Create query that can be used for role comparisons |
6,616 | def register ( name , options = { } ) help_entry = HelpEntry . new ( name , options ) @help_entries_by_name [ name ] = help_entry collection = find_collection ( options [ :parent ] ) collection << help_entry collection . sort_by! { | help_entry | - help_entry . priority } end | Add a section to the help dialog displayed in the editor . |
6,617 | def call ( rack_env ) begin env = { } bad_route = route_request ( rack_env , env ) return error_response ( bad_route , env ) if bad_route @before . each do | hook | result = hook . call ( rack_env , env ) return error_response ( result , env ) if result . is_a? Twirp :: Error end output = call_handler ( env ) return er... | Rack app handler . |
6,618 | def route_request ( rack_env , env ) rack_request = Rack :: Request . new ( rack_env ) if rack_request . request_method != "POST" return bad_route_error ( "HTTP request method must be POST" , rack_request ) end content_type = rack_request . get_header ( "CONTENT_TYPE" ) if ! Encoding . valid_content_type? ( content_typ... | Parse request and fill env with rpc data . Returns a bad_route error if something went wrong . |
6,619 | def rpc ( rpc_method , input_class , output_class , opts ) raise ArgumentError . new ( "rpc_method can not be empty" ) if rpc_method . to_s . empty? raise ArgumentError . new ( "input_class must be a Protobuf Message class" ) unless input_class . is_a? ( Class ) raise ArgumentError . new ( "output_class must be a Proto... | Configure service rpc methods . |
6,620 | def find_child ( method , * args ) children . find do | child | Launchy . log "Checking if class #{child} is the one for #{method}(#{args.join(', ')})}" child . send ( method , * args ) end end | Find one of the child classes by calling the given method and passing all the rest of the parameters to that method in each child |
6,621 | def capture_log_messages ( opts = { } ) from = opts . fetch ( :from , 'root' ) to = opts . fetch ( :to , '__rspec__' ) exclusive = opts . fetch ( :exclusive , true ) appender = Logging :: Appenders [ to ] || Logging :: Appenders :: StringIo . new ( to ) logger = Logging :: Logger [ from ] if exclusive logger . appender... | Capture log messages from the Logging framework and make them available via a |
6,622 | def parent_name ( key ) return if :root == key a = key . split PATH_DELIMITER p = :root while a . slice! ( - 1 ) and ! a . empty? k = a . join PATH_DELIMITER if @h . has_key? k then p = k ; break end end p end | Returns the name of the parent for the logger identified by the given _key_ . If the _key_ is for the root logger then + nil + is returned . |
6,623 | def build_singleton_methods method = case @age when 'daily' -> { now = Time . now ( now . day != age_fn_mtime . day ) || ( now - age_fn_mtime ) > 86400 } when 'weekly' -> { ( Time . now - age_fn_mtime ) > 604800 } when 'monthly' -> { now = Time . now ( now . month != age_fn_mtime . month ) || ( now - age_fn_mtime ) > 2... | We use meta - programming here to define the sufficiently_aged? method for the rolling appender . The sufficiently_aged? method is responsible for determining if the current log file is older than the rolling criteria - daily weekly etc . |
6,624 | def auto_flushing = ( period ) @auto_flushing = case period when true ; 1 when false , nil , 0 ; DEFAULT_BUFFER_SIZE when Integer ; period when String ; Integer ( period ) else raise ArgumentError , "unrecognized auto_flushing period: #{period.inspect}" end if @auto_flushing <= 0 raise ArgumentError , "auto_flushing pe... | Configure the auto - flushing threshold . Auto - flushing is used to flush the contents of the logging buffer to the logging destination automatically when the buffer reaches a certain threshold . |
6,625 | def _setup_async_flusher if @async_flusher @async_flusher . stop @async_flusher = nil Thread . pass end if @flush_period || async? @auto_flushing = DEFAULT_BUFFER_SIZE unless @auto_flushing > 1 @async_flusher = AsyncFlusher . new ( self , @flush_period ) @async_flusher . start Thread . pass end nil end | Using the flush_period create a new AsyncFlusher attached to this appender . If the flush_period is nil then no action will be taken . If a AsyncFlusher already exists it will be stopped and a new one will be created . |
6,626 | def []= ( color_tag , constants ) @scheme [ to_key ( color_tag ) ] = constants . respond_to? ( :map ) ? constants . map { | c | to_constant ( c ) } . join : to_constant ( constants ) end | Allow the scheme to be set like a Hash . |
6,627 | def to_constant ( v ) v = v . to_s . upcase ColorScheme . const_get ( v ) if ( ColorScheme . const_defined? ( v , false ) rescue ColorScheme . const_defined? ( v ) ) end | Return a normalized representation of a color setting . |
6,628 | def encoding = ( value ) if value . nil? @encoding = nil else @encoding = Object . const_defined? ( :Encoding ) ? Encoding . find ( value . to_s ) : nil end end | Set the appender encoding to the given value . The value can either be an Encoding instance or a String or Symbol referring to a valid encoding . |
6,629 | def allow ( event ) return nil if @level > event . level @filters . each do | filter | break unless event = filter . allow ( event ) end event end | Check to see if the event should be processed by the appender . An event will be rejected if the event level is lower than the configured level for the appender . Or it will be rejected if one of the filters rejects the event . |
6,630 | def context c = Thread . current . thread_variable_get ( NAME ) if c . nil? c = if Thread . current . thread_variable_get ( STACK_NAME ) flatten ( stack ) else Hash . new end Thread . current . thread_variable_set ( NAME , c ) end return c end | Returns the Hash acting as the storage for this MappedDiagnosticContext . A new storage Hash is created for each Thread running in the application . |
6,631 | def stack s = Thread . current . thread_variable_get ( STACK_NAME ) if s . nil? s = [ { } ] Thread . current . thread_variable_set ( STACK_NAME , s ) end return s end | Returns the stack of Hash objects that are storing the diagnostic context information . This stack is guarnteed to always contain at least one Hash . |
6,632 | def sanitize ( hash , target = { } ) unless hash . is_a? ( Hash ) raise ArgumentError , "Expecting a Hash but received a #{hash.class.name}" end hash . each { | k , v | target [ k . to_s ] = v } return target end | Given a Hash convert all keys into Strings . The values are not altered in any way . The converted keys and their values are stored in the target Hash if provided . Otherwise a new Hash is created and returned . |
6,633 | def context c = Thread . current . thread_variable_get ( NAME ) if c . nil? c = Array . new Thread . current . thread_variable_set ( NAME , c ) end return c end | Returns the Array acting as the storage stack for this NestedDiagnosticContext . A new storage Array is created for each Thread running in the application . |
6,634 | def iso8601_format ( time ) value = apply_utc_offset ( time ) str = value . strftime ( '%Y-%m-%dT%H:%M:%S' ) str << ( '.%06d' % value . usec ) offset = value . gmt_offset . abs return str << 'Z' if offset == 0 offset = sprintf ( '%02d:%02d' , offset / 3600 , offset % 3600 / 60 ) return str << ( value . gmt_offset < 0 ?... | Convert the given time into an ISO8601 formatted time string . |
6,635 | def as_json ( _options = { } ) hash = { } instance_variables . each do | var | name = var [ 1 .. - 1 ] if name =~ / / name = name [ 1 .. - 1 ] elsif name =~ / / name = nil end hash [ name ] = instance_variable_get ( var ) if name end hash end | Use instance variables to build a json object . Instance variables that begin with a single underscore are elided . Instance variables that begin with two underscores have one of them removed . |
6,636 | def find ( broadcast_id ) raise ArgumentError , "broadcast_id not provided" if broadcast_id . to_s . empty? broadcast_json = @client . get_broadcast ( broadcast_id . to_s ) Broadcast . new self , broadcast_json end | Gets a Broadcast object for the given broadcast ID . |
6,637 | def stop ( broadcast_id ) raise ArgumentError , "broadcast_id not provided" if broadcast_id . to_s . empty? broadcast_json = @client . stop_broadcast ( broadcast_id ) Broadcast . new self , broadcast_json end | Stops an OpenTok broadcast |
6,638 | def create_session ( opts = { } ) valid_opts = [ :media_mode , :location , :archive_mode ] opts = opts . inject ( { } ) do | m , ( k , v ) | if valid_opts . include? k . to_sym m [ k . to_sym ] = v end m end params = opts . clone if params . delete ( :media_mode ) == :routed params [ "p2p.preference" ] = "disabled" els... | Create a new OpenTok object . |
6,639 | def all ( session_id ) raise ArgumentError , 'session_id not provided' if session_id . to_s . empty? response_json = @client . info_stream ( session_id , '' ) StreamList . new response_json end | Use this method to get information on all OpenTok streams in a session . |
6,640 | def find ( archive_id ) raise ArgumentError , "archive_id not provided" if archive_id . to_s . empty? archive_json = @client . get_archive ( archive_id . to_s ) Archive . new self , archive_json end | Gets an Archive object for the given archive ID . |
6,641 | def all ( options = { } ) raise ArgumentError , "Limit is invalid" unless options [ :count ] . nil? or ( 0 .. 1000 ) . include? options [ :count ] archive_list_json = @client . list_archives ( options [ :offset ] , options [ :count ] , options [ :sessionId ] ) ArchiveList . new self , archive_list_json end | Returns an ArchiveList which is an array of archives that are completed and in - progress for your API key . |
6,642 | def stop_by_id ( archive_id ) raise ArgumentError , "archive_id not provided" if archive_id . to_s . empty? archive_json = @client . stop_archive ( archive_id ) Archive . new self , archive_json end | Stops an OpenTok archive that is being recorded . |
6,643 | def delete_by_id ( archive_id ) raise ArgumentError , "archive_id not provided" if archive_id . to_s . empty? response = @client . delete_archive ( archive_id ) ( 200 .. 300 ) . include? response . code end | Deletes an OpenTok archive . |
6,644 | def find_email ( address , opts = { } ) address = convert_address ( address ) if opts [ :with_subject ] expected_subject = ( opts [ :with_subject ] . is_a? ( String ) ? Regexp . escape ( opts [ :with_subject ] ) : opts [ :with_subject ] ) mailbox_for ( address ) . find { | m | m . subject =~ Regexp . new ( expected_sub... | Should be able to accept String or Regexp options . |
6,645 | def path_to_parts ( path ) path . downcase . split ( '/' ) . map { | part | part . empty? ? nil : part . strip } . compact end | Internal method to split a path into components |
6,646 | def navigated url = get_location @params = [ ] idx = match ( path_to_parts ( decode ( url . pathname ) ) , decode ( url . search ) ) if idx @routes [ idx ] [ :callback ] . call ( @params ) else @page404 . call ( url . pathname ) end end | Internal method called when the web browser navigates |
6,647 | def match ( path , search ) matches = get_matches ( path ) if matches . length > 0 match = matches . sort { | m | m [ 1 ] } . first @params = match [ 2 ] add_search_to_params ( search ) match [ 0 ] else nil end end | Internal method to match a path to the most likely route |
6,648 | def get_matches ( path ) matches = [ ] @routes . each_with_index do | route , i | score , pars = score_route ( route [ :parts ] , path ) matches << [ i , score , pars ] if score > 0 end matches end | Internal method to match a path to possible routes |
6,649 | def score_route ( parts , path ) score = 0 pars = { } if parts . length == path . length parts . each_with_index do | part , i | if part [ 0 ] == ':' score += 1 pars [ "#{part[1..-1]}" ] = path [ i ] elsif part == path [ i ] . downcase score += 2 end end end return score , pars end | Internal method to add a match score |
6,650 | def add_search_to_params ( search ) if ! search . empty? pars = search [ 1 .. - 1 ] . split ( '&' ) pars . each do | par | pair = par . split ( '=' ) @params [ pair [ 0 ] ] = pair [ 1 ] if pair . length == 2 end end end | Internal method to split search parameters |
6,651 | def dasherize ( class_name ) return class_name if class_name !~ / / c = class_name . to_s . gsub ( '::' , '' ) ( c [ 0 ] + c [ 1 .. - 1 ] . gsub ( / / ) { | c | "-#{c}" } ) . downcase . gsub ( '_' , '-' ) end | Convert a Ruby classname to a dasherized name for use with CSS . |
6,652 | def composite_state ( class_name , state ) if @compositor list = @compositor . css_classes_for ( "#{class_name}::#{state}" ) return list if ! list . empty? end [ dasherize ( state ) ] end | Convert a state - name to a list of CSS class names . |
6,653 | def composite_classes ( target , element , add_superclass ) if @compositor composite_for ( target . class . name , element ) if add_superclass composite_for ( target . class . superclass . name , element ) end end end | Internal method Composite CSS classes from Ruby class name |
6,654 | def css_classes_for_map ( classname , mapping ) css = mapping [ classname ] css . class == String ? css_classes_for_map ( css , mapping ) : ( css || [ ] ) end | Internal method to get mapping from selected map . |
6,655 | def switch_theme ( root_element , theme ) old_map = @mapping new_map = map ( theme ) root_element . each_child do | e | old_classes = css_classes_for_map e . class . name , old_map new_classes = css_classes_for_map e . class . name , new_map update_element_css_classes ( e , old_classes , new_classes ) old_classes = css... | Internal method to switch to a new theme . |
6,656 | def _stylize styles = style if styles . class == Hash set_attribute ( 'style' , styles . map { | k , v | "#{k}:#{v};" } . join ) end end | Internal method . |
6,657 | def add_child ( name , element_class , options = { } ) sym = symbolize ( name ) raise "Child '#{sym}' already defined" if @children . has_key? ( sym ) raise "Illegal name (#{sym})" if RESERVED_NAMES . include? ( sym ) @children [ sym ] = element_class . new ( self , sym , options ) end | Add a child element . |
6,658 | def each_child ( & block ) if block_given? block . call self @children . each do | _ , child | child . each_child ( & block ) end end end | Recursively iterate all child elements |
6,659 | def _replace_options ( string , options ) s = string . gsub ( '<' , '<' ) . gsub ( '>' , '>' ) if options s . gsub ( / \{ \w \} / ) do | m | key = ( $1 || m . tr ( "%{}" , "" ) ) if options . key? ( key ) options [ key ] . to_s . gsub ( '<' , '<' ) . gsub ( '>' , '>' ) else key end end else s end end | Internal method to substitute placeholders with a value . |
6,660 | def option_replace ( key , default = nil ) value = @options [ key ] || default @options . delete ( key ) if @options . has_key? ( key ) value end | Delete a key from the elements options hash . Will be renamed to option_delete . |
6,661 | def update_state ( state , active ) if ! active . nil? @states . each do | s , v | v [ 1 ] = active if s == state classify_state v end end end | Update the value of the state . |
6,662 | def toggle_state ( state ) @states . select { | s , _ | s == state } . each do | s , v | v [ 1 ] = ! v [ 1 ] classify_state v end end | Toggle the boolean value of the state |
6,663 | def route ( message ) @params . clear @message = message result = nil if @bounce_block and message . respond_to? ( :bounced? ) and message . bounced? return instance_exec ( & @bounce_block ) end routes . each do | route | break if result = route . match! ( message ) end if result @params . merge! ( result [ :params ] )... | Route a message . If the route block accepts arguments it passes any captured params . Named params are available from the + params + helper . The message is available from the + message + helper . |
6,664 | def match! ( message ) params = { } args = [ ] @conditions . each do | condition | if result = condition . match ( message ) params . merge! ( result [ 0 ] ) args += result [ 1 ] else return nil end end { :block => @block , :klass => @klass , :params => params , :args => args } end | Checks whether a message matches the route . |
6,665 | def run Mailman . logger . info "Mailman v#{Mailman::VERSION} started" if config . rails_root rails_env = File . join ( config . rails_root , 'config' , 'environment.rb' ) if File . exist? ( rails_env ) && ! ( defined? ( :: Rails ) && :: Rails . env ) Mailman . logger . info "Rails root found in #{config.rails_root}, r... | Runs the application . |
6,666 | def polling_loop ( connection ) if polling? polling_msg = "Polling enabled. Checking every #{config.poll_interval} seconds." else polling_msg = "Polling disabled. Checking for messages once." end Mailman . logger . info ( polling_msg ) tries ||= 5 loop do begin connection . connect connection . get_messages rescue Syst... | Run the polling loop for the email inbox connection |
6,667 | def hypernova_batch_render ( job ) if @hypernova_batch . nil? raise NilBatchError . new ( 'called hypernova_batch_render without calling ' 'hypernova_batch_before. Check your around_filter for :hypernova_render_support' ) end batch_token = @hypernova_batch . render ( job ) template_safe_token = Hypernova . render_token... | enqueue a render into the current request s hypernova batch |
6,668 | def render_react_component ( component , data = { } ) begin new_data = get_view_data ( component , data ) rescue StandardError => e on_error ( e ) new_data = data end job = { :data => new_data , :name => component , } hypernova_batch_render ( job ) end | shortcut method to render a react component |
6,669 | def hypernova_batch_after if @hypernova_batch . nil? raise NilBatchError . new ( 'called hypernova_batch_after without calling ' 'hypernova_batch_before. Check your around_filter for :hypernova_render_support' ) end return if @hypernova_batch . empty? jobs = @hypernova_batch . jobs hash = jobs . each_with_object ( { } ... | Modifies response . body to have all batched hypernova render results |
6,670 | def jobs_hash hash = { } jobs . each_with_index { | job , idx | hash [ idx . to_s ] = job } hash end | creates a hash with each index mapped to the value at that index |
6,671 | def its ( attribute , * options , & block ) its_caller = caller . select { | file_line | file_line !~ %r( ) } describe ( attribute . to_s , :caller => its_caller ) do let ( :__its_subject ) do if Array === attribute if Hash === subject attribute . inject ( subject ) { | inner , attr | inner [ attr ] } else subject [ * ... | Creates a nested example group named by the submitted attribute and then generates an example using the submitted block . |
6,672 | def refresh json = JSON ( Net :: HTTP . get ( URI . parse ( base_url ) ) ) unpack ( json ) end | Refresh the state of the lamp |
6,673 | def record ( nanos ) return if nanos < 0 @count . add_and_get ( 1 ) @total_time . add_and_get ( nanos ) @total_sq . add_and_get ( nanos * nanos ) @max . max ( nanos ) end | Update the statistics kept by this timer . If the amount of nanoseconds passed is negative the value will be ignored . |
6,674 | def with_tag ( key , value ) new_tags = @tags . dup new_tags [ key ] = value MeterId . new ( @name , new_tags ) end | Create a new MeterId with a given key and value |
6,675 | def key if @key . nil? hash_key = @name . to_s @key = hash_key keys = @tags . keys keys . sort keys . each do | k | v = tags [ k ] hash_key += "|#{k}|#{v}" end @key = hash_key end @key end | lazyily compute a key to be used in hashes for efficiency |
6,676 | def record ( amount ) return if amount < 0 @count . add_and_get ( 1 ) @total_amount . add_and_get ( amount ) @total_sq . add_and_get ( amount * amount ) @max . max ( amount ) end | Initialize a new DistributionSummary instance with a given id Update the statistics kept by the summary with the specified amount . |
6,677 | def measure cnt = Measure . new ( @id . with_stat ( 'count' ) , @count . get_and_set ( 0 ) ) tot = Measure . new ( @id . with_stat ( 'totalAmount' ) , @total_amount . get_and_set ( 0 ) ) tot_sq = Measure . new ( @id . with_stat ( 'totalOfSquares' ) , @total_sq . get_and_set ( 0 ) ) mx = Measure . new ( @id . with_stat ... | Get a list of measurements and reset the stats The stats returned are the current count the total amount the sum of the square of the amounts recorded and the max value |
6,678 | def post_json ( endpoint , payload ) s = payload . to_json uri = URI ( endpoint ) http = Net :: HTTP . new ( uri . host , uri . port ) req = Net :: HTTP :: Post . new ( uri . path , 'Content-Type' => 'application/json' ) req . body = s begin res = http . request ( req ) rescue StandardError => e Spectator . logger . in... | Create a new instance using the given registry to record stats for the requests performed Send a JSON payload to a given endpoing |
6,679 | def stop unless @started Spectator . logger . info ( 'Attemping to stop Spectator ' 'without a previous call to start' ) return end @should_stop = true Spectator . logger . info ( 'Stopping spectator' ) @publish_thread . kill if @publish_thread @started = false Spectator . logger . info ( 'Sending last batch of metrics... | Stop publishing measurements |
6,680 | def op_for_measurement ( measure ) stat = measure . id . tags . fetch ( :statistic , :unknown ) OPS . fetch ( stat , UNKNOWN_OP ) end | Get the operation to be used for the given Measure Gauges are aggregated using MAX_OP counters with ADD_OP |
6,681 | def should_send ( measure ) op = op_for_measurement ( measure ) return measure . value > 0 if op == ADD_OP return ! measure . value . nan? if op == MAX_OP false end | Gauges are sent if they have a value Counters if they have a number of increments greater than 0 |
6,682 | def build_string_table ( measurements ) common_tags = @registry . common_tags table = { } common_tags . each do | k , v | table [ k ] = 0 table [ v ] = 0 end table [ :name ] = 0 measurements . each do | m | table [ m . id . name ] = 0 m . id . tags . each do | k , v | table [ k ] = 0 table [ v ] = 0 end end keys = tabl... | Build a string table from the list of measurements Unique words are identified and assigned a number starting from 0 based on their lexicographical order |
6,683 | def payload_for_measurements ( measurements ) table = build_string_table ( measurements ) payload = [ ] payload . push ( table . length ) strings = table . keys . sort payload . concat ( strings ) measurements . each { | m | append_measurement ( payload , table , m ) } payload end | Generate a payload from the list of measurements The payload is an array with the number of elements in the string table The string table and measurements |
6,684 | def send_metrics_now ms = registry_measurements if ms . empty? Spectator . logger . debug 'No measurements to send' else uri = @registry . config [ :uri ] ms . each_slice ( @registry . batch_size ) do | batch | payload = payload_for_measurements ( batch ) Spectator . logger . info "Sending #{batch.length} measurements ... | Send the current measurements to our aggregator service |
6,685 | def timestamp = ( values ) values . each do | value | case value when String , Symbol , TrueClass @timestamps << value else fail ArgumentError , 'timestamp must be either: true, a String or a Symbol' end end end | Set the timestamp attribute . |
6,686 | def timestamp_attribute_name ( obj , next_state , user_timestamp ) user_timestamp == true ? default_timestamp_name ( obj , next_state ) : user_timestamp end | Returns the name of the timestamp attribute for this event If the timestamp was simply true it returns the default_timestamp_name otherwise returns the user - specified timestamp name |
6,687 | def show prevent_browser_caching cms_edit_links! with_email_locale do if @preview . respond_to? ( :preview_mail ) @mail , body = mail_and_body @mail_body_html = render_to_string ( inline : body , layout : 'rails_email_preview/email' ) else raise ArgumentError . new ( "#{@preview} is not a preview class, does not respon... | Preview an email |
6,688 | def show_headers mail = with_email_locale { mail_and_body . first } render partial : 'rails_email_preview/emails/headers' , locals : { mail : mail } end | Render headers partial . Used by the CMS integration to refetch headers after editing . |
6,689 | def show_body prevent_browser_caching cms_edit_links! with_email_locale do _ , body = mail_and_body render inline : body , layout : 'rails_email_preview/email' end end | Render email body iframe HTML . Used by the CMS integration to provide a link back to Show from Edit . |
6,690 | def incorrect_blobs ( db , table ) return [ ] if ( db . url =~ / \/ \/ / ) . nil? columns = [ ] db . schema ( table ) . each do | data | column , cdata = data columns << column if cdata [ :db_type ] =~ / / end columns end | mysql text and blobs fields are handled the same way internally this is not true for other databases so we must check if the field is actually text and manually convert it back to a string |
6,691 | def server_error_handling ( & blk ) begin blk . call rescue Sequel :: DatabaseError => e if e . message =~ / /i raise Taps :: DuplicatePrimaryKeyError , e . message else raise end end end | try to detect server side errors to give the client a more useful error message |
6,692 | def fetch_rows state [ :chunksize ] = fetch_chunksize ds = table . order ( * order_by ) . limit ( state [ :chunksize ] , state [ :offset ] ) log . debug "DataStream#fetch_rows SQL -> #{ds.sql}" rows = Taps :: Utils . format_data ( ds . all , :string_columns => string_columns , :schema => db . schema ( table_name ) , :t... | keep a record of the average chunksize within the first few hundred thousand records after chunksize goes below 100 or maybe if offset is > 1000 |
6,693 | def fetch_remote_in_server ( params ) json = self . class . parse_json ( params [ :json ] ) encoded_data = params [ :encoded_data ] rows = parse_encoded_data ( encoded_data , json [ :checksum ] ) @complete = rows == { } unless @complete import_rows ( rows ) rows [ :data ] . size else 0 end end | this one is used inside the server process |
6,694 | def stop @bot . loggers . debug "[Stopping handler] Stopping all threads of handler #{self}: #{@thread_group.list.size} threads..." @thread_group . list . each do | thread | Thread . new do @bot . loggers . debug "[Ending thread] Waiting 10 seconds for #{thread} to finish..." thread . join ( 10 ) @bot . loggers . debug... | Stops execution of the handler . This means stopping and killing all associated threads . |
6,695 | def call ( message , captures , arguments ) bargs = captures + arguments thread = Thread . new { @bot . loggers . debug "[New thread] For #{self}: #{Thread.current} -- #{@thread_group.list.size} in total." begin if @execute_in_callback @bot . callback . instance_exec ( message , * @args , * bargs , & @block ) else @blo... | Executes the handler . |
6,696 | def wait_until_synced ( attr ) attr = attr . to_sym waited = 0 while true return if attribute_synced? ( attr ) waited += 1 if waited % 100 == 0 bot . loggers . warn "A synced attribute ('%s' for %s) has not been available for %d seconds, still waiting" % [ attr , self . inspect , waited / 10 ] bot . loggers . warn call... | Blocks until the object is synced . |
6,697 | def load ( new_config , from_default = false ) if from_default @table = self . class . default_config end new_config . each do | option , value | if value . is_a? ( Hash ) if self [ option ] . is_a? ( Configuration ) self [ option ] . load ( value ) else self [ option ] = value end else self [ option ] = value end end ... | Loads a configuration from a hash by merging the hash with either the current configuration or the default configuration . |
6,698 | def find ( nick ) if nick == @bot . nick return @bot end downcased_nick = nick . irc_downcase ( @bot . irc . isupport [ "CASEMAPPING" ] ) @mutex . synchronize do return @cache [ downcased_nick ] end end | Finds a user . |
6,699 | def refresh return if @in_whois @data . keys . each do | attr | unsync attr end @in_whois = true if @bot . irc . network . whois_only_one_argument? @bot . irc . send "WHOIS #@name" else @bot . irc . send "WHOIS #@name #@name" end end | Queries the IRC server for information on the user . This will set the User s state to not synced . After all information are received the object will be set back to synced . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.