idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
15,800
def check_stream ( io_stream ) yaml_data = io_stream . read error_array = [ ] valid = check_data ( yaml_data , error_array ) errors [ '' ] = error_array unless error_array . empty? valid end
Check an IO stream
15,801
def display_errors errors . each do | path , errors | puts path errors . each do | err | puts " #{err}" end end end
Output the lint errors
15,802
def check_filename ( filename ) extension = filename . split ( '.' ) . last return true if valid_extensions . include? ( extension ) false end
Check file extension
15,803
def check_data ( yaml_data , errors_array ) valid = check_not_empty? ( yaml_data , errors_array ) valid &&= check_syntax_valid? ( yaml_data , errors_array ) valid &&= check_overlapping_keys? ( yaml_data , errors_array ) valid end
Check the data in the file or stream
15,804
def check_not_empty? ( yaml_data , errors_array ) if yaml_data . empty? errors_array << 'The YAML should not be an empty string' false elsif yaml_data . strip . empty? errors_array << 'The YAML should not just be spaces' false else true end end
Check that the data is not empty
15,805
def check_syntax_valid? ( yaml_data , errors_array ) YAML . safe_load ( yaml_data ) true rescue YAML :: SyntaxError => e errors_array << e . message false end
Check that the data is valid YAML
15,806
def check_overlapping_keys? ( yaml_data , errors_array ) overlap_detector = KeyOverlapDetector . new data = Psych . parser . parse ( yaml_data ) overlap_detector . parse ( data ) overlap_detector . overlapping_keys . each do | key | err_meg = "The same key is defined more than once: #{key.join('.')}" errors_array << er...
Check if there is overlapping key
15,807
def uncolor ( string = nil ) if block_given? yield . to_str . gsub ( COLORED_REGEXP , '' ) elsif string . respond_to? ( :to_str ) string . to_str . gsub ( COLORED_REGEXP , '' ) elsif respond_to? ( :to_str ) to_str . gsub ( COLORED_REGEXP , '' ) else '' end . extend ( Term :: ANSIColor ) end
Returns an uncolored version of the string that is all ANSI - Attributes are stripped from the string .
15,808
def color ( name , string = nil , & block ) attribute = Attribute [ name ] or raise ArgumentError , "unknown attribute #{name.inspect}" result = '' result << "\e[#{attribute.code}m" if Term :: ANSIColor . coloring? if block_given? result << yield . to_s elsif string . respond_to? ( :to_str ) result << string . to_str e...
Return + string + or the result string of the given + block + colored with color + name + . If string isn t a string only the escape sequence to switch on the color + name + is returned .
15,809
def execute! files_to_check = parse_options . leftovers YamlLint . logger . level = Logger :: DEBUG if opts . debug no_yamls_to_check_msg = "Error: need at least one YAML file to check.\n" 'Try --help for help.' abort ( no_yamls_to_check_msg ) if files_to_check . empty? lint ( files_to_check ) end
setup CLI options Run the CLI command
15,810
def detect_version ( executable_path ) capture = ShellCapture . new ( version_command ( executable_path ) ) unless capture . command_found raise Cliver :: Dependency :: NotFound . new ( "Could not find an executable at given path '#{executable_path}'." + "If this path was not specified explicitly, it is probably a " + ...
Forgiving input allows either argument if only one supplied .
15,811
def render config = json_escape JSON . generate ( self . options ) if @timeSeriesSource config . gsub! '"__DataSource__"' , json_escape ( @timeSeriesSource ) end dataUrlFormat = self . jsonUrl? ? "json" : ( self . xmlUrl ? "xml" : nil ) template = File . read ( File . expand_path ( "../../../templates/chart.erb" , __FI...
Render the chart
15,812
def parse_options newOptions = nil @options . each do | key , value | if key . downcase . to_s . eql? "timeseries" @timeSeriesData = value . GetDataStore ( ) @timeSeriesSource = value . GetDataSource ( ) newOptions = { } newOptions [ 'dataSource' ] = "__DataSource__" @options . delete ( key ) end end if newOptions @opt...
Helper method that converts the constructor params into instance variables
15,813
def smooth_location_by_average ( opts = { } ) seconds_either_side = opts [ :averaging_window ] || 20 earliest = ( find_point_by_time_or_offset ( opts [ :start ] ) || @earliest_point ) . time latest = ( find_point_by_time_or_offset ( opts [ :end ] ) || @latest_point ) . time tmp_points = [ ] @points . each do | point | ...
smooths the location data in the segment ( by recalculating the location as an average of 20 neighbouring points . Useful for removing noise from GPS traces .
15,814
def crop ( area ) reset_meta_data keep_tracks = [ ] tracks . each do | trk | trk . crop ( area ) unless trk . empty? update_meta_data ( trk ) keep_tracks << trk end end @tracks = keep_tracks routes . each { | rte | rte . crop ( area ) } waypoints . each { | wpt | wpt . crop ( area ) } end
Crops any points falling within a rectangular area . Identical to the delete_area method in every respect except that the points outside of the given area are deleted . Note that this method automatically causes the meta data to be updated after deletion .
15,815
def calculate_duration @duration = 0 if @tracks . nil? || @tracks . size . zero? || @tracks [ 0 ] . segments . nil? || @tracks [ 0 ] . segments . size . zero? return @duration end @duration = ( @tracks [ - 1 ] . segments [ - 1 ] . points [ - 1 ] . time - @tracks . first . segments . first . points . first . time ) resc...
Calculates and sets the duration attribute by subtracting the time on the very first point from the time on the very last point .
15,816
def contains? ( pt ) ( ( pt . lat >= min_lat ) && ( pt . lat <= max_lat ) && ( pt . lon >= min_lon ) && ( pt . lon <= max_lon ) ) end
Returns true if the pt is within these bounds .
15,817
def contains_time? ( time ) segments . each do | seg | return true if seg . contains_time? ( time ) end false end
Returns true if the given time occurs within any of the segments of this track .
15,818
def delete_area ( area ) reset_meta_data segments . each do | seg | seg . delete_area ( area ) update_meta_data ( seg ) unless seg . empty? end segments . delete_if ( & :empty? ) end
Deletes all points within a given area and updates the meta data .
15,819
def work ( interval = 5.0 ) interval = Float ( interval ) $0 = "resque-delayed: harvesting" startup loop do break if shutdown? while job = Resque :: Delayed . next do log "got: #{job.inspect}" queue , klass , * args = job Resque :: Job . create ( queue , klass , * args ) end break if interval . zero? log! "Sleeping for...
Can be passed a float representing the polling frequency . The default is 5 seconds but for a semi - active site you may want to use a smaller value .
15,820
def log ( message ) if verbose puts "*** #{message}" elsif very_verbose time = Time . now . strftime ( '%H:%M:%S %Y-%m-%d' ) puts "** [#{time}] #$$: #{message}" end end
Log a message to STDOUT if we are verbose or very_verbose .
15,821
def custom_caps ( text ) text . gsub ( %r{ \s \d \. \# \d \. \w }x ) do | str | tag , before , caps = $1 , $2 , $3 if tag || caps =~ / \d \. / str elsif $3 =~ / \d \. / before + caps else before + '<span class="caps">' + caps + '</span>' end end end
custom modules to jekyll - typogrify surrounds two or more consecutive capital letters perhaps with interspersed digits and periods in a span with a styled class .
15,822
def join_recursive ( join_options = { } , & block ) raise ArgumentError , 'block expected' unless block_given? query = Query . new ( klass ) if block . arity == 0 query . instance_eval ( & block ) else block . call ( query ) end query . join_to ( self , join_options ) end
Performs a join to recursive subquery which should be built within a block .
15,823
def audit_tag_with ( tag ) if audit = last_audit audit . update_attribute ( :tag , tag ) audits . reload if self . class . audited_version else self . audit_tag = tag snap! end end
Mark the latest record with a tag in order to easily find and perform diff against later If there are no audits for this record create a new audit with this tag
15,824
def snap serialize_attribute = lambda do | attribute | if attribute . is_a? Proc elsif attribute . class . ancestors . include? ( ActiveRecord :: Base ) attribute . serializable_hash elsif attribute . is_a? ( Array ) || attribute . is_a? ( ActiveRecord :: Associations :: CollectionProxy ) attribute . map { | element | ...
Take a snapshot of the current state of the audited record s audited attributes
15,825
def snap! ( options = { } ) data = options . merge ( :modifications => self . snap ) data [ :tag ] = self . audit_tag if self . audit_tag data [ :action ] = self . audit_action if self . audit_action data [ :changed_by ] = self . audit_changed_by if self . audit_changed_by self . save_audit ( data ) end
Take a snapshot of and save the current state of the audited record s audited attributes
15,826
def last_change_of ( attribute ) raise "#{attribute} is not audited for model #{self.class}. Audited attributes: #{self.class.audited_attributes}" unless self . class . audited_attributes . include? attribute . to_sym attribute = attribute . to_s last = audits . size - 1 last . downto ( 1 ) do | i | if audits [ i ] . m...
Return last attribute s change
15,827
def diff ( other_audit ) other_modifications = other_audit ? other_audit . modifications : { } { } . tap do | d | ( self . modifications . keys - other_modifications . keys ) . each do | k | d [ k ] = [ nil , self . modifications [ k ] ] if self . modifications [ k ] end ( other_modifications . keys - self . modificati...
Diffing two audits modifications
15,828
def diff_since ( time ) other_audit = auditable . audits . where ( "created_at <= ? AND id != ?" , time , id ) . order ( "id DESC" ) . limit ( 1 ) . first diff ( other_audit ) end
Diff this audit with the latest audit created before the time variable passed
15,829
def diff_since_version ( version ) other_audit = auditable . audits . where ( "version <= ? AND id != ?" , version , id ) . order ( "version DESC" ) . limit ( 1 ) . first diff ( other_audit ) end
Diff this audit with the latest audit created before this version
15,830
def tag h h2 = h . dup [ :show_help , :skip_header , :verbose , :quiet , :debug ] . each { | key | h2 . delete ( key ) } info = h2 . map { | k , v | k . to_s . capitalize + '=' + '"' + v . to_s + '"' } . join ( ',' ) line = '##BioVcf=<' + info + '>' @lines . insert ( - 2 , line ) line end
Push a special key value list to the header
15,831
def method_missing ( m , * args , & block ) name = m . to_s if name =~ / \? / @sample_index ||= @header . sample_index return ! VcfSample :: empty? ( @fields [ @sample_index [ name . chop ] ] ) else sample [ name ] end end
Return the sample
15,832
def each return enum_for ( :each ) unless block_given? io = nil if @is_gz infile = open ( @file ) io = Zlib :: GzipReader . new ( infile ) else io = File . open ( @file ) end header = BioVcf :: VcfHeader . new io . each_line do | line | line . chomp! if line =~ / / header . add ( line ) next end if line =~ / / header ....
Returns an enum that can be used as an iterator .
15,833
def method_missing ( m , * args , & block ) return nil if @is_empty if m =~ / \? / v = values [ fetch ( m . to_s . upcase . chop ) ] return ( not VcfValue :: empty? ( v ) ) else v = values [ fetch ( m . to_s . upcase ) ] return nil if VcfValue :: empty? ( v ) v = v . to_i if v =~ / \d / v = v . to_f if v =~ / \d \. \d ...
Returns the value of a field
15,834
def ilist name v = fetch_value ( name ) return nil if not v v . split ( ',' ) . map { | i | i . to_i } end
Return an integer list
15,835
def be_json ( expected = Saharspec :: Matchers :: BeJson :: NONE ) Saharspec :: Matchers :: BeJson . new ( expected ) end
be_json checks if provided value is JSON and optionally checks it contents .
15,836
def flash_to_headers if response . xhr? && growlyhash ( true ) . size > 0 response . headers [ 'X-Message' ] = URI . escape ( growlyhash . to_json ) growlyhash . each_key { | k | flash . discard ( k ) } end end
Dumps available messages to headers and discards them to prevent appear it again after refreshing a page
15,837
def growlyflash_static_notices ( js_var = 'window.flashes' ) return if flash . empty? script = "#{js_var} = #{growlyhash.to_json.html_safe};" . freeze view_context . javascript_tag ( script , defer : 'defer' ) end
View helper method which renders flash messages to js variable if they weren t dumped to headers with XHR request
15,838
def growlyhash ( force = false ) @growlyhash = nil if force @growlyhash ||= flash . to_hash . select { | k , v | v . is_a? String } end
Hash with available growl flash messages which contains a string object .
15,839
def protokoll ( column , _options = { } ) options = { :pattern => "%Y%m#####" , :number_symbol => "#" , :column => column , :start => 0 , :scope_by => nil } options . merge! ( _options ) raise ArgumentError . new ( "pattern can't be nil!" ) if options [ :pattern ] . nil? raise ArgumentError . new ( "pattern requires at...
Class method available in models
15,840
def lex ( input ) @input = input return enum_for ( :lex , input ) unless block_given? if debug logger . info "lex: tokens = #{@dsl.lex_tokens}" logger . info "lex: states = #{@dsl.state_info}" logger . info "lex: ignore = #{@dsl.state_ignore}" logger . info "lex: error = #{@dsl.state_error}" end stream_tokens ...
Tokenizes input and returns all tokens
15,841
def stream_tokens ( input , & block ) scanner = StringScanner . new ( input ) while ! scanner . eos? current_char = scanner . peek ( 1 ) if @dsl . state_ignore [ current_state ] . include? ( current_char ) scanner . pos += current_char . size @char_pos_in_line += current_char . size next end if debug logger . info "lex...
Advances through input and streams tokens
15,842
def add_order ( opts = { } ) required_opts = %w{ pair type ordertype volume } leftover = required_opts - opts . keys . map ( & :to_s ) if leftover . length > 0 raise ArgumentError . new ( "Required options, not given. Input must include #{leftover}" ) end post_private 'AddOrder' , opts end
Private User Trading
15,843
def render_nokogiri unless defined? Nokogiri raise ArgumentError , "Nokogiri not found!" end builder = Nokogiri :: XML :: Builder . new ( :encoding => "UTF-8" ) do | xml | xml . urlset ( XmlSitemap :: MAP_SCHEMA_OPTIONS ) { | s | @items . each do | item | s . url do | u | u . loc item . target if item . image_location ...
Render with Nokogiri gem
15,844
def render_string result = '<?xml version="1.0" encoding="UTF-8"?>' + "\n<urlset" XmlSitemap :: MAP_SCHEMA_OPTIONS . each do | key , val | result << ' ' + key + '="' + val + '"' end result << ">\n" item_results = [ ] @items . each do | item | item_string = " <url>\n" item_string << " <loc>#{CGI::escapeHTML(item.tar...
Render with plain strings
15,845
def find_resource ( resource , options = { } ) resource = resource . to_s scope , query = resource_scope_and_query ( resource , options ) through = options [ :through ] ? options [ :through ] . to_s : nil assoc = through || ( options [ :from ] ? resource . pluralize : nil ) scope = scope . send ( assoc ) if assoc && sc...
Internal find_resource instance method
15,846
def authorize ( required = nil , options ) if through = options [ :through ] name = through . to_s . singularize . to_sym else name = options [ :resource ] end record = instance_variable_get ( "@#{name}" ) if record . nil? record = send ( "current_#{name}" ) send "authenticate_#{name}!" end role_attr = record . class ....
Internal authorize instance method
15,847
def add ( map , use_offsets = true ) raise ArgumentError , 'XmlSitemap::Map object required!' unless map . kind_of? ( XmlSitemap :: Map ) raise ArgumentError , 'Map is empty!' if map . empty? @maps << { :loc => use_offsets ? map . index_url ( @offsets [ map . group ] , @secure ) : map . plain_index_url ( @secure ) , :l...
Initialize a new Index instance
15,848
def render xml = Builder :: XmlMarkup . new ( :indent => 2 ) xml . instruct! ( :xml , :version => '1.0' , :encoding => 'UTF-8' ) xml . sitemapindex ( XmlSitemap :: INDEX_SCHEMA_OPTIONS ) { | s | @maps . each do | item | s . sitemap do | m | m . loc item [ :loc ] m . lastmod item [ :lastmod ] end end } . to_s end
Generate sitemap XML index
15,849
def render_to ( path , options = { } ) overwrite = options [ :overwrite ] || true path = File . expand_path ( path ) if File . exists? ( path ) && ! overwrite raise RuntimeError , "File already exists and not overwritable!" end File . open ( path , 'w' ) { | f | f . write ( self . render ) } end
Render XML sitemap index into the file
15,850
def add ( target , opts = { } ) raise RuntimeError , 'Only up to 50k records allowed!' if @items . size > 50000 raise ArgumentError , 'Target required!' if target . nil? raise ArgumentError , 'Target is empty!' if target . to_s . strip . empty? url = process_target ( target ) if url . length > 2048 raise ArgumentError ...
Initializa a new Map instance
15,851
def render_to ( path , options = { } ) overwrite = options [ :overwrite ] == true || true compress = options [ :gzip ] == true || false path = File . expand_path ( path ) path << ".gz" unless path =~ / \. \z /i if compress if File . exists? ( path ) && ! overwrite raise RuntimeError , "File already exists and not overw...
Render XML sitemap into the file
15,852
def process_target ( str ) if @root == true url ( str =~ / \/ / ? str : "/#{str}" ) else str =~ / /i ? str : url ( str =~ / \/ / ? str : "/#{str}" ) end end
Process target path or url
15,853
def validate_tokens ( lexer ) if lexer . lex_tokens . empty? complain ( "No token list defined" ) end if ! lexer . lex_tokens . respond_to? ( :to_ary ) complain ( "Tokens must be a list or enumerable" ) end terminals = [ ] lexer . lex_tokens . each do | token | if ! identifier? ( token ) complain ( "Bad token name `#{t...
Validate provided tokens
15,854
def validate_states ( lexer ) if ! lexer . state_info . respond_to? ( :each_pair ) complain ( "States must be defined as a hash" ) end lexer . state_info . each do | state_name , state_type | if ! [ :inclusive , :exclusive ] . include? ( state_type ) complain ( "State type for state #{state_name}" " must be :inclusive ...
Validate provided state names
15,855
def body = ( value ) value = [ ] if ! value || value == '' super ( value . respond_to? ( :each ) ? value : [ value . to_s ] ) end
Automatically wraps the assigned value in an array if it doesn t respond to each . Also filters out non - true values and empty strings .
15,856
def finish ( * args , & block ) self [ 'Content-Type' ] ||= 'text/html;charset=utf-8' @block = block if block if [ 204 , 205 , 304 ] . include? ( status . to_i ) header . delete "Content-Type" header . delete "Content-Length" close [ status . to_i , header , [ ] ] else [ status . to_i , header , body ] end end
Override finish to avoid using BodyProxy
15,857
def try_matches eligable_matches . each do | match , idx | request . breadcrumb << match catch ( :pass ) { dispatch ( match ) return true } request . breadcrumb . pop end response . status = ( ! matches . empty? && eligable_matches . empty? ) ? 403 : 404 end
Tries to dispatch to each eligable match . If the first match _passes_ tries the second match and so on . If there are no eligable matches or all eligable matches pass an appropriate 4xx response status is set .
15,858
def dispatch ( match ) @_dispatched = true target = match . mapping [ :target ] response . merge! begin if Proc === target instance_exec ( & target ) else target . call ( env . merge ( 'SCRIPT_NAME' => request . matched_path . chomp ( '/' ) , 'PATH_INFO' => request . unmatched_path [ match . path . chomp ( '/' ) . leng...
Dispatches the request to the matched target . Overriding this method provides the opportunity for one to have more control over how mapping targets are invoked .
15,859
def matches @_matches ||= begin to_match = request . unmatched_path to_match = to_match . chomp ( '/' ) if config [ :strip_trailing_slash ] == :ignore && to_match =~ %r{ } mappings . map { | mapping | mapping [ :pattern ] . match ( to_match ) do | match_data | if match_data . pre_match == '' if match_data . names . emp...
Finds mappings that match the unmatched portion of the request path returning an array of Match objects or an empty array if no matches were found .
15,860
def eligable_matches @_eligable_matches ||= begin matches . select { | m | m . failed_condition . nil? } . each_with_index . sort_by do | m , idx | priority = m . mapping [ :priority ] || 0 media_type_rank = [ * m . mapping [ :conditions ] [ :media_type ] ] . map { | type | env [ 'scorched.accept' ] [ :accept ] . rank ...
Returns an ordered list of eligable matches . Orders matches based on media_type ensuring priority and definition order are respected appropriately . Sorts by mapping priority first media type appropriateness second and definition order third .
15,861
def check_for_failed_condition ( conds ) failed = ( conds || [ ] ) . find { | c , v | ! check_condition? ( c , v ) } if failed failed [ 0 ] = failed [ 0 ] [ 0 .. - 2 ] . to_sym if failed [ 0 ] [ - 1 ] == '!' end failed end
Tests the given conditions returning the name of the first failed condition or nil otherwise .
15,862
def check_condition? ( c , v ) c = c [ 0 .. - 2 ] . to_sym if invert = ( c [ - 1 ] == '!' ) raise Error , "The condition `#{c}` either does not exist, or is not an instance of Proc" unless Proc === self . conditions [ c ] retval = instance_exec ( v , & self . conditions [ c ] ) invert ? ! retval : ! ! retval end
Test the given condition returning true if the condition passes or false otherwise .
15,863
def redirect ( url , status : ( env [ 'HTTP_VERSION' ] == 'HTTP/1.1' ) ? 303 : 302 , halt : true ) response [ 'Location' ] = absolute ( url ) response . status = status self . halt if halt end
Redirects to the specified path or URL . An optional HTTP status is also accepted .
15,864
def flash ( key = :flash ) raise Error , "Flash session data cannot be used without a valid Rack session" unless session flash_hash = env [ 'scorched.flash' ] ||= { } flash_hash [ key ] ||= { } session [ key ] ||= { } unless session [ key ] . methods ( false ) . include? :[]= session [ key ] . define_singleton_method (...
Flash session storage helper . Stores session data until the next time this method is called with the same arguments at which point it s reset . The typical use case is to provide feedback to the user on the previous action they performed .
15,865
def run_filters ( type ) halted = false tracker = env [ 'scorched.executed_filters' ] ||= { before : Set . new , after : Set . new } filters [ type ] . reject { | f | tracker [ type ] . include? ( f ) } . each do | f | unless check_for_failed_condition ( f [ :conditions ] ) || ( halted && ! f [ :force ] ) tracker [ typ...
Returns false if any of the filters halted the request . True otherwise .
15,866
def unescaped_path path_info . split ( / /i ) . each_slice ( 2 ) . map { | v , m | URI . unescape ( v ) << ( m || '' ) } . join ( '' ) end
The unescaped URL excluding the escaped forward - slash and percent . The resulting string will always be safe to unescape again in situations where the forward - slash or percent are expected and valid characters .
15,867
def reboot! ( reboot_technique = :default_reboot ) case reboot_technique when :default_reboot self . service . rebootDefault when :os_reboot self . service . rebootSoft when :power_cycle self . service . rebootHard else raise ArgumentError , "Unrecognized reboot technique in SoftLayer::Server#reboot!}" end end
Construct a server from the given client using the network data found in + network_hash +
15,868
def notes = ( new_notes ) raise ArgumentError , "The new notes cannot be nil" unless new_notes edit_template = { "notes" => new_notes } self . service . editObject ( edit_template ) self . refresh_details ( ) end
Change the notes of the server raises ArgumentError if you pass nil as the notes
15,869
def set_hostname! ( new_hostname ) raise ArgumentError , "The new hostname cannot be nil" unless new_hostname raise ArgumentError , "The new hostname cannot be empty" if new_hostname . empty? edit_template = { "hostname" => new_hostname } self . service . editObject ( edit_template ) self . refresh_details ( ) end
Change the hostname of this server Raises an ArgumentError if the new hostname is nil or empty
15,870
def set_domain! ( new_domain ) raise ArgumentError , "The new hostname cannot be nil" unless new_domain raise ArgumentError , "The new hostname cannot be empty" if new_domain . empty? edit_template = { "domain" => new_domain } self . service . editObject ( edit_template ) self . refresh_details ( ) end
Change the domain of this server
15,871
def change_port_speed ( new_speed , public = true ) if public self . service . setPublicNetworkInterfaceSpeed ( new_speed ) else self . service . setPrivateNetworkInterfaceSpeed ( new_speed ) end self . refresh_details ( ) self end
Change the current port speed of the server
15,872
def reload_os! ( token = '' , provisioning_script_uri = nil , ssh_keys = nil ) configuration = { } configuration [ 'customProvisionScriptUri' ] = provisioning_script_uri if provisioning_script_uri configuration [ 'sshKeyIds' ] = ssh_keys if ssh_keys self . service . reloadOperatingSystem ( token , configuration ) end
Begins an OS reload on this server .
15,873
def parse self . result ||= Payload . new . tap do | payload | PayloadRepresenter . new ( payload ) . from_json ( input ) end rescue MultiJson :: ParseError raise InvalidJsonError end
Initialize the plugin parser
15,874
def object_filter ( filter ) raise ArgumentError , "object_filter expects an instance of SoftLayer::ObjectFilter" if filter . nil? || ! filter . kind_of? ( SoftLayer :: ObjectFilter ) APIParameterFilter . new ( self . target , @parameters . merge ( { :object_filter => filter } ) ) ; end
Adds an object_filter to the result . An Object Filter allows you to specify criteria which are used to filter the results returned by the server .
15,875
def verify ( ) if has_order_items? order_template = order_object order_template = yield order_object if block_given? @virtual_server . softlayer_client [ :Product_Order ] . verifyOrder ( order_template ) end end
Create an upgrade order for the virtual server provided .
15,876
def place_order! ( ) if has_order_items? order_template = order_object order_template = yield order_object if block_given? @virtual_server . softlayer_client [ :Product_Order ] . placeOrder ( order_template ) end end
Places the order represented by this object . This is likely to involve a change to the charges on an account .
15,877
def _item_prices_in_category ( which_category ) @virtual_server . upgrade_options . select { | item_price | item_price [ 'categories' ] . find { | category | category [ 'categoryCode' ] == which_category } } end
Returns a list of the update item prices in the given category for the server
15,878
def _item_price_with_capacity ( which_category , capacity ) _item_prices_in_category ( which_category ) . find { | item_price | item_price [ 'item' ] [ 'capacity' ] . to_i == capacity } end
Searches through the upgrade items prices known to this server for the one that is in a particular category and whose capacity matches the value given . Returns the item_price or nil
15,879
def order_object prices = [ ] cores_price_item = @cores ? _item_price_with_capacity ( "guest_core" , @cores ) : nil ram_price_item = @ram ? _item_price_with_capacity ( "ram" , @ram ) : nil max_port_speed_price_item = @max_port_speed ? _item_price_with_capacity ( "port_speed" , @max_port_speed ) : nil prices << { "id" =...
construct an order object
15,880
def assign_credential ( username ) raise ArgumentError , "The username cannot be nil" unless username raise ArgumentError , "The username cannot be empty" if username . empty? self . service . assignCredential ( username . to_s ) @credentials = nil end
Assign an existing network storage credential specified by the username to the network storage instance
15,881
def password = ( password ) raise ArgumentError , "The new password cannot be nil" unless password raise ArgumentError , "The new password cannot be empty" if password . empty? self . service . editObject ( { "password" => password . to_s } ) self . refresh_details ( ) end
Updates the password for the network storage instance .
15,882
def remove_credential ( username ) raise ArgumentError , "The username cannot be nil" unless username raise ArgumentError , "The username cannot be empty" if username . empty? self . service . removeCredential ( username . to_s ) @credentials = nil end
Remove an existing network storage credential specified by the username from the network storage instance
15,883
def softlayer_properties ( object_mask = nil ) my_service = self . service if ( object_mask ) my_service = my_service . object_mask ( object_mask ) else my_service = my_service . object_mask ( self . class . default_object_mask ) end my_service . getObject ( ) end
Make an API request to SoftLayer and return the latest properties hash for this object .
15,884
def update_credential_password ( username , password ) raise ArgumentError , "The new password cannot be nil" unless password raise ArgumentError , "The new username cannot be nil" unless username raise ArgumentError , "The new password cannot be empty" if password . empty? raise ArgumentError , "The new username canno...
Updates the password for the network storage credential of the username specified .
15,885
def items_with_description ( expected_description ) filter = ObjectFilter . new { | filter | filter . accept ( "items.description" ) . when_it is ( expected_description ) } items_data = self . service . object_filter ( filter ) . getItems ( ) items_data . collect do | item_data | first_price = item_data [ 'prices' ] [ ...
Returns the package items with the given description Currently this is returning the low - level hash representation directly from the Network API
15,886
def available_datacenters datacenters_data = self . service . getStorageLocations ( ) datacenters_data . collect { | datacenter_data | SoftLayer :: Datacenter . datacenter_named ( datacenter_data [ 'name' ] ) } end
Returns an array of the datacenters that this image can be stored in . This is the set of datacenters that you may choose from when putting together a list you will send to the datacenters = setter .
15,887
def shared_with_accounts = ( account_id_list ) already_sharing_with = self . shared_with_accounts accounts_to_add = account_id_list . select { | account_id | ! already_sharing_with . include? ( account_id ) } my_account_id = self [ 'accountId' ] accounts_to_add . push ( my_account_id ) if ! already_sharing_with . inclu...
Change the set of accounts that this image is shared with . The parameter is an array of account ID s .
15,888
def wait_until_ready ( max_trials , seconds_between_tries = 2 ) num_trials = 0 begin self . refresh_details ( ) parent_ready = ! ( has_sl_property? :transactionId ) || ( self [ :transactionId ] == "" ) children_ready = ( nil == self [ 'children' ] . find { | child | child [ 'transactionId' ] != "" } ) ready = parent_re...
Repeatedly poll the network API until transactions related to this image template are finished
15,889
def verify ( ) order_template = firewall_order_template order_template = yield order_template if block_given? server . softlayer_client [ :Product_Order ] . verifyOrder ( order_template ) end
Create a new order for the given server
15,890
def cancel! ( notes = nil ) user = self . softlayer_client [ :Account ] . object_mask ( "mask[id,account.id]" ) . getCurrentUser notes = "Cancelled by a call to #{__method__} in the softlayer_api gem" if notes == nil || notes == "" cancellation_request = { 'accountId' => user [ 'account' ] [ 'id' ] , 'userId' => user [...
Cancel the firewall
15,891
def change_rules_bypass! ( bypass_symbol ) change_object = { "firewallContextAccessControlListId" => rules_ACL_id ( ) , "rules" => self . rules } case bypass_symbol when :apply_firewall_rules change_object [ 'bypassFlag' ] = false self . softlayer_client [ :Network_Firewall_Update_Request ] . createObject ( change_obje...
This method asks the firewall to ignore its rule set and pass all traffic through the firewall . Compare the behavior of this routine with change_routing_bypass!
15,892
def change_routing_bypass! ( routing_symbol ) vlan_firewall_id = self [ 'networkVlanFirewall' ] [ 'id' ] raise "Could not identify the device for a VLAN firewall" if ! vlan_firewall_id case routing_symbol when :route_through_firewall self . softlayer_client [ :Network_Vlan_Firewall ] . object_with_id ( vlan_firewall_id...
This method allows you to route traffic around the firewall and directly to the servers it protects . Compare the behavior of this routine with change_rules_bypass!
15,893
def rules_ACL_id outside_interface_data = self [ 'firewallInterfaces' ] . find { | interface_data | interface_data [ 'name' ] == 'outside' } incoming_ACL = outside_interface_data [ 'firewallContextAccessControlLists' ] . find { | firewallACL_data | firewallACL_data [ 'direction' ] == 'in' } if outside_interface_data if...
Searches the set of access control lists for the firewall device in order to locate the one that sits on the outside side of the network and handles in coming traffic .
15,894
def place_order! ( ) order_template = virtual_guest_template order_template = yield order_template if block_given? virtual_server_hash = @softlayer_client [ :Virtual_Guest ] . createObject ( order_template ) SoftLayer :: VirtualServer . server_with_id ( virtual_server_hash [ 'id' ] , :client => @softlayer_client ) if v...
Calls the SoftLayer API to place an order for a new virtual server based on the template in this order . If this succeeds then you will be billed for the new Virtual Server .
15,895
def delete_user_password! ( username ) user_password = self . passwords . select { | sw_pw | sw_pw . username == username . to_s } unless user_password . empty? softlayer_client [ :Software_Component_Password ] . object_with_id ( user_password . first [ 'id' ] ) . deleteObject @passwords = nil end end
Deletes specified username password from current software instance
15,896
def print_todos_table find_todos if @todos . nil? return if @todos . empty? markdown ( "#### Todos left in files" ) @todos . group_by ( & :file ) . each { | file , todos | print_todos_per_file ( file , todos ) } end
Adds a list of offending files to the danger comment
15,897
def virtual_server_order product_order = { 'packageId' => @package . id , 'useHourlyPricing' => ! ! @hourly , 'virtualGuests' => [ { 'domain' => @domain , 'hostname' => @hostname } ] } product_order [ 'imageTemplateGlobalIdentifier' ] = @image_template . global_id if @image_template product_order [ 'location' ] = @data...
Construct and return a hash representing a + SoftLayer_Container_Product_Order_Virtual_Guest + based on the configuration options given .
15,898
def capture_image ( image_name , include_attached_storage = false , image_notes = '' ) image_notes = '' if ! image_notes image_name = 'Captured Image' if ! image_name disk_filter = lambda { | disk | disk [ 'device' ] == '0' } disk_filter = lambda { | disk | disk [ 'device' ] != '1' } if include_attached_storage disks =...
Capture a disk image of this virtual server for use with other servers .
15,899
def wait_until_ready ( max_trials , wait_for_transactions = false , seconds_between_tries = 2 ) num_trials = 0 begin self . refresh_details ( ) has_os_reload = has_sl_property? :lastOperatingSystemReload has_active_transaction = has_sl_property? :activeTransaction reloading_os = has_active_transaction && has_os_reload ...
Repeatedly polls the API to find out if this server is ready .