idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
23,700
def synchronizable_for_types ( types ) @synchronizable_fields . select do | field_description | types . include? ( field_description [ :type ] ) end . collect do | field_description | field_description [ :field ] end end
Fields that should be synchronized on types specified in argument
23,701
def to_s ( unit = nil , precision = 0 ) if unit . to_s =~ / / units = unit . to_s . split ( '_and_' ) . map do | unit | self . class . fetch_scale ( unit ) end UnitGroup . new ( units ) . format ( @amount , precision ) else unit = self . class . fetch_scale ( unit ) unit . format ( @amount , precision ) end end
Format the measurement and return as a string . This will format using the base unit if no unit is specified .
23,702
def << ( match ) if include? ( match ) match . reject! else @matches << match @matches . sort! @matches . pop . reject! if @matches . size > @capacity end self end
Initializes the list .
23,703
def method_owner ( method_symbol ) method = Object . instance_method ( :method ) . bind ( @object ) . call ( method_symbol ) method . owner rescue NameError poor_mans_method_owner ( method , method_symbol . to_s ) end
Returns the class or module where method is defined
23,704
def parse_config fail "Config file '#{@config_path}' not found" unless @config_path . file? fail "Config file '#{@config_path}' not readable" unless @config_path . readable? @ini_file = IniFile . load ( @config_path ) begin docker_image = @ini_file [ :main ] [ 'docker_image' ] @docker_image = Docker :: Image . get ( docker_image ) @logger . info ( to_s ) do "Docker image id=#{@docker_image.id[0..11]} name=#{docker_image}" end rescue NoMethodError raise 'No docker_image in section main in config found' rescue Docker :: Error :: NotFoundError raise "Docker_image '#{docker_image}' not found" rescue Excon :: Errors :: SocketError => e raise "Docker connection could not be established: #{e.message}" end end
Parse the config file for all pools
23,705
def pools_config_content_from_file ( config_path ) ini_file = IniFile . load ( config_path ) ret_val = [ ] ini_file . each_section do | section | ret_val << [ section , ini_file [ section ] ] end ret_val end
Reads config sections from a inifile
23,706
def pools_config_contents ret_val = [ ] Dir [ @pools_directory . join ( '*.conf' ) . to_s ] . each do | config_path | ret_val += pools_config_content_from_file ( config_path ) end ret_val end
Merges config sections form all inifiles
23,707
def pools_from_config configs = { } pools_config_contents . each do | section | d = Digest :: SHA2 . new ( 256 ) hash = d . reset . update ( section [ 0 ] ) . update ( section [ 1 ] . to_s ) . to_s configs [ hash ] = { name : section [ 0 ] , config : section [ 1 ] } end configs end
Hashes configs to detect changes
23,708
def polybox args , key_args dx , dy = args proc do | tkaroid , cos_r , sin_r | x = tkaroid . x y = tkaroid . y params = tkaroid . params ex = dx [ params ] rescue dx ey = dy [ params ] rescue dy points = [ [ ex , ey ] , [ ex , - ey ] , [ - ex , - ey ] , [ - ex , ey ] ] coords = [ ] points . each do | xv , yv | coords << x + xv * cos_r - yv * sin_r coords << y + xv * sin_r + yv * cos_r end config = { } handle_generic_config ( config , params , key_args ) [ TkcPolygon , coords , config ] end end
bitmap anchor anchorPos height pixels width pixels window pathName def window args key_args x y = args
23,709
def delete_all ( pattern = { } ) result = true each ( pattern ) { | st | result &&= delete ( st ) } result end
Delete all statements from the model matching the given pattern
23,710
def find ( scope , pattern = { } ) case scope when :first each ( pattern ) . first when :all each ( pattern ) . to_a else raise RedlandError , "Invalid search scope '#{scope}' specified." end end
Find statements satisfying the given criteria .
23,711
def location_in_cache ( revision = nil ) begin elements = [ cache , repo_type , split_url , revision ] . flatten . compact . collect { | i | i . to_s } File . join ( elements ) rescue => e raise CacheCalculationError . new ( e . msg + e . backtrace . to_s ) end end
Calculates the location of a cached checkout
23,712
def method_missing ( method_name , * args , & block ) key = method_name . to_s attributes . has_key? ( key ) ? attributes [ key ] : super end
Adds syntactic suger for reading attributes .
23,713
def load_image ( path , tileable = false ) if ! @images [ path ] @images [ path ] = Gosu :: Image . new ( @window , "#{@root}/#{path}" , tileable ) end @images [ path ] end
loads an image and caches it for further use if an image has been loaded it is just being returned
23,714
def partial ( name ) name = self . class . generate_template_name name , config . file_template_extension @_cached_partials ||= { } ( @_cached_partials [ media ] ||= { } ) [ name ] ||= self . read_template_from_media name , media end
Override this in your subclass if you want to do fun things like reading templates from a database . It will be rendered by the context so all you need to do is return a string .
23,715
def has_price ( options = { } , & block ) attribute = options [ :attribute ] || :price free = ! block_given? && options [ :free ] define_method attribute . to_sym do builder = PriceBuilder . new self builder . instance_eval & block unless free builder . price end end
Provides a simple DSL to defines price instance method on the receiver .
23,716
def schedule_counters counter_classes = [ Octo :: ProductHit , Octo :: CategoryHit , Octo :: TagHit , Octo :: ApiHit , Octo :: NewsfeedHit ] counter_classes . each do | clazz | clazz . send ( :get_typecounters ) . each do | counter | name = [ clazz , counter ] . join ( '::' ) config = { class : clazz . to_s , args : [ counter ] , cron : '* * * * *' , persist : true , queue : 'high' } Resque . set_schedule name , config end end def schedule_baseline baseline_classes = [ Octo :: ProductBaseline , Octo :: CategoryBaseline , Octo :: TagBaseline ] baseline_classes . each do | clazz | clazz . send ( :get_typecounters ) . each do | counter | name = [ clazz , counter ] . join ( '::' ) config = { class : clazz . to_s , args : [ counter ] , cron : '* * * * *' , persists : true , queue : 'baseline_processing' } Resque . set_schedule name , config end end end def schedule_subscribermail name = 'SubscriberDailyMailer' config = { class : Octo :: Mailer :: SubscriberMailer , args : [ ] , cron : '0 0 * * *' , persist : true , queue : 'subscriber_notifier' } Resque . set_schedule name , config end end
Setup the schedules for counters .
23,717
def have_attributes ( attr , * more ) sum = ( more << attr ) sum . each do | name | raise ArgumentError , "Reserved attribute name #{name}" if @verbotten . include? ( name ) end @attributes += sum end
Specify symbols that will later be reified into attributes
23,718
def where ( name ) raise ArgumentError , "Unknown attribute: #{name}" unless @attributes . include? name @constraints [ name ] = AttributeConstraint . new ( name ) end
Helpful method to define constraints
23,719
def valid? ( name , value ) if @constraints . include? name then constraints [ name ] . possible_vals . include? value else true end end
Check if a given name - value pair is valid given the constraints
23,720
def open @serial ||= SerialPort . new @port , @rate @serial_input = Enumerator . new { | y | loop do y . yield @serial . readbyte end } @connected = true end
Either specify the port and serial parameters
23,721
def inherited ( base ) dup = _validators . dup base . _validators = dup . each { | k , v | dup [ k ] = v . dup } super end
Copy validators on inheritance .
23,722
def numerate ( a = [ ] ) self . section_number = a section_children . each_with_index do | c , i | c . numerate ( a . clone . push ( i + 1 ) ) end if h = self . header_element h . attributes [ :section_number ] = self . section_number end end
Numerate this section and its children
23,723
def acts_as_featured ( attribute , options = { } ) cattr_accessor :featured_attribute cattr_accessor :featured_attribute_scope self . featured_attribute = attribute self . featured_attribute_scope = options [ :scope ] || false if scope_name = options [ :create_scope ] scope_name = attribute if scope_name == true scope scope_name , -> { where ( attribute => true ) . limit ( 1 ) } end before_save :remove_featured_from_other_records after_save :add_featured_to_first_record before_destroy :add_featured_to_first_record_if_featured end
Designates an attribute on this model to indicate featuredness where only one record within a given scope may be featured at a time .
23,724
def make_charge if ! todo . annotated? "Missing due date annotation" elsif todo . due_date . overdue? && todo . tag? "Overdue due date #{todo.due_date.to_date} via tag" elsif todo . due_date . overdue? "Overdue due date" end end
What is the problem with this todo?
23,725
def << ( measurement ) datapoint = cast_to_datapoint ( measurement ) if only_save_changes and BigDecimal . new ( datapoint . value ) == BigDecimal . new ( current_value ) @logger . debug "Ignoring datapoint from #{datapoint.at} because value did not change from #{current_value}" else @current_value = datapoint . value datapoints << datapoint @logger . debug "Queuing datapoint from #{datapoint.at} with value #{current_value}" end check_datapoints_buffer end
Have shift operator load the datapoint into the datastream s datapoints array
23,726
def cast_to_datapoint ( measurement , at = Time . now ( ) ) @logger . debug "cast_to_datapoint(#{measurement.inspect})" if measurement . is_a? ( Xively :: Datapoint ) return measurement elsif measurement . is_a? ( Hash ) raise "The datapoint hash does not contain :at" unless measurement [ :at ] raise "The datapoint hash does not contain :value" unless measurement [ :value ] return Xively :: Datapoint . new ( measurement ) else return Xively :: Datapoint . new ( :at => at , :value => measurement . to_s ) end end
Converts a measurement to a Datapoint
23,727
def save_datapoints @logger . debug "Saving #{datapoints.size} datapoints to the #{id} datastream" response = XivelyConnector . connection . post ( "/v2/feeds/#{device.id}/datastreams/#{id}/datapoints" , :body => { :datapoints => datapoints } . to_json ) if response . success? clear_datapoints_buffer response else logger . error response . response raise response . response end end
Send the queued datapoints array to Xively
23,728
def put ( url , payload , options = { } , & block ) http_options = options . merge ( @basic_options ) if block_given? RestClient . put ( url , payload , http_options , & block ) else RestClient . put ( url , payload , http_options ) end end
Performs a put request .
23,729
def delete ( url , options = { } , & block ) http_options = options . merge ( @basic_options ) if block_given? RestClient . delete ( url , http_options , & block ) else RestClient . delete ( url , http_options ) end end
Performs a delete request .
23,730
def inherited ( base ) base . allegations = allegations . clone base . defendant_options = defendant_options . clone super end
Copy allegations on inheritance .
23,731
def to_s String . new . tap do | result | result << header * '|' << "\n" records . each do | record | result << record * '|' << "\n" end end end
Returns a string with the export data
23,732
def to_csv ( objects = nil ) seed_records ( objects ) unless objects . nil? CSV . generate do | csv | csv << header records . each do | record | csv << record end end end
Returns a csv string with the export data
23,733
def get_klass_from_path ( path , klass = export_model ) return klass unless ( association_name = path . shift ) get_klass_from_path ( path , klass . reflect_on_association ( association_name . to_sym ) . klass ) end
Returns a class based on a path array
23,734
def diff ( other ) check_class_compatibility ( self , other ) self_attribs = self . get_attributes ( self . class . excluded_fields ) other_attribs = other . get_attributes ( other . class . excluded_fields ) change = compare_objects ( self_attribs , other_attribs , self , other ) if other . class . conditional_fields other . class . conditional_fields . each do | key | change [ key . to_sym ] = eval ( "other.#{key}" ) unless change . empty? end end change end
Produces a Hash containing the differences between the calling object and the object passed in as a parameter
23,735
def get_attributes ( excluded ) attribs = attributes . dup attribs . delete_if { | key , value | ( ! excluded . nil? and excluded . include? ( key ) ) or key == "id" } end
Fetches the attributes of the calling object exluding the + id + field and any fields specified passed as an array of symbols via the + excluded + parameter
23,736
def reflected_names ( obj ) classes = obj . reflections class_names = [ ] classes . each do | key , cl | if eval ( cl . class_name ) . respond_to? ( "diffable" ) and cl . association_class != ActiveRecord :: Associations :: BelongsToAssociation class_names << key end end class_names end
Uses reflection to fetch the eligible associated objects for the current object excluding parent objects and child objects that do not include the Diffable mixin
23,737
def plan if @current_user . plan_id . nil? if @plan_id . nil? raise StandardError , 'Error creando plan, plan_id null' end @current_user . update_attribute ( :plan_id , @plan_id ) plan else @current_user . update_attribute ( :plan_id , @plan_id ) plan_db = @current_user . plan if plan_db . plan_code . nil? || plan_db . plan_code . empty? raise StandardError , 'Error creando plan, code null' end plan_payu = PayuLatam :: Plan . new ( plan_db . plan_code ) if plan_payu . success? @plan = plan_payu else plan_db . create_payu_plan plan end end end
crea o carga un plan en un cliente de payu se utiliza el current_user el payu_id del cliente y el plan_code del plan
23,738
def create_card raise StandardError , 'Cliente null' if @client . nil? card = PayuLatam :: Card . new ( @client ) card . params . merge! card_params card . create! if card . success? @card = card @client . remove_cards @client . add_card ( card . response ) _card = card . load ( card . response [ 'token' ] ) @current_user . payu_cards . create ( token : @card . response [ 'token' ] , last_4 : _card [ 'number' ] , brand : _card [ 'type' ] ) else raise StandardError , "Error generando token de tarjeta: #{card.error}" end end
crear tarjeta de credito en payu utiliza los params recibidos
23,739
def find_card @client . remove_cards card = PayuLatam :: Card . new ( @client ) card . load ( PayuCard . find ( @selected_card ) . token ) @client . add_card ( { token : card . resource [ 'token' ] } ) end
busca la info de una tarjeta de payu
23,740
def limit options = { } page = options . delete :page query = options . dup collection = new_collection scoped_query ( options = { :limit => options [ :limit ] , :offset => options [ :offset ] , :order => [ options [ :order ] ] } . merge ( query ) ) options . merge! :count => calculate_total_records ( query ) , :page => page collection . paginator = DataMapper :: Paginator :: Main . new options collection end
Limit results .
23,741
def limit_page page = nil , options = { } if page . is_a? ( Hash ) options = page else options [ :page ] = page . to_i end options [ :page ] = options [ :page ] . to_i > 0 ? options [ :page ] : DataMapper :: Paginator . default [ :page ] options [ :limit ] = options [ :limit ] . to_i || DataMapper :: Paginator . default [ :limit ] options [ :offset ] = options [ :limit ] * ( options [ :page ] - 1 ) options [ :order ] = options [ :order ] || DataMapper :: Paginator . default [ :order ] limit options end
Limit results by page .
23,742
def calculate_total_records query query . delete :page query . delete :limit query . delete :offset collection = new_collection scoped_query ( query ) collection . count . to_i end
Calculate total records
23,743
def + ( other_program ) raise ArgumentError if @program . class != other_program . class additional_duration = other_program . duration + 1 program . duration += additional_duration occurrence . duration += additional_duration occurrence . end_time += additional_duration self end
Extends this scheduled program with another program of the same type .
23,744
def before_all ( key , options ) required ( key ) if ( options . has_key? ( :required ) and options [ :required ] == true ) if options . has_key? ( :dependencies ) dependencies ( key , options [ :dependencies ] ) elsif options . has_key? ( :dependency ) dependency ( key , options [ :dependency ] ) end end
This method is executed before any call to a public method .
23,745
def store ( key , process , options = { } ) unless ( options . has_key? ( :extract ) and options [ :extract ] == false ) if validator . datas . has_key? ( key ) value = ( ( options . has_key? ( :cast ) and options [ :cast ] == false ) ? validator . datas [ key ] : process . call ( validator . datas [ key ] ) ) if ( options . has_key? ( :in ) ) in_array? ( key , options [ :in ] ) elsif ( options . has_key? ( :equals ) ) equals_to? ( key , options [ :equals ] ) elsif ( options . has_key? ( :equals_key ) ) equals_key? ( key , options [ :equals_key ] ) end options . has_key? ( :rename ) ? ( validator . filtered [ options [ :rename ] ] = value ) : ( validator . filtered [ key ] = value ) end end end
Tries to store the associated key in the filtered key transforming it with the given process .
23,746
def raise_type_error ( key , type ) raise_error ( type : "type" , key : key , supposed : type , found : key . class ) end
Raises a type error with a generic message .
23,747
def required ( key ) raise_error ( type : "required" , key : key ) unless validator . datas . has_key? ( key ) end
Checks if a required key is present in provided datas .
23,748
def dependency ( key , dependency ) raise_error ( type : "dependency" , key : "key" , needed : dependency ) unless validator . datas . has_key? ( dependency ) end
Checks if a dependency is respected . A dependency is a key openly needed by another key .
23,749
def is_typed? ( key , type ) return ( ! validator . datas . has_key? ( key ) or validator . datas [ key ] . kind_of? ( type ) ) end
Check if the value associated with the given key is typed with the given type or with a type inheriting from it .
23,750
def in_array? ( key , values ) raise_error ( type : "array.in" , key : key , supposed : values , value : validator . datas [ key ] ) unless ( values . empty? or values . include? ( validator . datas [ key ] ) ) end
Checks if the value associated with the given key is included in the given array of values .
23,751
def equals_to? ( key , value ) raise_error ( type : "equals" , key : key , supposed : value , found : validator . datas [ key ] ) unless validator . datas [ key ] == value end
Checks if the value associated with the given key is equal to the given value .
23,752
def match? ( key , regex ) return ( ! validator . datas . has_key? ( key ) or validator . datas [ key ] . to_s . match ( regex ) ) end
Check if the value associated with the given key matches the given regular expression .
23,753
def contains? ( key , values , required_values ) raise_error ( type : "contains.values" , required : required_values , key : key ) if ( values & required_values ) != required_values end
Checks if the value associated with the given key has the given required values .
23,754
def has_keys? ( key , required_keys ) raise_error ( type : "contains.keys" , required : required_keys , key : key ) if ( validator . datas [ key ] . keys & required_keys ) != required_keys end
Checks if the value associated with the given key has the given required keys .
23,755
def blog__clean_tag_parents tag_parents = LatoBlog :: TagParent . all tag_parents . map { | tp | tp . destroy if tp . tags . empty? } end
This function cleans all old tag parents without any child .
23,756
def blog__get_tags ( order : nil , language : nil , search : nil , page : nil , per_page : nil ) tags = LatoBlog :: Tag . all order = order && order == 'ASC' ? 'ASC' : 'DESC' tags = _tags_filter_by_order ( tags , order ) tags = _tags_filter_by_language ( tags , language ) tags = _tags_filter_search ( tags , search ) tags = tags . uniq ( & :id ) total = tags . length page = page &. to_i || 1 per_page = per_page &. to_i || 20 tags = core__paginate_array ( tags , per_page , page ) { tags : tags && ! tags . empty? ? tags . map ( & :serialize ) : [ ] , page : page , per_page : per_page , order : order , total : total } end
This function returns an object with the list of tags with some filters .
23,757
def blog__get_category ( id : nil , permalink : nil ) return { } unless id || permalink if id category = LatoBlog :: Category . find_by ( id : id . to_i ) else category = LatoBlog :: Category . find_by ( meta_permalink : permalink ) end category . serialize end
This function returns a single category searched by id or permalink .
23,758
def random ( count : 1 ) list = self . connection . srandmember ( @key , count ) return nil if list . nil? return count == 1 ? list [ 0 ] : :: Set . new ( list ) end
Returns random items from the set
23,759
def difference ( other , dest : nil ) destination = coerce_destination ( dest ) results = if destination . nil? :: Set . new ( self . connection . sdiff ( @key , other . key ) ) else self . connection . sdiffstore ( destination . key , @key , other . key ) end return results end
Computes the difference of the two sets and stores the result in dest . If no destination provided computes the results in memory .
23,760
def intersection ( other , dest : nil ) destination = coerce_destination ( dest ) results = if destination . nil? :: Set . new ( self . connection . sinter ( @key , other . key ) ) else self . connection . sinterstore ( destination . key , @key , other . key ) end return results end
Computes the interesection of the two sets and stores the result in dest . If no destination provided computes the results in memory .
23,761
def union ( other , dest : nil ) destination = coerce_destination ( dest ) results = if destination . nil? :: Set . new ( self . connection . sunion ( @key , other . key ) ) else self . connection . sunionstore ( destination . key , @key , other . key ) end return results end
Computes the union of the two sets and stores the result in dest . If no destination provided computes the results in memory .
23,762
def exec ( * args , & block ) if @scope @scope . instance_variables . each do | name | instance_variable_set ( name , @scope . instance_variable_get ( name ) ) end end @ivars . each do | name , value | instance_variable_set ( name , value ) end instance_exec ( * args , & block ) end
Execute a block in the manipulated environment .
23,763
def process_appropriate ( doc , cmd ) return process_regex ( doc , cmd ) if ( cmd . is_a? Regexp ) return process_proc ( doc , cmd ) if ( cmd . is_a? Proc ) if cmd . is_a? ( String ) return process_xpath ( doc , cmd ) if cmd . start_with? ( "x|" ) return process_css ( doc , cmd ) if cmd . start_with? ( "c|" ) end nil end
accepts nokogiri doc s only atm
23,764
def validate! logger . debug "Starting validation for #{description}" raise NotFound . new path unless File . exists? path logger . info "Successfully validated #{description}" self end
Initializes a Connection for use in a particular directory
23,765
def seed_model ( model_class , options = { } ) if model_class . count == 0 or options [ :force ] table_name = options [ :file_name ] || model_class . table_name puts "Seeding #{model_class.to_s.pluralize}..." csv_file = @@csv_class . open ( Rails . root + "db/csv/#{table_name}.csv" , :headers => true ) seed_from_csv ( model_class , csv_file ) end end
Receives the reference to the model class to seed . Seeds only when there are no records in the table or if the + force + option is set to true . Also optionally it can receive the + file_name + to use .
23,766
def seed_from_csv ( migration_class , csv_file ) migration_class . transaction do csv_file . each do | line_values | record = migration_class . new line_values . to_hash . keys . map { | attribute | record . send ( "#{attribute.strip}=" , line_values [ attribute ] . strip ) rescue nil } record . save ( :validate => false ) end end end
Receives the class reference and csv file and creates all thre records inside one transaction
23,767
def add_dsts * dsts dsts . each do | dst | if dst . empty? or dst == Edoors :: ACT_SEP or dst [ 0 ] == Edoors :: PATH_SEP or dst =~ / \/ \? / or dst =~ / \/ / or dst =~ / \s / raise Edoors :: Exception . new "destination #{dst} is not acceptable" end @dsts << dst end end
adds destinations to the destination list
23,768
def set_dst! a , d @action = a if d . is_a? Edoors :: Iota @dst = d else @dst = nil _split_path! d end end
sets the current destination
23,769
def apply_link! lnk init! lnk . door clear_dsts! add_dsts * lnk . dsts set_link_keys * lnk . keys end
applies the effects of the given Link
23,770
def set_link_keys * args @link_keys . clear if not @link_keys . empty? args . compact! args . each do | lf | @link_keys << lf end @link_value = @payload . select { | k , v | @link_keys . include? k } end
sets the links keys
23,771
def link_with? link return true if link . value . nil? link . value . keys . inject ( { } ) { | h , k | h [ k ] = @payload [ k ] if @payload . has_key? ( k ) ; h } . eql? link . value end
tries to link the Particle with the given Link
23,772
def clear_merged! r = false @merged . each do | p | p . clear_merged! r r . release_p p if r end @merged . clear end
recursively clears the merged Particle list
23,773
def sr comp_div = @player_page . css ( '.competitive-rank > .h5' ) return - 1 if comp_div . empty? content = comp_div . first . content content . to_i if Integer ( content ) rescue - 1 end
Retrieve a player s current competitive season ranking . Returns - 1 if player did not complete placements .
23,774
def main_qp hero_img = hidden_mains_style . content . scan ( / \. \( \) /mis ) . flatten . first hero_img . scan ( / \/ \/ \/ /i ) . flatten . first end
Retrieve player s main Quick Play hero in lowercase form .
23,775
def main_comp hero_img = hidden_mains_style . content . scan ( / \. \( \) /mis ) . flatten . first hero_img . scan ( / \/ \/ \/ /i ) . flatten . first end
Retrieve player s main Competitive hero in lowercase form . You should check if the sr is - 1 before attempting to call this .
23,776
def to_xml ( body ) root = @api_options [ :root_element ] . nil? ? 'Request' : @api_options [ :root_element ] body . to_xml ( root : root , skip_instruct : true , skip_types : true ) end
parse body from hash to xml format
23,777
def parse_option ( option , argv ) if option =~ / / Ripl :: Profiles . load ( ( $1 . empty? ? argv . shift . to_s : $1 ) . split ( ':' ) ) else super end end
add command line option
23,778
def convert ( point ) today = Date . new ( year , month , day ) new_seconds = seconds + fractional + ( minutes + hours * 60 ) * 60 if hours >= 6 && hours < 18 start = NewTime . sunrise ( today , point ) finish = NewTime . sunset ( today , point ) new_start_hour = 6 else if hours < 6 start = NewTime . sunset ( today - 1 , point ) finish = NewTime . sunrise ( today , point ) new_start_hour = 18 - 24 else start = NewTime . sunset ( today , point ) finish = NewTime . sunrise ( today + 1 , point ) new_start_hour = 18 end end start + ( new_seconds . to_f / ( 60 * 60 ) - new_start_hour ) * ( finish - start ) / 12 end
Convert back to normal time
23,779
def delivery_status ( options ) raise ArgumentError , 'an options Hash is required' if ! options . instance_of? ( Hash ) raise ArgumentError , ':sender_address is required' if options [ :sender_address ] . nil? && @sender_address . nil? options [ :sender_address ] = options [ :sender_address ] || @sender_address Response . new self . class . get ( "/smsmessaging/outbound/#{options[:sender_address]}/requests/#{options[:request_id]}/deliveryInfos" , :basic_auth => @auth , :headers => SMSIFIED_HTTP_HEADERS ) end
Intantiate a new class to work with reporting
23,780
def list ( * args ) options = args . last . is_a? ( Hash ) ? args . pop : { } response = get ( 'threads/list' , options ) end
Returns a list of threads sorted by the date created .
23,781
def listPosts ( * args ) options = args . last . is_a? ( Hash ) ? args . pop : { } thread = args . first options . merge! ( :thread => thread ) if ( [ :ident , :link ] & options . keys ) . empty? response = get ( 'threads/listPosts' , options ) end
Returns a list of posts within a thread .
23,782
def remove ( * args ) options = args . last . is_a? ( Hash ) ? args . pop : { } thread = args . first options . merge! ( :thread => thread ) if ( [ :ident , :link ] & options . keys ) . empty? response = post ( 'threads/remove' , options ) end
Removes a thread
23,783
def dump ( type ) get_many ( type ) . map { | d | d . to_s } . sort . join ( "\n" ) end
Returns a String containing a representation of the current content of in this storage .
23,784
def select_or_fill ( field , value ) case field_type ( field ) when :select begin select ( value , :from => field ) rescue Capybara :: ElementNotFound raise Kelp :: OptionNotFound , "Field '#{field}' has no option '#{value}'" end when :fillable_field fill_in ( field , :with => value ) end end
Select a value from a dropdown or listbox or fill in a text field depending on what kind of form field is available . If field is a dropdown or listbox select value from that ; otherwise assume field is a text box .
23,785
def field_should_be_empty ( field , scope = { } ) in_scope ( scope ) do _field = nice_find_field ( field ) if ! ( _field . nil? || _field . value . nil? || _field . value . strip == '' ) raise Kelp :: Unexpected , "Expected field '#{field}' to be empty, but value is '#{_field.value}'" end end end
Verify that the given field is empty or nil .
23,786
def field_value ( field ) element = find_field ( field ) value = ( element . tag_name == 'textarea' ) ? element . text : element . value if value . class == Array value = value . first end return value . to_s end
Return the string value found in the given field . If the field is nil return the empty string .
23,787
def fields_should_contain ( field_values , scope = { } ) in_scope ( scope ) do field_values . each do | field , value | _field = find_field ( field ) if value . nil? or value . strip . empty? field_should_be_empty ( field ) elsif _field . tag_name == 'select' dropdown_should_equal ( field , value ) else field_should_contain ( field , value ) end end end end
Verify the values of multiple fields given as a Hash .
23,788
def field_type ( field ) select = all ( :select , field ) . count fillable = all ( :fillable_field , field ) . count count = select + fillable case count when 0 raise Kelp :: FieldNotFound , "No field with id, name, or label '#{field}' found" when 1 return select > 0 ? :select : :fillable_field else raise Kelp :: AmbiguousField , "Field '#{field}' is ambiguous" end end
Figure out whether the field locator matches a single select or fillable field .
23,789
def create_message ( message ) begin @producer . produce ( JSON . dump ( message ) , topic : @topic ) rescue Kafka :: BufferOverflow Octo . logger . error 'Buffer Overflow. Sleeping for 1s' sleep 1 retry end end
Creates a new message .
23,790
def create_referrer if self . respond_to? ( :_get_reqref ) if struct = _get_reqref self . create_referee ( origin : struct . referrer_url , request : struct . request_url , visits : struct . visit_count ) end end end
after create hook to create a corresponding + Referee +
23,791
def init_docker! Docker . options = @options set_docker_url LOG . debug { "Docker URL: #{Docker.url}" } LOG . debug { "Docker Options: #{Docker.options.inspect}" } Docker . validate_version! end
Initialize Docker Client
23,792
def immediate_at = ( level ) @immediate . clear immediate_at = case level when String ; level . split ( ',' ) . map { | x | x . strip } when Array ; level else Array ( level ) end immediate_at . each do | lvl | num = :: Logsly :: Logging182 . level_num ( lvl ) next if num . nil? @immediate [ num ] = true end end
Configure the levels that will trigger an immediate flush of the logging buffer . When a log event of the given level is seen the buffer will be flushed immediately . Only the levels explicitly given in this assignment will flush the buffer ; if an error message is configured to immediately flush the buffer a fatal message will not even though it is a higher level . Both must be explicitly passed to this assignment .
23,793
def add ( other ) case other when LinExpr @terms . merge! ( other . terms ) { | _ , c1 , c2 | c1 + c2 } when Variable if @terms . key? other @terms [ other ] += 1.0 else @terms [ other ] = 1.0 end else fail TypeError end self end
Add terms from the other expression to this one
23,794
def inspect @terms . map do | var , coeff | value = var . value next if coeff == 0 || value == 0 || value == false coeff == 1 ? var . name : "#{var.name} * #{coeff}" end . compact . join ( ' + ' ) end
Produce a string representing the expression
23,795
def value val = self . lazy_proc? ( @value ) ? self . coerce ( @value . call ) : @value val . respond_to? ( :returned_value ) ? val . returned_value : val end
if reading a lazy_proc call the proc and return its coerced return val otherwise just return the stored value
23,796
def method_missing ( meth , * args , & block ) xpath = _xpath_for_element ( meth . to_s , args . shift ) return nil if xpath . empty? if block_given? xpath . each_with_index do | node , idx | @nodes . push ( node ) case block . arity when 1 yield idx when 2 yield self . class . new ( node , @namespaces , false ) , idx else yield end @nodes . pop end self else node = xpath . first if node . xpath ( 'text()' ) . length == 1 content = node . xpath ( 'text()' ) . first . content case meth . to_s when / \? / ! ! Regexp . new ( / /i ) . match ( content ) else content end else self . class . new ( node , @namespaces , false ) end end end
The workhorse finds the node matching meth .
23,797
def write_xml ( options = { mapping : :_default } ) xml = save_to_xml ( options ) formatter = REXML :: Formatters :: Pretty . new formatter . compact = true io = :: StringIO . new formatter . write ( xml , io ) io . string end
Writes this mapped object as a pretty - printed XML string .
23,798
def to_cert ( raw_cert ) logger . debug "CertMunger raw_cert:\n#{raw_cert}" new_cert = build_cert ( raw_cert ) logger . debug "CertMunger reformatted_cert:\n#{new_cert}" logger . debug 'Returning OpenSSL::X509::Certificate.new on new_cert' OpenSSL :: X509 :: Certificate . new new_cert end
Attempts to munge a string into a valid X509 certificate
23,799
def build_cert ( raw_cert ) tmp_cert = [ '-----BEGIN CERTIFICATE-----' ] cert_contents = if raw_cert . lines . count == 1 one_line_contents ( raw_cert ) else multi_line_contents ( raw_cert ) end tmp_cert << cert_contents . flatten tmp_cert << '-----END CERTIFICATE-----' tmp_cert . join ( "\n" ) . rstrip end
Creates a temporary cert and orchestrates certificate body reformatting