idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
6,800
def auto_spin CURSOR_LOCK . synchronize do start sleep_time = 1.0 / @interval spin @thread = Thread . new do sleep ( sleep_time ) while @started_at if Thread . current [ 'pause' ] Thread . stop Thread . current [ 'pause' ] = false end spin sleep ( sleep_time ) end end end ensure if @hide_cursor write ( TTY :: Cursor . ...
Start automatic spinning animation
6,801
def run ( stop_message = '' , & block ) job ( & block ) auto_spin @work = Thread . new { execute_job } @work . join ensure stop ( stop_message ) end
Run spinner while executing job
6,802
def spin synchronize do return if @done emit ( :spin ) if @hide_cursor && ! spinning? write ( TTY :: Cursor . hide ) end data = message . gsub ( MATCHER , @frames [ @current ] ) data = replace_tokens ( data ) write ( data , true ) @current = ( @current + 1 ) % @length @state = :spinning data end end
Perform a spin
6,803
def fetch_format ( token , property ) if FORMATS . key? ( token ) FORMATS [ token ] [ property ] else raise ArgumentError , "Unknown format token `:#{token}`" end end
Find frames by token name
6,804
def auto_format ( value ) case value when TRUE_STRING true when FALSE_STRING false when NUMBER_PATTERN value . include? ( '.' ) ? value . to_f : value . to_i when DATE_PATTERN Date . parse ( value ) rescue value when TIME_PATTERN DateTime . parse ( value ) rescue value else value end end
Detects and casts numbers date time in text
6,805
def time_to_oa_date ( time ) time = time . to_time if time . respond_to? ( :to_time ) ( time + time . utc_offset ) . utc . to_f / 24 / 3600 + 25569 end
Converts Time objects to OLE Automation Date
6,806
def expanded_library_names library_names . map do | libname | pathname = File . expand_path ( File . join ( Libyajl2 . opt_path , libname ) ) pathname if File . file? ( pathname ) end . compact end
Array of yajl library names prepended with the libyajl2 path to use to load those directly and bypass the system libyajl by default . Since these are full paths this API checks to ensure that the file exists on the filesystem . May return an empty array .
6,807
def dlopen_yajl_library found = false ( expanded_library_names + library_names ) . each do | libname | begin dlopen ( libname ) found = true break rescue ArgumentError end end raise "cannot find yajl library for platform" unless found end
Iterate across the expanded library names in the libyajl2 - gem and then attempt to load the system libraries . Uses the native dlopen extension that ships in this gem .
6,808
def ffi_open_yajl_library found = false expanded_library_names . each do | libname | begin ffi_lib libname found = true rescue LoadError end end ffi_lib "yajl" unless found end
Iterate across the expanded library names in the libyajl2 - gem and attempt to load them . If they are missing just use ffi_lib yajl to accept the FFI default algorithm to find the library .
6,809
def graceful_shutdown ( timeout : true ) @stopping = true Thread . new do GrpcKit . logger . debug ( 'graceful shutdown' ) @mutex . synchronize { @sessions . each ( & :drain ) } begin sec = timeout ? @shutdown_timeout : 0 Timeout . timeout ( sec ) do sleep 1 until @sessions . empty? end rescue Timeout :: Error => _ Grp...
This method is expected to be called in trap context
6,810
def updated ( type = nil , children = nil , properties = nil ) new_type = type || @type new_children = children || @children new_properties = properties || { } if @type == new_type && @children == new_children && properties . nil? self else original_dup . send :initialize , new_type , new_children , new_properties end ...
Returns a new instance of Node where non - nil arguments replace the corresponding fields of self .
6,811
def to_sexp ( indent = 0 ) indented = " " * indent sexp = "#{indented}(#{fancy_type}" children . each do | child | if child . is_a? ( Node ) sexp += "\n#{child.to_sexp(indent + 1)}" else sexp += " #{child.inspect}" end end sexp += ")" sexp end
Converts self to a pretty - printed s - expression .
6,812
def to_sexp_array children_sexp_arrs = children . map do | child | if child . is_a? ( Node ) child . to_sexp_array else child end end [ type , * children_sexp_arrs ] end
Converts self to an Array where the first element is the type as a Symbol and subsequent elements are the same representation of its children .
6,813
def payload_parser @payload_parser ||= if @receive_raw_payload -> ( payload ) { payload } else -> ( payload ) { ActiveSupport :: HashWithIndifferentAccess . new ( JSON . parse ( payload ) ) } end end
Returns a proc that when called with the payload parses it according to the configuration .
6,814
def omit_payload_from_log? ( level_of_message_with_payload ) return true if @receive_raw_payload Pwwka :: Logging :: LEVELS [ Pwwka . configuration . payload_logging . to_sym ] > Pwwka :: Logging :: LEVELS [ level_of_message_with_payload . to_sym ] end
True if we should omit the payload from the log
6,815
def localizable_duplicate_entries localizable_files = ( git . modified_files + git . added_files ) - git . deleted_files localizable_files . select! { | line | line . end_with? ( '.strings' ) } duplicate_entries = [ ] localizable_files . each do | file | lines = File . readlines ( file ) keys = lines . map { | e | e . ...
Returns an array of all detected duplicate entries . An entry is represented by a has with file path under file key and the Localizable . strings key under key key .
6,816
def xpath ( * args ) backend . xpath ( * args ) . map { | node | backend . proxy_node . new ( node ) } end
Initialize abstract ProxyFetcher HTML Document
6,817
def css ( * args ) backend . css ( * args ) . map { | node | backend . proxy_node . new ( node ) } end
Searches elements by CSS selector .
6,818
def connectable? ssl_context = OpenSSL :: SSL :: SSLContext . new ssl_context . verify_mode = OpenSSL :: SSL :: VERIFY_NONE @http . head ( URL_TO_CHECK , ssl_context : ssl_context ) . status . success? rescue StandardError false end
Initialize new ProxyValidator instance
6,819
def class_for ( provider_name ) provider_name = provider_name . to_sym providers . fetch ( provider_name ) rescue KeyError raise ProxyFetcher :: Exceptions :: UnknownProvider , provider_name end
Returns a class for specific provider if it is registered in the registry . Otherwise throws an exception .
6,820
def setup_custom_class ( klass , required_methods : [ ] ) unless klass . respond_to? ( * required_methods ) raise ProxyFetcher :: Exceptions :: WrongCustomClass . new ( klass , required_methods ) end klass end
Checks if custom class has some required class methods
6,821
def fetch response = process_http_request response . body . to_s rescue StandardError => error ProxyFetcher . logger . warn ( "Failed to process request to #{url} (#{error.message})" ) '' end
Initialize HTTP client instance
6,822
def refresh_list! ( filters = nil ) @proxies = [ ] threads = [ ] lock = Mutex . new ProxyFetcher . config . providers . each do | provider_name | threads << Thread . new do provider = ProxyFetcher :: Configuration . providers_registry . class_for ( provider_name ) provider_filters = filters && filters . fetch ( provide...
Initialize ProxyFetcher Manager instance for managing proxies
6,823
def delete_all ( conditions = nil ) check_for_limit_scope! collection = conditions . nil? ? to_a . each ( & :delete ) . clear : where ( conditions ) collection . map ( & :delete ) . count end
Deletes the records matching + conditions + by instantiating each record and calling its + delete + method .
6,824
def find_by ( conditions = { } ) to_a . detect do | record | Find . new ( record ) . is_of ( conditions ) end end
Finds the first record matching the specified conditions . There is no implied ordering so if order matters you should specify it yourself .
6,825
def limit ( num ) relation = __new_relation__ ( all . take ( num ) ) relation . send ( :set_from_limit ) relation end
Specifies a limit for the number of records to retrieve .
6,826
def sum ( key ) values = values_by_key ( key ) values . inject ( 0 ) do | sum , n | sum + ( n || 0 ) end end
Calculates the sum of values on a given column . The value is returned with the same data type of the column 0 if there s no row .
6,827
def average ( key ) values = values_by_key ( key ) total = values . inject { | sum , n | sum + n } BigDecimal . new ( total ) / BigDecimal . new ( values . count ) end
Calculates the average value on a given column . Returns + nil + if there s no row .
6,828
def slice ( * methods ) Hash [ methods . map! { | method | [ method , public_send ( method ) ] } ] . with_indifferent_access end
Returns a hash of the given methods with their names as keys and returned values as values .
6,829
def warning_error_count ( file_path ) if File . file? ( file_path ) xcode_summary = JSON . parse ( File . read ( file_path ) , symbolize_names : true ) warning_count = warnings ( xcode_summary ) . count error_count = errors ( xcode_summary ) . count result = { warnings : warning_count , errors : error_count } result . ...
Reads a file with JSON Xcode summary and reports its warning and error count .
6,830
def result strings = @groups . map { | repeater | repeater . public_send ( __callee__ ) } RegexpExamples . permutations_of_strings ( strings ) . map do | result | GroupResult . new ( result , group_id ) end end
Generates the result of each contained group and adds the filled group of each result to itself
6,831
def button ( * args , & block ) button = Bh :: Button . new ( self , * args , & block ) button . extract! :context , :size , :layout button . append_class! :btn button . append_class! button . context_class button . append_class! button . size_class button . append_class! button . layout_class button . render_tag :butt...
Displays a Bootstrap - styled button .
6,832
def panel_row ( options = { } , & block ) panel_row = Bh :: PanelRow . new self , options , & block panel_row . extract! :column_class panel_row . append_class! :row panel_row . render_tag :div end
Wraps a set of Bootstrap - styled panels in a row .
6,833
def panel ( * args , & block ) panel = Bh :: Panel . new self , * args , & block panel . extract! :body , :context , :title , :heading , :tag panel . append_class! :panel panel . append_class! panel . context_class panel . merge_html! panel . body panel . prepend_html! panel . heading if panel_row = Bh :: Stack . find ...
Displays a Bootstrap - styled panel .
6,834
def modal ( * args , & block ) modal = Bh :: Modal . new self , * args , & block modal . extract! :button , :size , :body , :title , :id modal . extract_from :button , [ :context , :size , :layout , :caption ] modal . append_class_to! :button , :btn modal . append_class_to! :button , modal . button_context_class modal ...
Displays a Bootstrap - styled modal .
6,835
def nav ( options = { } , & block ) nav = Bh :: Nav . new ( self , options , & block ) nav . extract! :as , :layout nav . append_class! :nav if Bh :: Stack . find ( Bh :: Navbar ) nav . append_class! :' ' else nav . merge! role : :tablist nav . append_class! nav . style_class nav . append_class! nav . layout_class end ...
Displays a Bootstrap - styled nav .
6,836
def horizontal ( * args , & block ) if navbar = Bh :: Stack . find ( Bh :: Navbar ) horizontal = Bh :: Base . new self , * args , & block horizontal . append_class! :' ' horizontal . merge! id : navbar . id horizontal . render_tag :div end end
Displays the collapsable portion of a Bootstrap - styled navbar .
6,837
def icon ( name = nil , options = { } ) icon = Bh :: Icon . new self , nil , options . merge ( name : name ) icon . extract! :library , :name icon . append_class! icon . library_class icon . append_class! icon . name_class icon . render_tag :span end
Displays a Bootstrap - styled vector icon .
6,838
def vertical ( * args , & block ) if navbar = Bh :: Stack . find ( Bh :: Navbar ) vertical = Bh :: Vertical . new self , * args , & block vertical . append_class! :' ' vertical . prepend_html! vertical . toggle_button ( navbar . id ) vertical . render_tag :div end end
Displays the non - collapsable portion of a Bootstrap - styled navbar .
6,839
def progress_bar ( args = nil , container_options = { } ) progress_bars = Array . wrap ( args ) . map do | options | progress_bar = Bh :: ProgressBar . new self , nil , options progress_bar . extract! :percentage , :context , :striped , :animated , :label progress_bar . merge! progress_bar . aria_values progress_bar . ...
Displays one or more Bootstrap - styled progress bars .
6,840
def navbar ( options = { } , & block ) navbar = Bh :: Navbar . new ( self , options , & block ) navbar . extract! :inverted , :position , :padding , :fluid , :id navbar . append_class_to! :navigation , :navbar navbar . append_class_to! :navigation , navbar . style_class navbar . append_class_to! :navigation , navbar . ...
Displays a Bootstrap - styled navbar .
6,841
def link_to ( * args , & block ) link_to = Bh :: LinkTo . new self , * args , & block link_to . append_class! :' ' if Bh :: Stack . find ( Bh :: AlertBox ) link_to . append_class! :' ' if Bh :: Stack . find ( Bh :: Vertical ) link_to . merge! role : :menuitem if Bh :: Stack . find ( Bh :: Dropdown ) link_to . merge! ta...
Overrides link_to to display a Bootstrap - styled link . Can only be used in Ruby frameworks that provide the link_to method .
6,842
def alert_box ( * args , & block ) alert_box = Bh :: AlertBox . new ( self , * args , & block ) alert_box . extract! :context , :priority , :dismissible alert_box . append_class! :alert alert_box . append_class! alert_box . context_class alert_box . merge! role : :alert alert_box . prepend_html! alert_box . dismissible...
Displays a Bootstrap - styled alert message .
6,843
def otherwise ( first , second ) first = first . to_s first . empty? ? second : first end
Returns the first argument if it s not nil or empty otherwise it returns the second one .
6,844
def audio ( hsh , key = nil ) if ! hsh . nil? && hsh . length if key . nil? hsh [ 'mp3' ] ? hsh [ 'mp3' ] : hsh [ 'm4a' ] ? hsh [ 'm4a' ] : hsh [ 'ogg' ] ? hsh [ 'ogg' ] : hsh [ 'opus' ] ? hsh [ 'opus' ] : hsh . values . first else hsh [ key ] end end end
Returns the audio file name of a given hash . Is no key as second parameter given it trys first mp3 than m4a and than it will return a more or less random value .
6,845
def audio_type ( hsh ) if ! hsh . nil? && hsh . length hsh [ 'mp3' ] ? mime_type ( 'mp3' ) : hsh [ 'm4a' ] ? mime_type ( 'm4a' ) : hsh [ 'ogg' ] ? mime_type ( 'ogg' ) : mime_type ( 'opus' ) end end
Returns the audio - type of a given hash . Is no key as second parameter given it trys first mp3 than m4a and than it will return a more or less random value .
6,846
def split_chapter ( chapter_str , attribute = nil ) attributes = chapter_str . split ( / / , 2 ) return nil unless attributes . first . match ( / \A \d \. \z / ) if attribute . nil? { 'start' => attributes . first , 'title' => attributes . last } else attribute == 'start' ? attributes . first : attributes . last end en...
Splits a chapter like it is written to the post YAML front matter into the components start which refers to a single point in time relative to the beginning of the media file nad title which defines the text to be the title of the chapter .
6,847
def string_of_size ( bytes ) bytes = bytes . to_i . to_f out = '0' return out if bytes == 0.0 jedec = %w[ b K M G ] [ 3 , 2 , 1 , 0 ] . each { | i | if bytes > 1024 ** i out = "%.1f#{jedec[i]}" % ( bytes / 1024 ** i ) break end } return out end
Gets a number of bytes and returns an human readable string of it .
6,848
def disqus_config ( site , page = nil ) if page disqus_vars = { 'disqus_identifier' => page [ 'url' ] , 'disqus_url' => "#{site['url']}#{page['url']}" , 'disqus_category_id' => page [ 'disqus_category_id' ] || site [ 'disqus_category_id' ] , 'disqus_title' => j ( page [ 'title' ] || site [ 'site' ] ) } else disqus_vars...
Generates the config for disqus integration If a page object is given it generates the config variables only for this page . Otherwise it generate only the global config variables .
6,849
def sha1 ( str , lenght = 8 ) sha1 = Digest :: SHA1 . hexdigest ( str ) sha1 [ 0 , lenght . to_i ] end
Returns the hex - encoded hash value of a given string . The optional second argument defines the length of the returned string .
6,850
def format_date ( date , format ) date = datetime ( date ) if format . nil? || format . empty? || format == "ordinal" date_formatted = ordinalize ( date ) else format . gsub! ( / / , ABBR_DAYNAMES_DE [ date . wday ] ) format . gsub! ( / / , DAYNAMES_DE [ date . wday ] ) format . gsub! ( / / , ABBR_MONTHNAMES_DE [ date ...
Formats date by given date format
6,851
def flattr_loader_options ( site ) return if site [ 'flattr_uid' ] . nil? keys = %w[ mode https popout uid button language category ] options = flattr_options ( site , nil , keys ) . delete_if { | _ , v | v . to_s . empty? } options . map { | k , v | "#{k}=#{ERB::Util.url_encode(v)}" } . join ( '&' ) end
Generates the query string part for the flattr load . js from the configurations in _config . yml
6,852
def flattr_button ( site , page = nil ) return if site [ 'flattr_uid' ] . nil? keys = %w[ url title description uid popout button category language tags ] options = flattr_options ( site , page , keys ) button = '<a class="FlattrButton" style="display:none;" ' button << %Q{title="#{options.delete('title')}" href="#{opt...
Returns a flattr button
6,853
def flattrize ( hsh ) config = { } hsh . to_hash . each { | k , v | if new_key = k . to_s . match ( / \A \z / ) config [ new_key [ 1 ] ] = v else config [ k ] = v end } config end
Removes all leading flattr_ from the keys of the given hash .
6,854
def load ( name , options = { } ) env_var = options . fetch ( :env_var , name . to_s . upcase ) type = options . fetch ( :type , :string ) required = options . fetch ( :required , true ) @registry [ name ] = case type when :string then load_string ( env_var , required ) when :int then load_int ( env_var , required ) wh...
Initialise a Registry .
6,855
def run start_time = Time . new . to_f Signal . trap ( 'TERM' ) do log . info ( 'SIGTERM received. shutting down gracefully...' ) @request_shutdown = true end run_desc = @dry_run ? 'dry run' : 'run' log . info ( "beginning alerts #{run_desc}" ) alerts = read_alerts ( @alert_sources ) groups = read_groups ( @group_sourc...
groups_sources is a hash from type = > options for each group source host_sources is a hash from type = > options for each host source destinations is a similar hash from type = > options for each alerter
6,856
def account_number return @account_number if @account_number begin my_arn = AWS :: IAM . new ( access_key_id : @access_key_id , secret_access_key : @secret_access_key ) . client . get_user [ :user ] [ :arn ] rescue AWS :: IAM :: Errors :: AccessDenied => e my_arn = e . message . split [ 1 ] end @account_number = my_arn...
unfortunately this appears to be the only way to get your account number
6,857
def call ( * tms ) unless @arguments . empty? tms . empty? or raise ( ArgumentError , 'Op arguments is already set, use call()' ) tms = @arguments end res = [ * tms ] . flatten . map ( & method ( :perform ) ) tms . count == 1 && Util . timey? ( tms . first ) ? res . first : res end
Performs op . If an Op was created with arguments just performs all operations on them and returns the result . If it was created without arguments performs all operations on arguments provided to call .
6,858
def indices ( * names ) names = Array ( names ) . flatten names . compact . empty? ? @attributes [ :indices ] : ( names . each { | n | @attributes [ :indices ] . push ( n ) } and return self ) end
Get or set the alias indices
6,859
def filter ( type = nil , * options ) type ? ( @attributes [ :filter ] = Search :: Filter . new ( type , * options ) . to_hash and return self ) : @attributes [ :filter ] end
Get or set the alias routing
6,860
def as_json ( options = nil ) actions = [ ] indices . add_indices . each do | index | operation = { :index => index , :alias => name } operation . update ( { :routing => routing } ) if respond_to? ( :routing ) and routing operation . update ( { :filter => filter } ) if respond_to? ( :filter ) and filter actions . push ...
Return a Hash suitable for JSON serialization
6,861
def mapping! ( * args ) mapping ( * args ) raise RuntimeError , response . body unless response . success? end
Raises an exception for unsuccessful responses
6,862
def listing_row_to_object ( row ) l = Listing . new row . css ( 'td' ) . each_with_index do | td , i | txt = td . text . strip case i when 4 l . sku = txt when 5 l . asin = txt when 6 l . product_name = txt when 7 l . created_at = parse_amazon_time ( txt ) when 8 l . quantity = ( inputs = td . css ( 'input' ) ) . any? ...
0 - hidden input of sku 1 - checkbox itemOffer 2 - actions 3 - status 4 - sku 5 - asin 6 - product name 7 - date created 8 - qty 9 - your price 10 - condition 11 - low price 12 - buy - box price 13 - fulfilled by
6,863
def theme = ( options ) reset_themes defaults = { :colors => %w( black white ) , :additional_line_colors => [ ] , :marker_color => 'white' , :marker_shadow_color => nil , :font_color => 'black' , :background_colors => nil , :background_image => nil } @theme_options = defaults . merge options @colors = @theme_options [ ...
You can set a theme manually . Assign a hash to this method before you send your data .
6,864
def data ( name , data_points = [ ] , color = nil ) data_points = Array ( data_points ) @data << [ name , data_points , color ] @column_count = ( data_points . length > @column_count ) ? data_points . length : @column_count data_points . each do | data_point | next if data_point . nil? if @maximum_value . nil? && @mini...
Parameters are an array where the first element is the name of the dataset and the value is an array of values to plot .
6,865
def draw unless @has_data draw_no_data return end setup_data setup_drawing debug { @d . rectangle ( @left_margin , @top_margin , @raw_columns - @right_margin , @raw_rows - @bottom_margin ) @d . rectangle ( @graph_left , @graph_top , @graph_right , @graph_bottom ) } draw_legend draw_line_markers draw_axis_labels draw_ti...
Overridden by subclasses to do the actual plotting of the graph .
6,866
def normalize ( force = false ) if @norm_data . nil? || force @norm_data = [ ] return unless @has_data @data . each do | data_row | norm_data_points = [ ] data_row [ DATA_VALUES_INDEX ] . each do | data_point | if data_point . nil? norm_data_points << nil else norm_data_points << ( ( data_point . to_f - @minimum_value ...
Make copy of data with values scaled between 0 - 100
6,867
def setup_graph_measurements @marker_caps_height = @hide_line_markers ? 0 : calculate_caps_height ( @marker_font_size ) @title_caps_height = ( @hide_title || @title . nil? ) ? 0 : calculate_caps_height ( @title_font_size ) * @title . lines . to_a . size @legend_caps_height = @hide_legend ? 0 : calculate_caps_height ( @...
Calculates size of drawable area general font dimensions etc .
6,868
def draw_axis_labels unless @x_axis_label . nil? x_axis_label_y_coordinate = @graph_bottom + LABEL_MARGIN * 2 + @marker_caps_height @d . fill = @font_color @d . font = @font if @font @d . stroke ( 'transparent' ) @d . pointsize = scale_fontsize ( @marker_font_size ) @d . gravity = NorthGravity @d = @d . annotate_scaled...
Draw the optional labels for the x axis and y axis .
6,869
def draw_line_markers return if @hide_line_markers @d = @d . stroke_antialias false if @y_axis_increment . nil? if @marker_count . nil? ( 3 .. 7 ) . each do | lines | if @spread % lines == 0.0 @marker_count = lines break end end @marker_count ||= 4 end @increment = ( @spread > 0 && @marker_count > 0 ) ? significant ( @...
Draws horizontal background lines and labels
6,870
def draw_legend return if @hide_legend @legend_labels = @data . collect { | item | item [ DATA_LABEL_INDEX ] } legend_square_width = @legend_box_size @d . font = @font if @font @d . pointsize = @legend_font_size label_widths = [ [ ] ] @legend_labels . each do | label | metrics = @d . get_type_metrics ( @base_image , la...
Draws a legend with the names of the datasets matched to the colors used to draw them .
6,871
def draw_title return if ( @hide_title || @title . nil? ) @d . fill = @font_color @d . font = @title_font || @font if @title_font || @font @d . stroke ( 'transparent' ) @d . pointsize = scale_fontsize ( @title_font_size ) @d . font_weight = if @bold_title then BoldWeight else NormalWeight end @d . gravity = NorthGravit...
Draws a title on the graph .
6,872
def draw_value_label ( x_offset , y_offset , data_point , bar_value = false ) return if @hide_line_markers && ! bar_value @d . fill = @font_color @d . font = @font if @font @d . stroke ( 'transparent' ) @d . font_weight = NormalWeight @d . pointsize = scale_fontsize ( @marker_font_size ) @d . gravity = NorthGravity @d ...
Draws the data value over the data point in bar graphs
6,873
def draw_no_data @d . fill = @font_color @d . font = @font if @font @d . stroke ( 'transparent' ) @d . font_weight = NormalWeight @d . pointsize = scale_fontsize ( 80 ) @d . gravity = CenterGravity @d = @d . annotate_scaled ( @base_image , @raw_columns , @raw_rows / 2.0 , 0 , 10 , @no_data_message , @scale ) end
Shows an error message because you have no data .
6,874
def render_gradiated_background ( top_color , bottom_color , direct = :top_bottom ) case direct when :bottom_top gradient_fill = GradientFill . new ( 0 , 0 , 100 , 0 , bottom_color , top_color ) when :left_right gradient_fill = GradientFill . new ( 0 , 0 , 0 , 100 , top_color , bottom_color ) when :right_left gradient_...
Use with a theme definition method to draw a gradiated background .
6,875
def sort_data @data = @data . sort_by { | a | - a [ DATA_VALUES_INDEX ] . inject ( 0 ) { | sum , num | sum + num . to_f } } end
Sort with largest overall summed value at front of array .
6,876
def sort_norm_data @norm_data = @norm_data . sort_by { | a | - a [ DATA_VALUES_INDEX ] . inject ( 0 ) { | sum , num | sum + num . to_f } } end
Sort with largest overall summed value at front of array so it shows up correctly in the drawn graph .
6,877
def get_maximum_by_stack max_hash = { } @data . each do | data_set | data_set [ DATA_VALUES_INDEX ] . each_with_index do | data_point , i | max_hash [ i ] = 0.0 unless max_hash [ i ] max_hash [ i ] += data_point . to_f end end max_hash . keys . each do | key | @maximum_value = max_hash [ key ] if max_hash [ key ] > @ma...
Used by StackedBar and child classes .
6,878
def label ( value , increment ) label = if increment if increment >= 10 || ( increment * 1 ) == ( increment * 1 ) . to_i . to_f sprintf ( '%0i' , value ) elsif increment >= 1.0 || ( increment * 10 ) == ( increment * 10 ) . to_i . to_f sprintf ( '%0.1f' , value ) elsif increment >= 0.1 || ( increment * 100 ) == ( increm...
Return a formatted string representing a number value that should be printed as a label .
6,879
def calculate_width ( font_size , text ) return 0 if text . nil? @d . pointsize = font_size @d . font = @font if @font @d . get_type_metrics ( @base_image , text . to_s ) . width end
Returns the width of a string at this pointsize .
6,880
def annotate_scaled ( img , width , height , x , y , text , scale ) scaled_width = ( width * scale ) >= 1 ? ( width * scale ) : 1 scaled_height = ( height * scale ) >= 1 ? ( height * scale ) : 1 self . annotate ( img , scaled_width , scaled_height , x * scale , y * scale , text . gsub ( '%' , '%%' ) ) end
Additional method to scale annotation text since Draw . scale doesn t .
6,881
def limits ( action ) @limits ||= { } limits = @limits [ action . to_sym ] raise TrafficJam :: LimitNotFound . new ( action ) if limits . nil? limits end
Get registered limit parameters for an action .
6,882
def increment ( amount = 1 , time : Time . now ) exceeded_index = limits . find_index do | limit | ! limit . increment ( amount , time : time ) end if exceeded_index limits [ 0 ... exceeded_index ] . each do | limit | limit . decrement ( amount , time : time ) end end exceeded_index . nil? end
Attempt to increment the limits by the given amount . Does not increment if incrementing would exceed any limit .
6,883
def increment! ( amount = 1 , time : Time . now ) exception = nil exceeded_index = limits . find_index do | limit | begin limit . increment! ( amount , time : time ) rescue TrafficJam :: LimitExceededError => e exception = e true end end if exceeded_index limits [ 0 ... exceeded_index ] . each do | limit | limit . decr...
Increment the limits by the given amount . Raises an error and does not increment if doing so would exceed any limit .
6,884
def decrement ( amount = 1 , time : Time . now ) limits . all? { | limit | limit . decrement ( amount , time : time ) } end
Decrement the limits by the given amount .
6,885
def limit_exceeded ( amount = 1 ) limits . each do | limit | limit_exceeded = limit . limit_exceeded ( amount ) return limit_exceeded if limit_exceeded end nil end
Return the first limit to be exceeded if incrementing by the given amount or nil otherwise . Does not change amount used for any limit .
6,886
def increment ( amount = 1 , time : Time . now ) return true if amount == 0 return false if max == 0 raise ArgumentError . new ( "Amount must be positive" ) if amount < 0 if amount != amount . to_i raise ArgumentError . new ( "Amount must be an integer" ) end return false if amount > max incrby = ( period * 1000 * amou...
Increment the amount used by the given number . Does not perform increment if the operation would exceed the limit . Returns whether the operation was successful .
6,887
def increment ( amount = 1 , time : Time . now ) return amount <= 0 if max . zero? if amount != amount . to_i raise ArgumentError . new ( "Amount must be an integer" ) end timestamp = ( time . to_f * 1000 ) . to_i argv = [ timestamp , amount . to_i , max , period * 1000 ] result = begin redis . evalsha ( Scripts :: INC...
Increment the amount used by the given number . Does not perform increment if the operation would exceed the limit . Returns whether the operation was successful . Time of increment can be specified optionally with a keyword argument which is useful for rolling back with a decrement .
6,888
def used return 0 if max . zero? amount = redis . get ( key ) || 0 [ amount . to_i , max ] . min end
Return amount of limit used
6,889
def dispatch ( channel , message ) @worker_pool . post do begin dispatch_in_thread ( channel , message ) rescue => e err = "Worker Thread Exception for #{message}\n" err += e . inspect err += e . backtrace . join ( "\n" ) if e . respond_to? ( :backtrace ) Volt . logger . error ( err ) end end end
Dispatch takes an incoming Task from the client and runs it on the server returning the result to the client . Tasks returning a promise will wait to return .
6,890
def safe_method? ( klass , method_name ) return false unless klass . ancestors . include? ( Task ) klass . ancestors . each do | ancestor_klass | if ancestor_klass . instance_methods ( false ) . include? ( method_name ) return true elsif ancestor_klass == Task return false end end false end
Check if it is safe to use this method
6,891
def dispatch_in_thread ( channel , message ) callback_id , class_name , method_name , meta_data , * args = message method_name = method_name . to_sym klass = Object . send ( :const_get , class_name ) promise = Promise . new cookies = nil start_time = Time . now . to_f if safe_method? ( klass , method_name ) promise . r...
Do the actual dispatching should be running inside of a worker thread at this point .
6,892
def validate ( field_name = nil , options = nil , & block ) if block if field_name || options fail 'validate should be passed a field name and options or a block, not both.' end @instance_custom_validations << block else @instance_validations [ field_name ] ||= { } @instance_validations [ field_name ] . merge! ( option...
Called on the model inside of a validations block . Allows the user to control if validations should be run .
6,893
def mark_all_fields! fields_to_mark = [ ] validations = self . class . validations_to_run if validations fields_to_mark += validations . keys end fields_to_mark += attributes . keys fields_to_mark . each do | key | mark_field! ( key . to_sym ) end end
Marks all fields useful for when a model saves .
6,894
def error_in_changed_attributes? errs = errors changed_attributes . each_pair do | key , _ | return true if errs [ key ] end false end
Returns true if any of the changed fields now has an error
6,895
def run_validations ( validations = nil ) validations ||= self . class . validations_to_run promise = Promise . new . resolve ( nil ) if validations validations . each_pair do | field_name , options | promise = promise . then { run_validation ( field_name , options ) } end end promise end
Runs through each of the normal validations .
6,896
def run_validation ( field_name , options ) promise = Promise . new . resolve ( nil ) options . each_pair do | validation , args | klass = validation_class ( validation , args ) if klass promise = promise . then do klass . validate ( self , field_name , args ) end . then do | errs | errors . merge! ( errs ) end else fa...
Runs an individual validation
6,897
def __clear old_size = @array . size deps = @array_deps @array_deps = [ ] old_size . times do | index | trigger_removed! ( old_size - index - 1 ) end if deps deps . each do | dep | dep . changed! if dep end end @array = [ ] end
used internally clears out the array triggers the change events but does not call clear on the persistors . Used when models are updated externally .
6,898
def promise_for_errors ( errors ) mark_all_fields! errors = errors . is_a? ( Errors ) ? errors : Errors . new ( errors ) Promise . new . reject ( errors ) end
When errors come in we mark all fields and return a rejected promise .
6,899
def buffer model_path = options [ :path ] model_klass = self . class new_options = options . merge ( path : model_path , save_to : self , buffer : true ) . reject { | k , _ | k . to_sym == :persistor } model = nil Volt :: Model . no_validate do model = model_klass . new ( attributes , new_options , :loaded ) model . in...
Returns a buffered version of the model