idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
12,800
def procfs_file ( * names , & block ) path = File . join ( procfs_path , * names ) File . open ( path , "r" , & block ) end
Opens a proc file system file handle and returns the handle in the passed block . Closes the file handle .
12,801
def + ( other ) SearchAtom . new ( @records . clone . merge! ( other . records ) { | key , _old , _new | _old + _new } ) end
Creates a new SearchAtom with the combined records from self and other
12,802
def - ( other ) records = @records . clone . reject { | name , records | other . records . include? ( name ) } SearchAtom . new ( records ) end
Creates a new SearchAtom with records in other removed from self .
12,803
def preceded_by ( former ) matches = SearchAtom . new latter = ActiveSupport :: OrderedHash . new former . record_ids . each do | rid | latter [ rid ] = @records [ rid ] if @records [ rid ] end latter . each do | record_id , pos | pos . each do | p | if former . include_position? ( record_id , p - 1 ) matches . add_rec...
Returns at atom containing the records and positions of + self + preceded by + former + former latter or big dog where big is the former and dog is the latter .
12,804
def weightings ( records_size ) out = ActiveSupport :: OrderedHash . new matching_records_size = ( records_size == @records . size ? @records . size - 1 : @records . size ) @records . each do | r_id , pos | if records_size < 1 out [ r_id ] = 0.0 next end out [ r_id ] = pos . size * Math . log ( records_size . to_f / ma...
Returns a hash of record_ids and weightings for each record in the atom .
12,805
def elicit_slot! ( slot_to_elicit , skip_render : false ) directives << { type : "Dialog.ElicitSlot" , slotToElicit : slot_to_elicit } if skip_render @slots_to_not_render_elicitation << slot_to_elicit end end
Marks a slot for elicitation .
12,806
def fetch ( atom_names , start = false ) atoms = ActiveSupport :: OrderedHash . new atom_names . uniq . collect { | a | encoded_prefix ( a ) } . uniq . each do | prefix | pattern = @path . join ( prefix . to_s ) . to_s pattern += '*' if start pattern += INDEX_FILE_EXTENSION Pathname . glob ( pattern ) . each do | atom_...
Takes a string array of atoms names return a hash of the relevant atoms .
12,807
def operate ( operation , atoms ) atoms_sorted = ActiveSupport :: OrderedHash . new atoms . each do | atom_name , records | ( atoms_sorted [ encoded_prefix ( atom_name ) ] ||= ActiveSupport :: OrderedHash . new ) [ atom_name ] = records end atoms_sorted . each do | e_p , atoms | path = @path . join ( e_p . to_s + INDEX...
Takes atoms and adds or removes them from the index depending on the passed operation .
12,808
def lock_file ( file_path , & block ) @@file_lock . synchronize do if ! windows? && file_path . exist? file_path . open ( 'r+' ) do | f | begin f . flock File :: LOCK_EX yield ensure f . flock File :: LOCK_UN end end else yield end end end
Borrowed from Rails ActiveSupport FileStore . Also under MIT licence . Lock a file for a block so only one process or thread can modify it at a time .
12,809
def location @_location ||= begin if Alexa . configuration . location_permission_type == :full_address get_address elsif Alexa . configuration . location_permission_type == :country_and_postal_code get_address ( only : :country_and_postal_code ) end end end
Return device location from amazon . Makes an API to amazon alexa s device location service and returns the location hash
12,810
def get_sq_seg_dist ( point , point_1 , point_2 ) x = point_1 . x y = point_1 . y dx = point_2 . x - x dy = point_2 . y - y if dx != 0 || dy != 0 t = ( ( point . x - x ) * dx + ( point . y - y ) * dy ) / ( dx * dx + dy * dy ) if t > 1 x = point_2 . x y = point_2 . y elsif t > 0 x += dx * t y += dy * t end end dx = poin...
Square distance from a point to a segment
12,811
def acts_as_indexed ( options = { } ) class_eval do extend ActsAsIndexed :: SingletonMethods end include ActsAsIndexed :: InstanceMethods after_create :add_to_index before_update :update_index after_destroy :remove_from_index if self . respond_to? ( :where ) scope :with_query , lambda { | query | where ( "#{table_name}...
Declares a class as searchable .
12,812
def index_add ( record ) return if self . aai_config . disable_auto_indexing build_index index = new_index index . add_record ( record ) @query_cache = { } end
Adds the passed + record + to the index . Index is built if it does not already exist . Clears the query cache .
12,813
def index_update ( record ) return if self . aai_config . disable_auto_indexing build_index index = new_index index . update_record ( record , find ( record . id ) ) @query_cache = { } end
Updates the index . 1 . Removes the previous version of the record from the index 2 . Adds the new version to the index .
12,814
def search_index ( query , find_options = { } , options = { } ) @query_cache = { } if options [ :no_query_cache ] if ! @query_cache || ! @query_cache [ query ] build_index ( @query_cache ||= { } ) [ query ] = new_index . search ( query ) end if options [ :ids_only ] find_option_keys = find_options . keys . map { | k | ...
Finds instances matching the terms passed in + query + . Terms are ANDed by default . Returns an array of model instances or if + ids_only + is true an array of integer IDs .
12,815
def build_index return if aai_config . index_file . directory? index = new_index find_in_batches ( { :batch_size => 500 } ) do | records | index . add_records ( records ) end end
Builds an index from scratch for the current model class . Does not run if the index already exists .
12,816
def sort ( ranked_records ) ranked_records . sort { | a , b | a_score = a . last a_id = a . first . is_a? ( Fixnum ) ? a . first : a . first . id b_score = b . last b_id = b . first . is_a? ( Fixnum ) ? b . first : b . first . id if a_score == b_score a_id <=> b_id else b_score <=> a_score end } end
If two records or record IDs have the same rank sort them by ID . This prevents a different order being returned by different Rubies .
12,817
def mongo_fix_session_keys ( session = { } ) new_session = Hash . new session . to_hash . each do | i , j | new_session [ i . gsub ( / \. /i , "|" ) ] = j . inspect end unless session . empty? new_session end
session keys can be with dots . It is invalid keys for BSON
12,818
def find_templates ( name , prefix , partial , details , key = nil , locals = [ ] ) return [ ] if @@resolver_options [ :only ] && ! @@resolver_options [ :only ] . include? ( prefix ) path = build_path ( name , prefix ) conditions = { :path => path , :locale => [ normalize_array ( details [ :locale ] ) . first , nil ] ,...
this method is mandatory to implement a Resolver
12,819
def virtual_path ( path , partial ) return path unless partial if index = path . rindex ( "/" ) path . insert ( index + 1 , "_" ) else "_#{path}" end end
returns a path depending if its a partial or template
12,820
def send_message ( message ) body = message . is_a? ( String ) ? options . merge ( text : message ) : options . merge ( message . as_json ) conn = Faraday . new ( url : @base_uri ) response = conn . post ( '' , payload : body . to_json ) response end
Initializes a Poster instance to post messages with an incoming webhook URL . It also accepts an options hash . If no options are given then the poster uses the default configuration from Slack integration .
12,821
def record_serializer ( rec , nice = true ) [ :messages , :params ] . each do | key | if msgs = rec [ key ] msgs . each do | i , j | msgs [ i ] = ( true == nice ? nice_serialize_object ( j ) : j . inspect ) end end end end
try to serialyze data by each key and found invalid object
12,822
def rescue_connection_failure ( max_retries = 40 ) success = false retries = 0 while ! success begin yield success = true rescue mongo_error_type => e raise e if ( retries += 1 ) >= max_retries sleep 0.25 end end end
Use retry alg from mongodb to gobble up connection failures during replica set master vote Defaults to a 10 second wait
12,823
def error_value if poi_cell . cell_type == CELL_TYPE_ERROR error_value_from ( poi_cell . error_cell_value ) elsif poi_cell . cell_type == CELL_TYPE_FORMULA && poi_cell . cached_formula_result_type == CELL_TYPE_ERROR cell_value = formula_evaluator . evaluate ( poi_cell ) cell_value && error_value_from ( cell_value . err...
This is NOT an inexpensive operation . The purpose of this method is merely to get more information out of cell when one thinks the value returned is incorrect . It may have more value in development than in production .
12,824
def to_s ( evaluate_formulas = true ) return '' if poi_cell . nil? if poi_cell . cell_type == CELL_TYPE_FORMULA && evaluate_formulas == false formula_value else value . to_s end end
Get the String representation of this Cell s value .
12,825
def add_mouse_event_listener Element . find ( "##{@canvas.id}" ) . on :mousemove do | event | coords = get_cursor_position ( event ) @mouse_x = coords . x [ :x ] @mouse_y = coords . x [ :y ] end end
adds mousemove event listener to main canvas
12,826
def add_keyboard_event_listeners Element . find ( "html" ) . on :keydown do | event | @keys [ get_key_id ( event ) ] = true end Element . find ( "html" ) . on :keyup do | event | @keys [ get_key_id ( event ) ] = false end :: Window . on :blur do | event | @keys . fill false end end
adds keyboard event listeners to entire page
12,827
def [] ( row_index ) if Fixnum === row_index rows [ row_index ] else ref = org . apache . poi . ss . util . CellReference . new ( row_index ) cell = rows [ ref . row ] [ ref . col ] cell && cell . value ? cell . value : cell end end
Accepts a Fixnum or a String as the row_index
12,828
def section ( name , opts = { } ) if @in_section raise LineNotAllowed , "You can't nest sections in INI files." end if @document . has_section? ( name . to_s ( ) ) @context = @document [ name . to_s ( ) ] else @context = Lines :: Section . new ( name , line_options ( opts ) ) @document . lines << @context end if block_...
Creates a new section with the given name and adds it to the document .
12,829
def option ( key , value , opts = { } ) @context . lines << Lines :: Option . new ( key , value , line_options ( opts ) ) rescue LineNotAllowed raise NoSectionError , 'Your INI document contains an option before the first section is ' 'declared which is not allowed.' end
Adds a new option to the current section .
12,830
def comment ( comment , opts = { } ) @context . lines << Lines :: Comment . new ( line_options ( opts . merge ( :comment => comment ) ) ) end
Adds a new comment line to the document .
12,831
def with_options ( opts = { } ) opts = opts . dup opts . delete ( :comment ) @opt_stack . push ( @opt_stack . last . merge ( opts ) ) yield self @opt_stack . pop end
Wraps lines setting default options for each .
12,832
def videos_for ( items , key , options ) items . body [ 'items' ] . map { | item | item [ 'id' ] = item [ key ] [ 'videoId' ] } if options [ :parts ] == %i( id ) items else options [ :ids ] = items . body [ 'items' ] . map { | item | item [ 'id' ] } options [ :offset ] = nil get ( '/youtube/v3/videos' , resource_params...
Expands the resultset into a collection of videos by fetching missing parts eventually with an additional HTTP request .
12,833
def ga_track_event ( category , action , label = nil , value = nil ) ga_events . push ( GoogleAnalytics :: Event . new ( category , action , label , value ) ) end
Tracks an event or goal on a page load
12,834
def to_ini string = @lines . to_a . map { | line | line . to_ini } . join ( $/ ) string = "#{ string }\n" unless string [ - 1 ] == "\n" string end
Returns this document as a string suitable for saving to a file .
12,835
def to_hash result = { } @lines . entries . each do | section | result [ section . key ] ||= { } section . entries . each do | option | opts = Array ( option ) val = opts . map { | o | o . respond_to? ( :value ) ? o . value : o } val = val . size > 1 ? val : val . first result [ section . key ] [ opts . first . key ] =...
Returns a has representation of the INI with multi - line options as an array
12,836
def save ( path = nil ) @path = path if path raise IniParseError , 'No path given to Document#save' if @path !~ / \S / File . open ( @path , 'w' ) { | f | f . write ( self . to_ini ) } end
Saves a copy of this Document to disk .
12,837
def [] ( reference ) if Fixnum === reference return worksheets [ reference ] end if sheet = worksheets . detect { | e | e . name == reference } return sheet . poi_worksheet . nil? ? nil : sheet end cell = cell ( reference ) if Array === cell cell . collect { | e | e . value } elsif Hash === cell values = { } cell . eac...
reference can be a Fixnum referring to the 0 - based sheet or a String which is the sheet name or a cell reference .
12,838
def parse IniParse :: Generator . gen do | generator | @source . split ( "\n" , - 1 ) . each do | line | generator . send ( * Parser . parse_line ( line ) ) end end end
Creates a new Parser instance for parsing string + source + .
12,839
def []= ( key , value ) key = key . to_s if has_key? ( key ) @lines [ @indicies [ key ] ] = value else @lines << value @indicies [ key ] = @lines . length - 1 end end
Set a + value + identified by + key + .
12,840
def each ( include_blank = false ) @lines . each do | line | if include_blank || ! ( line . is_a? ( Array ) ? line . empty? : line . blank? ) yield ( line ) end end end
Enumerates through the collection .
12,841
def delete ( key ) key = key . key if key . respond_to? ( :key ) unless ( idx = @indicies [ key ] ) . nil? @indicies . delete ( key ) @indicies . each { | k , v | @indicies [ k ] = v -= 1 if v > idx } @lines . delete_at ( idx ) end end
Removes the value identified by + key + .
12,842
def << ( line ) if line . kind_of? ( IniParse :: Lines :: Section ) raise IniParse :: LineNotAllowed , "You can't add a Section to an OptionCollection." end if line . blank? || ( ! has_key? ( line . key ) ) super else self [ line . key ] = [ self [ line . key ] , line ] . flatten end self end
Appends a line to the collection .
12,843
def keys map { | line | line . kind_of? ( Array ) ? line . first . key : line . key } end
Return an array containing the keys for the lines added to this collection .
12,844
def assure_time arg = nil , opts = { } if arg arg . kind_of? ( Time ) ? arg : Time . gm ( * arg . split ( '-' ) ) elsif opts [ :default ] Time . send ( opts [ :default ] ) end end
A helper function to assure a value is an instance of time
12,845
def set_language_from session [ :lang_from ] = params [ :lang ] . to_sym I18n . locale = session [ :lang_from ] render nothing : true end
set language user translating from
12,846
def set_language_to session [ :lang_to ] = params [ :lang ] . to_sym respond_to do | format | format . html { redirect_to root_url } format . js { render nothing : true } end end
set language user translating to
12,847
def translation_ids query = Translation . all query = query . where ( lang : lang ) unless lang . blank? query = query . joins ( :translation_key ) . where ( "translation_center_translation_keys.name LIKE ?" , "%#{translation_key_name}%" ) unless translation_key_name . blank? if translator_identifier translator_class =...
return translation ids that matches this search criteria
12,848
def add_category category_name = self . name . to_s . split ( '.' ) . first category_name = self . name . to_s . split ( '.' ) . size == 1 ? 'general' : self . name . to_s . split ( '.' ) . first self . category = TranslationCenter :: Category . where ( name : category_name ) . first_or_create self . last_accessed = Ti...
add a category of this translation key
12,849
def update_status ( lang ) if self . translations . in ( lang ) . blank? self . update_attribute ( "#{lang}_status" , UNTRANSLATED ) elsif ! self . translations . in ( lang ) . accepted . blank? self . update_attribute ( "#{lang}_status" , TRANSLATED ) else self . update_attribute ( "#{lang}_status" , PENDING ) end end
updates the status of the translation key depending on the translations
12,850
def create_default_translation translation = self . translations . build ( value : self . name . to_s . split ( '.' ) . last . titleize , lang : :en , status : 'accepted' ) translation . translator = TranslationCenter . prepare_translator translation . save end
create default translation
12,851
def add_to_hash ( all_translations , lang ) levels = self . name . split ( '.' ) add_to_hash_rec ( all_translations , levels , lang . to_s ) end
adds a translation key with its translation to a translation yaml hash send the hash and the language as parameters
12,852
def money * attributes options = attributes . last . is_a? ( Hash ) ? attributes . pop : { } attributes . each do | attribute | install_money_getter attribute , options install_money_setter attribute , options end install_money_option_eval install_currency_error_tester end
installs a setter and a getter for the attribute you want to typecast as exchange money
12,853
def select_date ( value , datepicker : :bootstrap , format : nil , from : nil , xpath : nil , ** args ) fail "Must pass a hash containing 'from' or 'xpath'" if from . nil? && xpath . nil? value = value . respond_to? ( :to_date ) ? value . to_date : Date . parse ( value ) date_input = xpath ? find ( :xpath , xpath , ** ...
Selects a date by simulating human interaction with the datepicker or filling the input field
12,854
def select_simple_date ( date_input , value , format = nil ) value = value . strftime format unless format . nil? date_input . set "#{value}\e" end
Selects a date by filling the input field
12,855
def select_bootstrap_date ( date_input , value ) date_input . click picker = Picker . new picker . goto_decade_panel picker . navigate_through_decades value . year picker . find_year ( value . year ) . click picker . find_month ( value . month ) . click picker . find_day ( value . day ) . click fail if Date . parse ( d...
Selects a date by simulating human interaction with the datepicker
12,856
def subclass_with_constantize self . subclass = parent_module . const_get camelize ( self . subclass_without_constantize ) unless ! self . subclass_without_constantize || self . subclass_without_constantize . is_a? ( Class ) subclass_without_constantize end
Alias method chain to instantiate the subclass from a symbol should it not be a class
12,857
def assert_currency! arg defines? ( arg ) ? ( country_map [ arg ] || arg ) : raise ( Exchange :: NoCurrencyError . new ( "#{arg} is not a currency nor a country code matchable to a currency" ) ) end
Asserts a given argument is a currency . Tries to match with a country code if the argument is not a currency
12,858
def instantiate amount , currency if amount . is_a? ( BigDecimal ) amount else BigDecimal . new ( amount . to_s , precision_for ( amount , currency ) ) end end
Use this to instantiate a currency amount . For one it is important that we use BigDecimal here so nothing gets lost because of floating point errors . For the other This allows us to set the precision exactly according to the iso definition
12,859
def stringify amount , currency , opts = { } definition = definitions [ currency ] separators = definition [ :separators ] || { } format = "%.#{definition[:minor_unit]}f" string = format % amount major , minor = string . split ( '.' ) major . gsub! ( / \d \d \d \d \d / ) { $1 + separators [ :major ] } if separators [ :...
Converts the currency to a string in ISO 4217 standardized format either with or without the currency . This leaves you with no worries how to display the currency .
12,860
def symbolize_keys hsh new_hsh = Hash . new hsh . each_pair do | k , v | v = symbolize_keys v if v . is_a? ( Hash ) new_hsh [ k . downcase . to_sym ] = v end new_hsh end
symbolizes keys and returns a new hash
12,861
def precision_for amount , currency defined_minor_precision = definitions [ currency ] [ :minor_unit ] match = amount . to_s . match ( / \d \. \d \d / ) . to_a [ 1 .. 3 ] given_major_precision , given_minor_precision = precision_from_match * match given_major_precision + [ defined_minor_precision , given_minor_precisio...
get a precision for a specified amount and a specified currency
12,862
def translation_for ( key , lang ) self . translations . find_or_initialize_by ( translation_key_id : key . id , lang : lang . to_s , translator_type : self . class . name ) end
returns the translation a user has made for a certain key in a certain language
12,863
def complete_percentage_in ( lang ) if self . keys . blank? 100 else accepted_keys = accepted_keys ( lang ) 100 * accepted_keys . count / self . keys . count end end
gets how much complete translation of category is in a certain language
12,864
def to other , options = { } other = ISO . assert_currency! ( other ) if api_supports_currency? ( currency ) && api_supports_currency? ( other ) opts = { :at => time , :from => self } . merge ( options ) Money . new ( api . new . convert ( value , currency , other , opts ) , other , opts ) elsif fallback! to other , op...
Converts this instance of currency into another currency
12,865
def fallback! fallback = Exchange . configuration . api . fallback new_api = fallback . index ( api ) ? fallback [ fallback . index ( api ) + 1 ] : fallback . first if new_api @api = new_api return true end return false end
Fallback to the next api defined in the api fallbacks . Changes the api for the given instance
12,866
def accept unless self . accepted? self . translation_key . accepted_translation_in ( self . lang ) . try ( :update_attribute , :status , TranslationKey :: PENDING ) self . translation_key . reload self . update_attribute ( :status , ACCEPTED ) end end
Accept translation by changing its status and if there is an accepting translation make it pending
12,867
def one_translation_per_lang_per_key translation_exists = Translation . exists? ( lang : self . lang , translator_id : self . translator . id , translator_type : self . translator . class . name , translation_key_id : self . key . id ) unless translation_exists true else false self . errors . add ( :lang , I18n . t ( '...
make sure user has one translation per key per lang
12,868
def method_missing ( method , * args , & block ) if main_app_url_helper? ( method ) main_app . send ( method , * args ) else super end end
Can search for named routes directly in the main app omitting the main_app . prefix
12,869
def tags runner . tag_lists [ decision_task . workflow_execution ] ||= begin collision = 0 begin decision_task . workflow_execution . tags rescue => e collision += 1 if collision < 10 max_slot_delay = 2 ** collision - 1 sleep ( slot_time * rand ( 0 .. max_slot_delay ) ) retry end end end
exponential backoff handles rate limiting exceptions when querying tags on a workflow execution .
12,870
def say_response ( speech , end_session = true , ssml = false ) output_speech = add_speech ( speech , ssml ) { :outputSpeech => output_speech , :shouldEndSession => end_session } end
Adds a speech to the object also returns a outputspeech object .
12,871
def say_response_with_reprompt ( speech , reprompt_speech , end_session = true , speech_ssml = false , reprompt_ssml = false ) output_speech = add_speech ( speech , speech_ssml ) reprompt_speech = add_reprompt ( reprompt_speech , reprompt_ssml ) { :outputSpeech => output_speech , :reprompt => reprompt_speech , :shouldE...
Incorporates reprompt in the SDK 2015 - 05
12,872
def build_response ( session_end = true ) response_object = build_response_object ( session_end ) response = Hash . new response [ :version ] = @version response [ :sessionAttributes ] = @session_attributes unless @session_attributes . empty? response [ :response ] = response_object response . to_json end
Builds a response . Takes the version response and should_end_session variables and builds a JSON object .
12,873
def add_hash_slots ( slots ) raise ArgumentError , 'Slots can\'t be empty' slots . each do | slot | @slots [ :slot [ :name ] ] = Slot . new ( slot [ :name ] , slot [ :value ] ) end @slots end
We still don t know if all of the parameters in the request are required . Checking for the presence of intent on an IntentRequest . Takes a Hash object .
12,874
def add_slot ( name , value ) slot = Slot . new ( name , value ) @slots [ :name ] = slot slot end
Adds a slot from a name and a value .
12,875
def perform_now deserialize_arguments_if_needed run_callbacks :perform do perform ( * arguments ) end rescue => exception rescue_with_handler ( exception ) || raise ( exception ) end
Performs the job immediately . The job is not sent to the queueing adapter and will block the execution until it s finished .
12,876
def apply_rate_limit? ( env ) @exceptions . none? { | e | e . call ( env ) } && @conditions . all? { | c | c . call ( env ) } end
Apply the rate limiter if none of the exceptions apply and all the conditions are met .
12,877
def seconds_until_epoch ( epoch ) sec = ( epoch - Time . now . to_f ) . ceil sec = 0 if sec < 0 sec end
Clamp negative durations in case we re in a new rate - limiting window .
12,878
def enqueue ( options = { } ) self . scheduled_at = options [ :wait ] . seconds . from_now . to_f if options [ :wait ] self . scheduled_at = options [ :wait_until ] . to_f if options [ :wait_until ] self . queue_name = self . class . queue_name_from_part ( options [ :queue ] ) if options [ :queue ] run_callbacks :enque...
Equeue the job to be performed by the queue adapter .
12,879
def create_match ( home_team , away_team ) home_team , away_team = away_team , home_team unless home_team raise 'Invalid match' unless home_team build_match ( home_team , away_team ) end
Create a match . Used by tournament systems .
12,880
def loss_count_hash @loss_count_hash ||= matches . each_with_object ( Hash . new ( 0 ) ) { | match , hash | hash [ get_match_loser ( match ) ] += 1 } end
Get a hash of the number of losses of each team . Used by tournament systems .
12,881
def to_hash { response_id : response_id , question_id : question_id , option_id : option_id , question_pipe : question_pipe , submitted_at : submitted_at , survey_id : survey_id , other_text : other_text , answer_text : option_id || other_text ? nil : answer_text } . reject { | k , v | v . nil? } end
Strips out the answer_text when there is a valid option_id
12,882
def rgb_to_hsl ( red , green , blue ) red = round_rgb_color ( red ) green = round_rgb_color ( green ) blue = round_rgb_color ( blue ) color_max = [ red , green , blue ] . max color_min = [ red , green , blue ] . min color_range = color_max - color_min if color_range == 0 return [ 0 , 0 , ( color_max * 100.0 / 255 ) . t...
Convert RGB Color model to HSL Color model
12,883
def hsl_to_rgb ( h , s , l ) h %= 201 s %= 101 l %= 101 if l <= 49 color_max = 255.0 * ( l + l * ( s / 100.0 ) ) / 100.0 color_min = 255.0 * ( l - l * ( s / 100.0 ) ) / 100.0 else color_max = 255.0 * ( l + ( 100 - l ) * ( s / 100.0 ) ) / 100.0 color_min = 255.0 * ( l - ( 100 - l ) * ( s / 100.0 ) ) / 100.0 end if h < H...
Convert HSV Color model to RGB Color model
12,884
def to_packer packer = Smash . new packer [ 'variables' ] = self [ 'variables' ] . dup unless self [ 'variables' ] . nil? || self [ 'variables' ] . empty? packer [ 'builders' ] = [ ] unless self [ 'builders' ] . nil? || self [ 'builders' ] . empty? logger . info ( "Processing builders..." ) self [ 'builders' ] . each d...
This formats the template into packer format hash
12,885
def route_params params = { id : id } self . class . routes . values . each do | route | route . gsub ( / \w / ) do | m | m = m . delete ( ':' ) . to_sym params [ m ] = self . send ( m ) end end params end
Extract attributes required for API calls about this object
12,886
def pen_color = ( val ) if val . is_a? ( Numeric ) val %= 201 _ , s , l = Color . rgb_to_hsl ( * pen_color ) val = Color . hsl_to_rgb ( val , s , l ) end @pen_color = val end
set pen color
12,887
def change_pen_color_by ( val ) h , s , l = Color . rgb_to_hsl ( * pen_color ) @pen_color = Color . hsl_to_rgb ( h + val , s , l ) end
change pen color
12,888
def pen_shade = ( val ) val %= 101 h , s , = * Color . rgb_to_hsl ( * pen_color ) @pen_color = Color . hsl_to_rgb ( h , s , val ) end
set pen shade
12,889
def page_entries_info ( collection , options = { } ) entry_name = options [ :entry_name ] || ( collection . empty? ? 'entry' : collection . first . class . name . underscore . sub ( '_' , ' ' ) ) if collection . total_pages < 2 case collection . size when 0 ; "No #{entry_name.pluralize} found" when 1 ; "Displaying <b>1...
Renders a helpful message with numbers of displayed vs . total entries . You can use this as a blueprint for your own similar helpers .
12,890
def to_html links = @options [ :page_links ] ? windowed_links : [ ] links . unshift page_link_or_span ( @collection . previous_page , 'disabled prev_page' , @options [ :prev_label ] ) links . push page_link_or_span ( @collection . next_page , 'disabled next_page' , @options [ :next_label ] ) html = links . join ( @opti...
Process it! This method returns the complete HTML string which contains pagination links . Feel free to subclass LinkRenderer and change this method as you see fit .
12,891
def html_attributes return @html_attributes if @html_attributes @html_attributes = @options . except * ( WillPaginate :: ViewHelpers . pagination_options . keys - [ :class ] ) if @options [ :container ] and @options [ :id ] === true @html_attributes [ :id ] = @collection . first . class . name . underscore . pluralize ...
Returns the subset of + options + this instance was initialized with that represent HTML attributes for the container element of pagination links .
12,892
def windowed_links prev = nil visible_page_numbers . inject [ ] do | links , n | links << gap_marker if prev and n > prev + 1 links << page_link_or_span ( n , 'current' ) prev = n links end end
Collects link items for visible page numbers .
12,893
def stringified_merge ( target , other ) other . each do | key , value | key = key . to_s existing = target [ key ] if value . is_a? ( Hash ) and ( existing . is_a? ( Hash ) or existing . nil? ) stringified_merge ( existing || ( target [ key ] = { } ) , value ) else target [ key ] = value end end end
Recursively merge into target hash by using stringified keys from the other one
12,894
def tax_codes @tax_codes ||= begin response = TaxCloud . client . request :get_ti_cs_by_group , tic_group : group_id tax_codes = TaxCloud :: Responses :: TaxCodesByGroup . parse response Hash [ tax_codes . map { | tic | [ tic . ticid , tic ] } ] end end
All Tax Codes in this group .
12,895
def authorized ( options = { } ) options = { date_authorized : Date . today } . merge ( options ) request_params = { 'customerID' => customer_id , 'cartID' => cart_id , 'orderID' => order_id , 'dateAuthorized' => xml_date ( options [ :date_authorized ] ) } response = TaxCloud . client . request :authorized , request_pa...
Once a purchase has been made and payment has been authorized this method must be called . A matching Lookup call must have been made before this is called .
12,896
def returned ( options = { } ) options = { returned_date : Date . today } . merge ( options ) request_params = { 'orderID' => order_id , 'cartItems' => { 'CartItem' => cart_items . map ( & :to_hash ) } , 'returnedDate' => xml_date ( options [ :returned_date ] ) } response = TaxCloud . client . request :returned , reque...
Marks any included cart items as returned .
12,897
def to_s s = "" s << width . to_i . to_s if width > 0 s << "x#{height.to_i}" if height > 0 s << modifier . to_s s end
Returns the width and height in a format suitable to be passed to Geometry . parse
12,898
def should_have_attached_file name klass = self . name . gsub ( / / , '' ) . constantize matcher = have_attached_file name should matcher . description do assert_accepts ( matcher , klass ) end end
This will test whether you have defined your attachment correctly by checking for all the required fields exist after the definition of the attachment .
12,899
def should_validate_attachment_presence name klass = self . name . gsub ( / / , '' ) . constantize matcher = validate_attachment_presence name should matcher . description do assert_accepts ( matcher , klass ) end end
Tests for validations on the presence of the attachment .