idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
21,000
def assoc_values ( * others ) all_keys = keys others . each { | hash | all_keys . concat ( hash . keys ) } all_keys . to_compact_hash do | k | others . map { | other | other [ k ] } . unshift ( self [ k ] ) end end
Returns a hash which associates each key in this hash with the value mapped by the others .
21,001
def enum_keys_with_value ( target_value = nil , & filter ) return enum_keys_with_value { | v | v == target_value } if target_value filter_on_value ( & filter ) . keys end
Returns an Enumerable whose each block is called on each key which maps to a value which either equals the given target_value or satisfies the filter block .
21,002
def copy_recursive copy = Hash . new keys . each do | k | value = self [ k ] copy [ k ] = Hash === value ? value . copy_recursive : value end copy end
Returns a new Hash that recursively copies this hash s values . Values of type hash are copied using copy_recursive . Other values are unchanged .
21,003
def body msg = "Hello.\n\n" if job . status == 200 msg += "Your backup of database #{job.rds_id} is complete.\n" + ( job . files . empty? ? "" : "Output is at #{job.files.first[:url]}\n" ) else msg += "Your backup is incomplete. (job ID #{job.backup_id})\n" end msg += "Job status: #{job.message}" end
defines the body of a Job s status email
21,004
def bootstrapped_form object , options = { } , & block options [ :builder ] = BootstrapFormBuilder form_for object , options , & block end
merely setup the form_for to use our new form builder
21,005
def api_version version = params [ :api_version ] return current_api_version if version == 'current' api_versions . include? ( version ) ? version : current_api_version end
The api version of the current request
21,006
def allowable_log_level ( log_level ) log_level = "" if log_level . nil? log_level = log_level . to_sym unless log_level . is_a? ( Symbol ) if ! @log_levels . include? ( log_level ) log_level = :notice end return log_level end
Initializes the task run and sets the start time
21,007
def run_task begin run rescue Exception => e @task_run . add_error_text ( e . class . name + ": " + e . message ) @task_run . add_error_text ( e . backtrace . inspect ) @task_run . success = false end finally @task_run . end_time = Time . now @task_run . save end
this calls task with error catching if an error is caught sets success to false and records the error either way sets an end time and saves the task run information
21,008
def force_due r = self r . update_attributes ( :started_at => ( Time . now . utc - Jobtracker . runner_read_freq - 1 . second ) ) end
update runner started_at to be whatever the notification is - 1 . second which will force runner to be due
21,009
def create_user ( user , opts = { } ) data , _status_code , _headers = create_user_with_http_info ( user , opts ) return data end
Creates a new user in the store
21,010
def get_user ( id , opts = { } ) data , _status_code , _headers = get_user_with_http_info ( id , opts ) return data end
Returns a single user
21,011
def update_user ( id , user , opts = { } ) data , _status_code , _headers = update_user_with_http_info ( id , user , opts ) return data end
Updates a single user
21,012
def time_for_period ( string = nil ) @last_date = case string when / / , / / now when / / tomorrow_time when / / yesterday_time when / / , / / , / / , / / , / / , / / , / / time_for_weekday ( string ) when / / now + period_of_time_from_string ( string . gsub ( "next" , "1" ) ) when / / now - period_of_time_from_string ( string . gsub ( "last" , "1" ) ) when / \d \s \s / @last_date ||= now @last_date -= period_of_time_from_string ( string ) when / \d \s \s / @last_date ||= now now - period_of_time_from_string ( string ) when / \d \s \s / @last_date ||= now @last_date += period_of_time_from_string ( string ) when / / , / \d \s / , / \d \s / , / \d \s / , / \d \s / , / \d \s / , / \d \s / now + period_of_time_from_string ( string ) when / \d \d \d / time_from_date ( string ) when / / , / / now + rand ( 100_000_000 ) when / / now - rand ( 100_000_000 ) end return @last_date end
Returns the formatted date according to the given period of time expresed in a literal way
21,013
def is_required_day? ( time , day ) day_to_ask = "#{day}?" result = eval ( "time.#{day_to_ask}" ) if time . respond_to? day_to_ask . to_sym return result end
Method to know if the day is the required day
21,014
def multiply_by ( string ) return minute_mult ( string ) || hour_mult ( string ) || day_mult ( string ) || week_mult ( string ) || month_mult ( string ) || year_mult ( string ) || 1 end
Returns seconds to multiply by for the given string
21,015
def time_from_date ( date ) numbers = date . scan ( / \d / ) . map! { | i | i . to_i } day = numbers [ 2 - numbers . index ( numbers . max ) ] Date . new ( numbers . max , numbers [ 1 ] , day ) . to_time end
Return the Time object according to the splitted date in the given array
21,016
def method_missing ( meth ) self . class . send :define_method , meth do string = meth . to_s . gsub ( "_" , " " ) self . for ( "for('#{string}')" ) end begin self . send ( meth . to_s ) rescue raise "Method does not exists (#{meth})." end end
Try to convert Missing methods to string and call to for method with converted string
21,017
def update_flags self . allow_anon = self . require_anon = self . require_admin = self . unknown_controller = self . non_standard = false self . unknown_controller = true klass = :: Incline . get_controller_class ( controller_name ) if klass self . unknown_controller = false if klass . require_admin_for? ( action_name ) self . require_admin = true elsif klass . require_anon_for? ( action_name ) self . require_anon = true elsif klass . allow_anon_for? ( action_name ) self . allow_anon = true end unless klass . instance_method ( :valid_user? ) . owner == Incline :: Extensions :: ActionControllerBase && klass . instance_method ( :authorize! ) . owner == Incline :: Extensions :: ActionControllerBase self . non_standard = true end end end
Updates the flags based on the controller configuration .
21,018
def permitted ( refresh = false ) @permitted = nil if refresh @permitted ||= if require_admin? 'Administrators Only' elsif require_anon? 'Anonymous Only' elsif allow_anon? 'Everyone' elsif groups . any? names = groups . pluck ( :name ) . map { | v | "\"#{v}\"" } 'Members of ' + if names . count == 1 names . first elsif names . count == 2 names . join ( ' or ' ) else names [ 0 ... - 1 ] . join ( ', ' ) + ', or ' + names . last end else 'All Users' end + if non_standard ' (Non-Standard)' else '' end end
Gets a string describing who is permitted to execute the action .
21,019
def group_ids = ( values ) values ||= [ ] values = [ values ] unless values . is_a? ( :: Array ) values = values . reject { | v | v . blank? } . map { | v | v . to_i } self . groups = Incline :: AccessGroup . where ( id : values ) . to_a end
Sets the group IDs accepted by this action .
21,020
def check_comment ( options = { } ) return false if invalid_options? message = call_akismet ( 'comment-check' , options ) { :spam => ! self . class . valid_responses . include? ( message ) , :message => message } end
This is basically the core of everything . This call takes a number of arguments and characteristics about the submitted content and then returns a thumbs up or thumbs down . Almost everything is optional but performance can drop dramatically if you exclude certain elements .
21,021
def call_akismet ( akismet_function , options = { } ) http_post ( Net :: HTTP . new ( [ self . options [ :api_key ] , self . class . host ] . join ( '.' ) , options [ :proxy_host ] , options [ :proxy_port ] ) , akismet_function , options . update ( :blog => self . options [ :blog ] ) . to_query ) end
Internal call to Akismet . Prepares the data for posting to the Akismet service .
21,022
def define_action ( action , & block ) action = action . to_sym defined_actions << action unless defined_actions . include? ( action ) if action . in? ( Evvnt :: ClassTemplateMethods . instance_methods ) define_class_action ( action , & block ) end if action . in? ( Evvnt :: InstanceTemplateMethods . instance_methods ) define_instance_action ( action , & block ) end action end
Define an action for this class to map on to the Evvnt API for this class s resource .
21,023
def get_request ( hash = true ) resp = RestClient . get get_url hash ? Hash . from_xml ( resp ) . it_keys_to_sym : resp end
send GET HTTP request
21,024
def filter ( * conditions ) latest = ! conditions . select { | item | item === true } . empty? filters = translate_conditions ( conditions ) items = list ( latest ) unless filters . empty? items = items . select do | item | ! filters . select { | filter | match_filter ( filter , item ) } . empty? end end items end
Returns list of available os versions filtered by conditions
21,025
def is_version ( string ) return false if string === false || string === true || string . nil? string . to_s . match ( / \d \d \. \- / ) end
Returns true if provided value is a version string
21,026
def is_os ( string ) return false if string === false || string === true || string . nil? @os . key? ( string . to_sym ) end
Returns true if provided value is a registered OS
21,027
def match_filter ( filter , item ) filter . each_pair do | key , value | unless item . key? ( key ) return false end unless value . is_a? ( Array ) return false if value != item [ key ] else return true if value . empty? return false unless value . include? ( item [ key ] ) end end true end
Returns true if item matches filter conditions
21,028
def list ( latest = false ) result = [ ] @os . map do | os , versions | unless latest versions . each { | version | result << { os : os , version : version } } else result << { os : os , version : versions . last } if versions . length > 0 end end result end
Returns list of available os versions
21,029
def fetch_and_cache_job ( job_id ) job = fetch_job ( job_id ) self . cached_jobs [ job_id ] = job unless job . nil? @min_climbed_job_id = job_id if job_id < @min_climbed_job_id @max_climbed_job_id = job_id if job_id > @max_climbed_job_id return job end
Helper method similar to fetch_job that retrieves the job identified by + job_id + caches it and updates counters before returning the job . If the job does not exist nothing is cached however counters will be updated and nil is returned
21,030
def connect_to_mycroft if ARGV . include? ( "--no-tls" ) @client = TCPSocket . open ( @host , @port ) else socket = TCPSocket . new ( @host , @port ) ssl_context = OpenSSL :: SSL :: SSLContext . new ssl_context . cert = OpenSSL :: X509 :: Certificate . new ( File . open ( @cert ) ) ssl_context . key = OpenSSL :: PKey :: RSA . new ( File . open ( @key ) ) @client = OpenSSL :: SSL :: SSLSocket . new ( socket , ssl_context ) begin @client . connect rescue end end end
connects to mycroft aka starts tls if necessary
21,031
def send_manifest begin manifest = JSON . parse ( File . read ( @manifest ) ) manifest [ 'instanceId' ] = "#{Socket.gethostname}_#{SecureRandom.uuid}" if @generate_instance_ids @instance_id = manifest [ 'instanceId' ] rescue end send_message ( 'APP_MANIFEST' , manifest ) end
Sends the app manifest to mycroft
21,032
def query ( capability , action , data , priority = 30 , instance_id = nil ) query_message = { id : SecureRandom . uuid , capability : capability , action : action , data : data , priority : priority , instanceId : [ ] } query_message [ :instanceId ] = instance_id unless instance_id . nil? send_message ( 'MSG_QUERY' , query_message ) end
Sends a query to mycroft
21,033
def broadcast ( content ) message = { id : SecureRandom . uuid , content : content } send_message ( 'MSG_BROADCAST' , message ) end
Sends a broadcast to the mycroft message board
21,034
def visit ( page_class , query_params = { } , browser = @browser ) page = page_class . new ( browser ) url = query_params . empty? ? page . page_url : page . page_url ( query_params ) browser . goto ( url ) yield page if block_given? page end
Initializes an instance of the given page class drives the given browser instance to the page s url with any given query parameters appended yields the page instance to a block if given and returns the page instance .
21,035
def on ( page_class , browser = @browser ) page = page_class . new ( browser ) yield page if block_given? page end
Initializes and returns an instance of the given page class . Yields the page instance to a block if given .
21,036
def load_directory ( path ) unless File . directory? ( path ) raise "Konfig couldn't load because it was unable to access #{ path }. Please make sure the directory exists and has the correct permissions." end Dir [ File . join ( path , "*.yml" ) ] . each { | f | load_file ( f ) } end
Loads all yml files in a directory into this store Will not recurse into subdirectories .
21,037
def load_file ( path ) d = YAML . load_file ( path ) if d . is_a? ( Hash ) d = HashWithIndifferentAccess . new ( d ) e = Evaluator . new ( d ) d = process ( d , e ) end @data [ File . basename ( path , ".yml" ) . downcase ] = d end
Loads a single yml file into the store
21,038
def profile_new_command ( profile_command ) profile_command . desc _ ( 'cli.profile.new.desc' ) profile_command . arg_name "[name]" profile_command . command :new do | profile_new_command | profile_new_command . flag :p , :arg_name => 'path' , :desc => _ ( 'cli.profile.new.path_flag_desc' ) profile_new_command . action do | global_options , options , args | path = options [ :p ] || '' help_now! ( error ( _ ( 'cli.profile.new.name_arg_missing' ) ) ) if args . count == 0 Bebox :: ProfileWizard . new . create_new_profile ( project_root , args . first , path ) end end end
Profile new command
21,039
def profile_remove_command ( profile_command ) profile_command . desc _ ( 'cli.profile.remove.desc' ) profile_command . command :remove do | profile_remove_command | profile_remove_command . action do | global_options , options , args | Bebox :: ProfileWizard . new . remove_profile ( project_root ) end end end
Profile remove command
21,040
def profile_list_command ( profile_command ) profile_command . desc _ ( 'cli.profile.list.desc' ) profile_command . command :list do | profile_list_command | profile_list_command . action do | global_options , options , args | profiles = Bebox :: ProfileWizard . new . list_profiles ( project_root ) title _ ( 'cli.profile.list.current_profiles' ) profiles . map { | profile | msg ( profile ) } warn ( _ ( 'cli.profile.list.no_profiles' ) ) if profiles . empty? linebreak end end end
Profile list command
21,041
def wrap ( width : 78 , indent : 0 , indent_after : false , segments : false ) if segments text = Text . wrap_segments ( @lines [ @line ] , width : width , indent : indent , indent_after : indent_after ) else text = Text . wrap ( @lines [ @line ] , width : width , indent : indent , indent_after : indent_after ) end @lines . delete_at ( @line ) @line -= 1 text . split ( "\n" ) . each { | line | self . next ( line ) } return self end
Wrap the current line to + width + with an optional + indent + . After wrapping the current line will be the last line wrapped .
21,042
def search ( search_string = nil , index = 0 , num_results = 10 ) raise "no search string provieded!" if ( search_string === nil ) fts = "fts=" + search_string . split ( ) . join ( '+' ) . to_s min = "min=" + index . to_s count = "count=" + num_results . to_s args = [ fts , min , count ] . join ( '&' ) return call_api ( __method__ , args ) end
Searches the shopsense API
21,043
def get_look ( look_id = nil ) raise "no look_id provieded!" if ( look_id === nil ) look = "look=" + look_id . to_s return call_api ( __method__ , look ) end
This method returns information about a particular look and its products .
21,044
def get_stylebook ( user_name = nil , index = 0 , num_results = 10 ) raise "no user_name provieded!" if ( user_name === nil ) handle = "handle=" + user_name . to_s min = "min=" + index . to_s count = "count=" + num_results . to_s args = [ handle , min , count ] . join ( '&' ) return call_api ( __method__ , args ) end
This method returns information about a particular user s Stylebook the looks within that Stylebook and the title and description associated with each look .
21,045
def get_looks ( look_type = nil , index = 0 , num_results = 10 ) raise "invalid filter type must be one of the following: #{self.look_types}" if ( ! self . look_types . include? ( look_type ) ) type = "type=" + look_type . to_s min = "min=" + index . to_s count = "count=" + num_results . to_s args = [ type , min , count ] . join ( '&' ) return call_api ( __method__ , args ) end
This method returns information about looks that match different kinds of searches .
21,046
def get_trends ( category = "" , products = 0 ) cat = "cat=" + category . to_s products = "products=" + products . to_s args = [ cat , products ] . join ( '&' ) return call_api ( __method__ , args ) end
This method returns the popular brands for a given category along with a sample product for the brand - category combination .
21,047
def call_api ( method , args = nil ) method_url = self . api_url + self . send ( "#{method}_path" ) pid = "pid=" + self . partner_id format = "format=" + self . format site = "site=" + self . site if ( args === nil ) then uri = URI . parse ( method_url . to_s + [ pid , format , site ] . join ( '&' ) . to_s ) else uri = URI . parse ( method_url . to_s + [ pid , format , site , args ] . join ( '&' ) . to_s ) end return Net :: HTTP . get ( uri ) end
This method is used for making the http calls building off the DSL of this module .
21,048
def digits_text ( digit_values , options = { } ) insignificant_digits = options [ :insignificant_digits ] || 0 num_digits = digit_values . reduce ( 0 ) { | num , digit | digit . nil? ? num : num + 1 } num_digits -= insignificant_digits digit_values . map { | d | if d . nil? options [ :separator ] else num_digits -= 1 if num_digits >= 0 digit_symbol ( d , options ) else options [ :insignificant_symbol ] end end } . join end
Convert sequence of digits to its text representation . The nil value can be used in the digits sequence to represent the group separator .
21,049
def width @width ||= list . map { | t | t . name_with_args ? t . name_with_args . length : 0 } . max || 10 end
Determine the max count of characters for all task names .
21,050
def print list . each do | entry | entry . headline ? print_headline ( entry ) : print_task_description ( entry ) end end
Print the current task list to console .
21,051
def wait ( timeout = nil ) @mutex . lock unless @set remaining = Condition :: Result . new ( timeout ) while ! @set && remaining . can_wait? remaining = @condition . wait ( @mutex , remaining . remaining_time ) end end @set ensure @mutex . unlock end
Wait a given number of seconds for the Event to be set by another thread . Will wait forever when no timeout value is given . Returns immediately if the Event has already been set .
21,052
def method_missing ( method_name , * arguments , & block ) arguments << block . to_lambda if block_given? reqeust = { object : self , method : method_name . to_s , arguments : arguments } begin return_value = @object_request_broker . call ( reqeust ) rescue ClosedObjectRequestBrokerError raise StaleObjectError end end
Makes a calls to the object on the remote endpoint .
21,053
def run_hook ( hook_name , * args ) list = self . class . all_hooks ( hook_name ) shell = self list . each do | hook | result = hook . call ( shell , * args ) return :break if result == :break end list . any? end
Runs a hook in the current shell instance .
21,054
def add_breadcrumb ( name , url = 'javascript:;' , atts = { } ) hash = { name : name , url : url , atts : atts } @breadcrumbs << hash end
add a breadcrumb to the breadcrumb hash
21,055
def authorize_demo if ! request . xhr? && ! request . get? && ( ! current_user . blank? && current_user . username . downcase == 'demo' && Setting . get ( 'demonstration_mode' ) == 'Y' ) redirect_to :back , flash : { error : I18n . t ( 'generic.demo_notification' ) } and return end render :inline => 'demo' and return if params [ :action ] == 'save_menu' && ! current_user . blank? && current_user . username . downcase == 'demo' && Setting . get ( 'demonstration_mode' ) == 'Y' end
restricts any CRUD functions if you are logged in as the username of demo and you have demonstration mode turned on
21,056
def mark_required ( object , attribute ) "*" if object . class . validators_on ( attribute ) . map ( & :class ) . include? ActiveModel :: Validations :: PresenceValidator end
Adds an asterix to the field if it is required .
21,057
def connect uri = URI . parse ( "https://userstream.twitter.com/2/user.json?track=#{@screen_name}" ) https = Net :: HTTP . new ( uri . host , uri . port ) https . use_ssl = true https . ca_file = @ca_file https . verify_mode = OpenSSL :: SSL :: VERIFY_PEER https . verify_depth = 5 https . start do | https | request = Net :: HTTP :: Get . new ( uri . request_uri , "User-Agent" => @user_agent , "Accept-Encoding" => "identity" ) request . oauth! ( https , @credential . consumer , @credential . access_token ) buf = "" https . request ( request ) do | response | response . read_body do | chunk | buf << chunk while ( ( line = buf [ / \r \n /m ] ) != nil ) begin buf . sub! ( line , "" ) line . strip! status = Yajl :: Parser . parse ( line ) rescue break end yield status end end end end end
Connects to UserStreaming API .
21,058
def fetch ( ) name = urlfy ( @name ) page = Net :: HTTP . get ( URI ( "http://www.gog.com/game/" + name ) ) data = JSON . parse ( page [ / / , 1 ] ) data end
Fetches raw data and parses as JSON object
21,059
def parse ( data ) game = GameItem . new ( get_title ( data ) , get_genres ( data ) , get_download_size ( data ) , get_release_date ( data ) , get_description ( data ) , get_price ( data ) , get_avg_rating ( data ) , get_avg_ratings_count ( data ) , get_platforms ( data ) , get_languages ( data ) , get_developer ( data ) , get_publisher ( data ) , get_modes ( data ) , get_bonus_content ( data ) , get_reviews ( data ) , get_pegi_age ( data ) ) game end
Parses raw data and returns game item .
21,060
def format_message_segment segment return segment . to_summary if segment . respond_to? ( :to_summary ) return segment if String === segment segment . inspect end
Construct a nicer error .
21,061
def to_s extended : nil message = super ( ) return message if extended == false if ( extended || add_extended_message? ) && ! extended_message . empty? message + "\n\n" + extended_message else message end end
Get the message or the extended message .
21,062
def inherited ( subclass ) subclass . _arguments = [ ] subclass . _description = '' subclass . _abstract = false subclass . _skip_options = false subclass . _exe_name = @_exe_name subclass . _default_priority = @_default_priority . to_f / 2 subclass . _priority = 0 super end
Trigger when a class inherit this class Rest class_attributes that should not be shared with subclass
21,063
def arguments ( args = nil ) return @_arguments if args . nil? @_arguments = [ ] [ * args ] . map ( & :split ) . flatten . each do | arg | @_arguments << Clin :: Argument . new ( arg ) end end
Set or get the arguments for the command
21,064
def verify ( ) send_bridge_request ( ) begin line = gets ( ) match = line . match ( %r{ \. } ) if ( ! match ) raise "HTTP BRIDGE error: bridge server sent incorrect reply to bridge request." end case code = match [ 1 ] . to_i when 100 , 101 return true when 401 raise "HTTP BRIDGE error #{code}: host key was invalid or missing, but required." when 503 , 504 raise "HTTP BRIDGE error #{code}: could not verify server can handle requests because it's overloaded." else raise "HTTP BRIDGE error #{code}: #{match[2]} unknown error connecting to bridge server." end ensure close ( ) end end
This just tries to determine if the server will honor requests as specified above so that the TCPServer initializer can error out early if it won t .
21,065
def setup ( ) send_bridge_request code = nil name = nil headers = [ ] while ( line = gets ( ) ) line = line . strip if ( line == "" ) case code . to_i when 100 code = name = nil headers = [ ] next when 101 write ( "HTTP/1.1 100 Continue\r\n\r\n" ) return self when 401 close ( ) raise "HTTP BRIDGE error #{code}: host key was invalid or missing, but required." when 503 , 504 close ( ) sleep_time = headers . find { | header | header [ "Retry-After" ] } || 5 raise RetryError . new ( "BRIDGE server timed out or is overloaded, wait #{sleep_time}s to try again." , sleep_time ) else raise "HTTP BRIDGE error #{code}: #{name} waiting for connection." end end if ( ! code && ! name ) if ( match = line . match ( %r{ \. } ) ) code = match [ 1 ] name = match [ 2 ] next else raise "Parse error in BRIDGE request reply." end else if ( match = line . match ( %r{ \s } ) ) headers . push ( { match [ 1 ] => match [ 2 ] } ) else raise "Parse error in BRIDGE request reply's headers." end end end return nil end
This does the full setup process on the request returning only when the connection is actually available .
21,066
def semantic_attributes_for ( record , options = { } , & block ) options [ :html ] ||= { } html_class = [ "attrtastic" , record . class . to_s . underscore , options [ :html ] [ :class ] ] . compact . join ( " " ) output = tag ( :div , { :class => html_class } , true ) if block_given? output << capture ( SemanticAttributesBuilder . new ( record , self ) , & block ) else output << capture ( SemanticAttributesBuilder . new ( record , self ) ) do | attr | attr . attributes end end output . safe_concat ( "</div>" ) end
Creates attributes for given object
21,067
def wait_for_reply ( user_id , timeout ) filter = "#{Java::org.hornetq.api.core::FilterConstants::HORNETQ_USERID} = 'ID:#{user_id}'" if user_id @session . consumer ( :queue_name => @reply_queue , :filter => filter ) do | consumer | consumer . receive ( timeout ) end end
Asynchronous wait for reply
21,068
def build_fields if @data . key? ( :fields ) @data [ :fields ] . each do | k , v | v [ :required ] = true unless v . key? ( :required ) end else { city : { label : 'City' , required : true } , region : { label : 'Province' , required : false } , postcode : { label : 'Post Code' , required : false } } end end
all fields are required by default unless otherwise stated
21,069
def page_url ( url ) define_method ( :page_url ) do | query_params = { } | uri = URI ( url ) existing_params = URI . decode_www_form ( uri . query || '' ) new_params = query_params . to_a unless existing_params . empty? && new_params . empty? combined_params = existing_params . push ( * new_params ) uri . query = URI . encode_www_form ( combined_params ) end uri . to_s end end
Defines an instance method page_url which returns the url passed to this method and takes optional query parameters that will be appended to the url if given .
21,070
def merge ( source , target ) return target if source . equal? ( target ) mas = @mergeable . call ( source ) unless mas . empty? then logger . debug { "Merging #{source.qp} #{mas.to_series} into #{target.qp}..." } end target . merge_attributes ( source ) target . merge_attributes ( source , mas , @matches , & @filter ) end
Merges the given source object into the target object .
21,071
def checkpoint_parameter_from_file ( node_type , parameter ) Bebox :: Node . checkpoint_parameter_from_file ( self . project_root , self . environment , self . hostname , node_type , parameter ) end
Get node checkpoint parameter from the yml file
21,072
def prepare started_at = DateTime . now . to_s prepare_deploy prepare_common_installation puppet_installation create_prepare_checkpoint ( started_at ) end
Prepare the configured nodes
21,073
def create_hiera_template options = { ssh_key : Bebox :: Project . public_ssh_key_from_file ( project_root , environment ) , project_name : Bebox :: Project . shortname_from_file ( project_root ) } Bebox :: Provision . generate_hiera_for_steps ( self . project_root , "node.yaml.erb" , self . hostname , options ) end
Create the puppet hiera template file
21,074
def create_node_checkpoint self . created_at = DateTime . now . to_s Bebox :: Environment . create_checkpoint_directories ( project_root , environment ) generate_file_from_template ( "#{Bebox::FilesHelper::templates_path}/node/node.yml.erb" , "#{project_root}/.checkpoints/environments/#{environment}/nodes/#{hostname}.yml" , { node : self } ) end
Create checkpoint for node
21,075
def define_fast_methods_for_model ( name , options ) join_table = options [ :join_table ] join_column_name = name . to_s . downcase . singularize define_method "fast_#{join_column_name}_ids_insert" do | * args | table_name = self . class . table_name . singularize insert = M2MFastInsert :: Base . new id , join_column_name , table_name , join_table , * args insert . fast_insert end end
Get necessary table and column information so we can define fast insertion methods
21,076
def execute graph = Digraph . new { | g | vertex_count . times do | i | vertex = g . add_vertex vertex_builder . call ( vertex , i ) if vertex_builder end edge_count . times do | i | source = g . ith_vertex ( Kernel . rand ( vertex_count ) ) target = g . ith_vertex ( Kernel . rand ( vertex_count ) ) edge = g . connect ( source , target ) edge_builder . call ( edge , i ) if edge_builder end } strip ? _strip ( graph ) : graph end
Creates an algorithm instance Executes the random generation
21,077
def kill return false unless hostname == Socket . gethostname begin Process . kill ( 'KILL' , pid ) self . state = "killed" self . save! rescue Errno :: ESRCH puts "pid #{pid} does not exist!" mark_dead end end
Kills the job if running Using PID
21,078
def running? logs = Log . where ( :file => file , :job_type => job_type , :state => "running" , :export_id => export_id , :hostname => hostname ) if logs . count > 0 logs . each do | log | begin Process . getpgid ( log . pid ) puts "still running #{log.file}" return true rescue Errno :: ESRCH log . mark_dead end end end return false end
Checks to see if the PID of the log is active or not
21,079
def register ( name , klass ) if valid_strategy? klass available_strategies [ name . to_sym ] = klass else fail exception_to_raise_for_invalid_strategy , "Registering #{klass} failed. It does not support \"#{class_must_have_methods.join('-, ')}\"-method" end end
Register a new comparator strategy
21,080
def assign_group_items ( name , items , raise_if_exists = false ) group = group_items ( name ) if items . kind_of? ( Array ) items = Set [ * items ] elsif ! items . kind_of? ( Set ) items = Set [ items ] end c_allocated = allocated . count c_group = group . count items . each do | item | utf8_item = item . encode ( "UTF-8" ) allocated . add ( utf8_item ) group . add ( utf8_item ) end if raise_if_exists raise unless group . count == c_group + items . count && allocated . count == c_allocated + items . count end replace_group ( name , group ) return items end
Assign one or more items to a group . This method is additive so multitemle calls will grow the group not replace it .
21,081
def remove_from_group ( name , items ) group = group_items ( name ) items . each do | item | utf8_item = item . encode ( "UTF-8" ) deallocate ( utf8_item ) group . delete ( utf8_item ) end replace_group ( name , group ) return items end
Remove the items from the group provided by name also deallocates them .
21,082
def decommission_group ( name ) group = group_items ( name ) group . each do | item | deallocate ( item ) end groups . delete ( name ) return name end
Remove a group and free its allocated item addresses .
21,083
def preload_keys ( amount = 12 ) keys = EncryptedStore :: ActiveRecord . preload_keys ( amount ) keys . each { | k | ( @_decrypted_keys ||= { } ) [ k . id ] = k . decrypted_key } end
Preloads the most recent amount keys .
21,084
def login ( user , password ) @user = user @password = password response = call_remote ( :login , [ :username , user , :password , password ] ) raise "Incorrect user name / password [#{response.fault}]" unless response . loginResponse result = response [ :loginResponse ] [ :result ] @session_id = result [ :sessionId ] init_server ( result [ :serverUrl ] ) response end
Log in to the server with a user name and password remembering the session ID returned to us by SalesForce .
21,085
def login_with_oauth result = @server . post @oauth [ :login_url ] , '' , { } case result when Net :: HTTPSuccess doc = REXML :: Document . new result . body @session_id = doc . elements [ '*/sessionId' ] . text server_url = doc . elements [ '*/serverUrl' ] . text init_server server_url return { :sessionId => @sessionId , :serverUrl => server_url } when Net :: HTTPUnauthorized raise 'Invalid OAuth tokens' else raise 'Unexpected error: #{response.inspect}' end end
Log in to the server with OAuth remembering the session ID returned to us by SalesForce .
21,086
def method_missing ( method , * args ) unless args . size == 1 && [ Hash , Array ] . include? ( args [ 0 ] . class ) raise 'Expected 1 Hash or Array argument' end call_remote method , args [ 0 ] end
Turns method calls on this object into remote SOAP calls .
21,087
def teardown unless options [ :quit ] . to_s . strip == '' self . ignore_io_error = true exec_ignore_code options [ :quit ] , command_timeout : 1 , timeout_error : false end end
Tears down the shell session .
21,088
def execute_multiple ( url , bodies ) response = Excon . post url , body : bodies . join ( "\r\n" ) , expects : 200 , connect_timeout : 15 response_lines = response . body . split ( "\n" ) . map ( & :strip ) errors = [ ] errors << parse_error ( response_lines ) until response_lines . empty? raise LightstreamerError if errors . size != bodies . size errors rescue Excon :: Error => error raise Errors :: ConnectionError , error . message end
Sends a POST request to the specified Lightstreamer URL that concatenates multiple individual POST request bodies into one to avoid sending lots of individual requests . The return value is an array with one entry per body and indicates the error state returned by the server for that body s request or nil if no error occurred .
21,089
def request_body ( query ) params = { } query . each do | key , value | next if value . nil? value = value . map ( & :to_s ) . join ( ' ' ) if value . is_a? Array params [ key ] = value end URI . encode_www_form params end
Returns the request body to send for a POST request with the given options .
21,090
def parse_error ( response_lines ) first_line = response_lines . shift return nil if first_line == 'OK' return Errors :: SyncError . new if first_line == 'SYNC ERROR' if first_line == 'ERROR' error_code = response_lines . shift LightstreamerError . build response_lines . shift , error_code else LightstreamerError . new first_line end end
Parses the next error from the given lines that were returned by a POST request . The consumed lines are removed from the passed array .
21,091
def add_exception description : nil , is_fatal : false is_fatal_int = is_fatal ? 1 : 0 @params = { t : "exception" , exd : description , exf : is_fatal_int } send_to_ga end
convert bool to integer
21,092
def child_url? ( url1 , url2 , api = nil , strict : false ) parent_url? ( url2 , url1 , api , strict : strict ) end
Returns true if the first URL is the child of the second URL
21,093
def linked_data ( uri , ld ) uri = linked_data_path ( uri ) return nil unless uri && ld ld . each { | u , data | return data if uri == linked_data_path ( u ) } nil end
Returns the data for a URI from a parsed linked data API response which may contain multiple objects
21,094
def linked_data_path ( uri ) URI . parse ( uri ) . path rescue URI :: InvalidComponentError , URI :: InvalidURIError nil end
Returns the path of a URI
21,095
def list_url? ( u = nil , parsed : nil ) return false if ( u . nil? || u . empty? ) && parsed . nil? parsed ||= parse_url ( u ) child_type = parsed [ :child_type ] parsed [ :type ] == 'lists' && ( child_type . nil? || child_type . empty? ) end
Returns true if a URL is a list URL false otherwise
21,096
def parent_url? ( url1 , url2 , api = nil , strict : false ) u1 = url_for_comparison ( url1 , api , parsed : true ) u2 = url_for_comparison ( url2 , api , parsed : true ) return false unless u1 [ :type ] == u2 [ :type ] && u1 [ :id ] == u2 [ :id ] return true unless strict u1 [ :child_type ] . nil? && ! u2 [ :child_type ] . nil? ? true : false end
Returns true if the first URL is the parent of the second URL
21,097
def url_for_comparison ( url , api = nil , parsed : false ) if url . is_a? ( MatchData ) && parsed url elsif parsed && url . respond_to? ( :parsed_url ) url . parsed_url elsif ! parsed && url . respond_to? ( url ) url . url else result = api . nil? ? url . to_s : api . canonical_url ( url . to_s ) parsed ? parse_url ( result ) : result end end
Returns a parsed or unparsed URL for comparison
21,098
def url_path filename = URI . parse ( url ) . path filename . slice! ( 0 ) filename . end_with? ( '.json' ) ? filename : "#{filename}.json" rescue URI :: InvalidComponentError , URI :: InvalidURIError nil end
Returns the path from the URL as a relative filename
21,099
def import_documentations require SwaggerDocsGenerator . file_base SwaggerDocsGenerator . file_docs . each { | rb | require rb } end
Import documentation file