idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
12,100
def encode_pixels ( pixels , stream = @stream ) raise ArgumentError , "Expected Array, got #{pixels.class}." unless pixels . is_a? ( Array ) bin = false bit_depth_element = self [ '0028,0100' ] pixel_representation_element = self [ '0028,0103' ] if bit_depth_element and pixel_representation_element template = template_...
Packs a pixel value array to a binary pixel string . The encoding is performed using values defined in the image related elements of the DObject instance .
12,101
def images ( options = { } ) images = Array . new if exists? ( PIXEL_TAG ) strings = image_strings ( split_to_frames = true ) strings = [ strings [ options [ :frame ] ] ] if options [ :frame ] if compression? if [ TXS_RLE ] . include? ( transfer_syntax ) pixel_frames = Array . new strings . each { | string | pixel_fram...
Extracts an array of image objects created from the encoded pixel data using the image related elements in the DICOM object .
12,102
def image_to_file ( file ) raise ArgumentError , "Expected #{String}, got #{file.class}." unless file . is_a? ( String ) parts = file . split ( '.' ) if parts . length > 1 base = parts [ 0 .. - 2 ] . join extension = '.' + parts . last else base = file extension = '' end images = image_strings images . each_index do | ...
Dumps the binary content of the Pixel Data element to the specified file .
12,103
def pixels ( options = { } ) pixels = nil if exists? ( PIXEL_TAG ) if compression? pixels = decompress ( image_strings . first ) else pixels = decode_pixels ( image_strings . first ) end if pixels if options [ :remap ] or options [ :level ] if options [ :narray ] pixels = process_presentation_values_narray ( pixels , -...
Extracts the Pixel Data values in an ordinary Ruby Array . Returns nil if no pixel data is present and false if it fails to retrieve pixel data which is present .
12,104
def decode_rle ( cols , rows , string ) pixels = Array . new header = string [ 0 ... 64 ] . unpack ( 'L*' ) image_segments = Array . new header . each_index do | n | if n == 0 elsif n == header [ 0 ] image_segments << [ header [ n ] , - 1 ] break else image_segments << [ header [ n ] , header [ n + 1 ] - 1 ] end end im...
Performs a run length decoding on the input stream .
12,105
def process_presentation_values ( pixel_data , min_allowed , max_allowed , level = nil ) center , width , intercept , slope = window_level_values if level if level . is_a? ( Array ) center = level [ 0 ] width = level [ 1 ] end else center , width = false , false end if intercept != 0 or slope != 1 pixel_data . collect!...
Converts original pixel data values to presentation values .
12,106
def process_presentation_values_narray ( pixel_data , min_allowed , max_allowed , level = nil ) center , width , intercept , slope = window_level_values if level if level . is_a? ( Array ) center = level [ 0 ] width = level [ 1 ] end else center , width = false , false end if pixel_data . is_a? ( Array ) n_arr = Numo :...
Converts original pixel data values to presentation values using the efficient NArray library .
12,107
def read_image ( pixel_data , columns , rows , options = { } ) raise ArgumentError , "Expected Array for pixel_data, got #{pixel_data.class}" unless pixel_data . is_a? ( Array ) raise ArgumentError , "Expected Integer for columns, got #{columns.class}" unless columns . is_a? ( Integer ) raise ArgumentError , "Expected ...
Creates an image object from the specified pixel value array performing presentation value processing if requested .
12,108
def window_level_values center = ( self [ '0028,1050' ] . is_a? ( Element ) == true ? self [ '0028,1050' ] . value . to_i : nil ) width = ( self [ '0028,1051' ] . is_a? ( Element ) == true ? self [ '0028,1051' ] . value . to_i : nil ) intercept = ( self [ '0028,1052' ] . is_a? ( Element ) == true ? self [ '0028,1052' ]...
Collects the window level values needed to convert the original pixel values to presentation values .
12,109
def write_pixels ( bin ) if self . exists? ( PIXEL_TAG ) self [ PIXEL_TAG ] . bin = bin else pixel_element = Element . new ( PIXEL_TAG , bin , :encoded => true , :parent => self ) end end
Transfers a pre - encoded binary string to the pixel data element either by overwriting the existing element value or creating a new Pixel Data element .
12,110
def parse ( bin , syntax , switched = false , explicit = true ) raise ArgumentError , "Invalid argument 'bin'. Expected String, got #{bin.class}." unless bin . is_a? ( String ) raise ArgumentError , "Invalid argument 'syntax'. Expected String, got #{syntax.class}." unless syntax . is_a? ( String ) read ( bin , signatur...
Loads data from an encoded DICOM string and creates items and elements which are linked to this instance .
12,111
def check_duplicate ( tag , elemental ) if @current_parent [ tag ] gp = @current_parent . parent ? "#{@current_parent.parent.representation} => " : '' p = @current_parent . representation logger . warn ( "Duplicate #{elemental} (#{tag}) detected at level: #{gp}#{p}" ) end end
Checks whether the given tag is a duplicate of an existing tag with this parent .
12,112
def check_header if @str . length < 132 return nil else @stream . skip ( 128 ) identifier = @stream . decode ( 4 , "STR" ) @header_length += 132 if identifier != "DICM" then logger . warn ( "This string does not contain the expected DICOM header. Will try to parse the string anyway (assuming a missing header)." ) @expl...
Checks for the official DICOM header signature .
12,113
def process_data_element if ! @original_explicit . nil? && @explicitness_reset_parent == @current_parent @explicit = @original_explicit end tag = read_tag return nil unless tag name , vr = LIBRARY . name_and_vr ( tag ) vr , length = read_vr_length ( vr , tag ) level_vr = vr if @enc_image and tag == ITEM_TAG vr = "OW" i...
Handles the process of reading a data element from the DICOM string and creating an element object from the parsed data .
12,114
def read ( string , signature = true , options = { } ) @str = string @overwrite = options [ :overwrite ] @signature = false @explicit = options [ :explicit ] . nil? ? true : options [ :explicit ] @str_endian = false @switched_endian = false @rest_explicit = false @rest_endian = false @switched = options [ :switched ] ?...
Builds a DICOM object by parsing an encoded DICOM string .
12,115
def add_with_segmentation ( string ) if ( string . length + @stream . length ) > @max_size split_and_add ( string ) elsif ( 30 + @stream . length ) > @max_size @segments << @stream . export @stream . add_last ( string ) else @stream . add_last ( string ) end end
Adds an encoded string to the output stream while keeping track of the accumulated size of the output stream splitting it up as necessary and transferring the encoded string fragments to an array .
12,116
def check_encapsulated_image ( element ) if element . tag == PIXEL_TAG and element . parent . is_a? ( DObject ) @enc_image = true if element . length <= 0 end end
Toggles the status for enclosed pixel data .
12,117
def encode_in_segments ( max_size , options = { } ) @max_size = max_size @transfer_syntax = options [ :syntax ] @write_success = false @explicit = true @str_endian = false @switched = false @enc_image = false @stream = Stream . new ( nil , @str_endian ) @segments = Array . new write_data_elements ( children ) @segments...
Writes DICOM content to a series of size - limited binary strings which is returned in an array . This is typically used in preparation of transmitting DICOM objects through network connections .
12,118
def split_and_add ( string ) segment = string . dup append = segment . slice! ( 0 , @max_size - @stream . length ) @segments << @stream . export + append if ( 30 + segment . length ) > @max_size number = ( segment . length / @max_size . to_f ) . floor start_index = 0 number . times { @segments << segment . slice ( star...
Splits a pre - encoded string in parts and adds it to the segments instance array .
12,119
def write_data_element ( element ) write_tag ( element . tag ) write_vr_length ( element . tag , element . vr , element . length ) write_value ( element . bin ) check_encapsulated_image ( element ) end
Encodes and writes a single data element .
12,120
def write_delimiter ( element ) delimiter_tag = ( element . tag == ITEM_TAG ? ITEM_DELIMITER : SEQUENCE_DELIMITER ) write_tag ( delimiter_tag ) write_vr_length ( delimiter_tag , ITEM_VR , 0 ) end
Encodes and writes an Item or Sequence delimiter .
12,121
def write_elements ( options = { } ) open_file ( options [ :file_name ] ) if @file @transfer_syntax = options [ :syntax ] @write_success = false @explicit = true @str_endian = false @switched = false @enc_image = false @stream = Stream . new ( nil , @str_endian ) @stream . set_file ( @file ) write_signature if options ...
Handles the encoding of DICOM information to string as well as writing it to file .
12,122
def stream if top_parent . is_a? ( DObject ) return top_parent . stream else return Stream . new ( nil , file_endian = false ) end end
Returns a Stream instance which can be used for encoding a value to binary .
12,123
def add_element ( element ) raise ArgumentError , "Invalid argument 'element'. Expected DictionaryElement, got #{element.class}" unless element . is_a? ( DictionaryElement ) @elements [ element . tag ] = element method = element . name . to_element_method @methods_from_names [ element . name ] = method @names_from_meth...
Creates a DLibrary instance .
12,124
def add_element_dictionary ( file ) File . open ( file , :encoding => 'utf-8' ) . each do | record | fields = record . split ( "\t" ) add_element ( DictionaryElement . new ( fields [ 0 ] , fields [ 1 ] , fields [ 2 ] . split ( "," ) , fields [ 3 ] . rstrip , fields [ 4 ] . rstrip ) ) end end
Adds a custom dictionary file to the ruby - dicom element dictionary .
12,125
def add_uid_dictionary ( file ) File . open ( file , :encoding => 'utf-8' ) . each do | record | fields = record . split ( "\t" ) add_uid ( UID . new ( fields [ 0 ] , fields [ 1 ] , fields [ 2 ] . rstrip , fields [ 3 ] . rstrip ) ) end end
Adds a custom dictionary file to the ruby - dicom uid dictionary .
12,126
def as_name ( value ) case true when value . tag? element ( value ) . name when value . dicom_name? @methods_from_names . has_key? ( value ) ? value . to_s : nil when value . dicom_method? @names_from_methods [ value . to_sym ] else nil end end
Gives the name corresponding to the specified element string value .
12,127
def as_tag ( value ) case true when value . tag? element ( value ) ? value : nil when value . dicom_name? get_tag ( value ) when value . dicom_method? get_tag ( @names_from_methods [ value . to_sym ] ) else nil end end
Gives the tag corresponding to the specified element string value .
12,128
def element ( tag ) element = @elements [ tag ] unless element if tag . group_length? element = DictionaryElement . new ( tag , 'Group Length' , [ 'UL' ] , '1' , '' ) else if tag . private? element = DictionaryElement . new ( tag , 'Private' , [ 'UN' ] , '1' , '' ) else element = unknown_or_range_element ( tag ) end en...
Identifies the DictionaryElement that corresponds to the given tag .
12,129
def extract_transfer_syntaxes_and_sop_classes transfer_syntaxes = Hash . new sop_classes = Hash . new @uids . each_value do | uid | if uid . transfer_syntax? transfer_syntaxes [ uid . value ] = uid . name elsif uid . sop_class? sop_classes [ uid . value ] = uid . name end end return transfer_syntaxes , sop_classes end
Extracts and returns all transfer syntaxes and SOP Classes from the dictionary .
12,130
def get_tag ( name ) tag = nil name = name . to_s . downcase @tag_name_pairs_cache ||= Hash . new return @tag_name_pairs_cache [ name ] unless @tag_name_pairs_cache [ name ] . nil? @elements . each_value do | element | next unless element . name . downcase == name tag = element . tag break end @tag_name_pairs_cache [ n...
Gives the tag that matches the supplied data element name by searching the element dictionary .
12,131
def unknown_or_range_element ( tag ) element = nil range_candidates ( tag ) . each do | range_candidate_tag | if de = @elements [ range_candidate_tag ] element = DictionaryElement . new ( tag , de . name , de . vrs , de . vm , de . retired ) break end end element ||= DictionaryElement . new ( tag , 'Unknown' , [ 'UN' ]...
Matches a tag against the possible range tag candidates and if no match is found returns a dictionary element representing an unknown tag .
12,132
def with_pool_for ( machine , read_only = false ) @pool_storage . transaction ( read_only ) do pool = lookup_pool_for ( machine ) pool ||= generate_pool_for ( machine ) yield pool end end
Create a new PoolManager instance with persistent storage .
12,133
def machine_auto_networks ( machine ) machine . config . vm . networks . select do | ( net_type , options ) | net_type == :private_network and options [ :auto_network ] end end
Fetch all private networks that are tagged for auto networking
12,134
def request ( machine ) if ( address = address_for ( machine ) ) return address elsif ( address = next_available_lease ) @pool [ address ] = id_for ( machine ) return address else raise PoolExhaustedError , :name => machine . name , :network => @network_range end end
Create a new Pool object that manages a range of IP addresses .
12,135
def address_for ( machine ) machine_id = id_for ( machine ) addr , _ = @pool . find do | ( addr , id ) | if id . is_a? ( String ) id == machine . id else id == machine_id end end addr end
Look up the address assigned to a given machine .
12,136
def default_pool = ( pool ) begin IPAddr . new pool rescue ArgumentError raise InvalidSettingErrror , :setting_name => 'default_pool' , :value => pool . inspect end @default_pool = pool end
Set the default pool to a new IP range .
12,137
def has_many ( * elements ) elements . each do | element | class_name_plural = element . to_s . split ( "_" ) . map { | e | e . capitalize } . join class_name = class_name_plural . chop adapter_class = self . to_s . scan ( / / ) . flatten . first clazz = RAutomation . constants . include? ( class_name ) ? RAutomation :...
Creates collection classes and methods for elements .
12,138
def process_projection ( data ) mutex . synchronize do projection_status = status [ data [ :projection ] ] projection_status . set_error data [ :error ] , data [ :backtrace ] projection_status . event = data [ :event ] end end
status of all projections received so far
12,139
def allowed_values ( type , field , workspace = nil ) rally_workspace_object ( workspace ) type_def = get_typedef_for ( type , workspace ) allowed_vals = { } type_def [ "Attributes" ] . each do | attr | next if attr [ "ElementName" ] != field attr [ "AllowedValues" ] . each do | val_ref | val = val_ref [ "StringValue" ...
todo - check support for portfolio item fields
12,140
def check_type ( type_name ) alias_name = @rally_alias_types [ type_name . downcase . to_s ] return alias_name unless alias_name . nil? return type_name end
check for an alias of a type - eg userstory = > hierarchicalrequirement you can add to
12,141
def check_id ( type , idstring ) if idstring . class == Fixnum return make_read_url ( type , idstring ) end if ( idstring . class == String ) return idstring if idstring . index ( "http" ) == 0 return ref_by_formatted_id ( type , idstring . split ( "|" ) [ 1 ] ) if idstring . index ( "FormattedID" ) == 0 end make_read_...
expecting idstring to have FormattedID|DE45 or the objectID or a ref itself
12,142
def method_missing ( sym , * args ) ret_val = get_val ( sym . to_s ) if ret_val . nil? && @rally_rest . rally_rest_api_compat ret_val = get_val ( camel_case_word ( sym ) ) end ret_val end
An attempt to be rally_rest_api user friendly - you can get a field the old way with an underscored field name or the upcase name
12,143
def ack ( delivery_tag , multiple = false ) if multiple @acknowledged_state [ :pending ] . keys . each do | key | ack ( key , false ) if key <= delivery_tag end elsif @acknowledged_state [ :pending ] . key? ( delivery_tag ) update_acknowledgement_state ( delivery_tag , :acked ) end nil end
Acknowledge message .
12,144
def nack ( delivery_tag , multiple = false , requeue = false ) if multiple @acknowledged_state [ :pending ] . keys . each do | key | nack ( key , false , requeue ) if key <= delivery_tag end elsif @acknowledged_state [ :pending ] . key? ( delivery_tag ) delivery , header , body = update_acknowledgement_state ( delivery...
Unacknowledge message .
12,145
def reject ( delivery_tag , requeue = false ) if @acknowledged_state [ :pending ] . key? ( delivery_tag ) delivery , header , body = update_acknowledgement_state ( delivery_tag , :rejected ) delivery . queue . publish ( body , header . to_hash ) if requeue end nil end
Rejects a message . A rejected message can be requeued or dropped by RabbitMQ .
12,146
def bind ( exchange , opts = { } ) check_queue_deleted! if exchange . respond_to? ( :add_route ) exchange . add_route opts . fetch ( :routing_key , @name ) , self else @channel . queue_bind self , opts . fetch ( :routing_key , @name ) , exchange end self end
Bind this queue to an exchange
12,147
def unbind ( exchange , opts = { } ) check_queue_deleted! if exchange . respond_to? ( :remove_route ) exchange . remove_route opts . fetch ( :routing_key , @name ) , self else @channel . queue_unbind self , opts . fetch ( :routing_key , @name ) , exchange end end
Unbind this queue from an exchange
12,148
def pop ( opts = { manual_ack : false } , & block ) if BunnyMock . use_bunny_queue_pop_api bunny_pop ( opts , & block ) else warn '[DEPRECATED] This behavior is deprecated - please set `BunnyMock::use_bunny_queue_pop_api` to true to use Bunny Queue#pop behavior' @messages . shift end end
Get oldest message in queue
12,149
def bind ( exchange , opts = { } ) if exchange . respond_to? ( :add_route ) exchange . add_route opts . fetch ( :routing_key , @name ) , self else @channel . xchg_bind self , opts . fetch ( :routing_key , @name ) , exchange end self end
Bind this exchange to another exchange
12,150
def unbind ( exchange , opts = { } ) if exchange . respond_to? ( :remove_route ) exchange . remove_route opts . fetch ( :routing_key , @name ) , self else @channel . xchg_unbind opts . fetch ( :routing_key , @name ) , exchange , self end self end
Unbind this exchange from another exchange
12,151
def routes_to? ( exchange_or_queue , opts = { } ) route = exchange_or_queue . respond_to? ( :name ) ? exchange_or_queue . name : exchange_or_queue rk = opts . fetch ( :routing_key , route ) @routes . key? ( rk ) && @routes [ rk ] . any? { | r | r == exchange_or_queue } end
Check if a queue is bound to this exchange
12,152
def move ( x , y ) ( x < 0 ? backward ( - x ) : ( x > 0 ? forward ( x ) : '' ) ) + ( y < 0 ? down ( - y ) : ( y > 0 ? up ( y ) : '' ) ) end
Move cursor relative to its current position
12,153
def clear_lines ( n , direction = :up ) n . times . reduce ( [ ] ) do | acc , i | dir = direction == :up ? up : down acc << clear_line + ( ( i == n - 1 ) ? '' : dir ) end . join end
Clear a number of lines
12,154
def transform_move ( line , c ) ret = { } ret [ "comments" ] = c if ! c . empty? if line [ "move" ] . is_a? Hash ret [ "move" ] = line [ "move" ] else ret [ "special" ] = special2csa ( line [ "move" ] ) end ret [ "time" ] = line [ "time" ] if line [ "time" ] ret end
transform move to jkf
12,155
def transform_teban_fugou_from ( teban , fugou , from ) ret = { "color" => teban2color ( teban . join ) , "piece" => fugou [ "piece" ] } if fugou [ "to" ] ret [ "to" ] = fugou [ "to" ] else ret [ "same" ] = true end ret [ "promote" ] = true if fugou [ "promote" ] ret [ "from" ] = from if from ret end
transform teban - fugou - from to jkf
12,156
def reverse_color ( moves ) moves . each do | move | if move [ "move" ] && move [ "move" ] [ "color" ] move [ "move" ] [ "color" ] = ( move [ "move" ] [ "color" ] + 1 ) % 2 end move [ "forks" ] . each { | _fork | reverse_color ( _fork ) } if move [ "forks" ] end end
exchange sente gote
12,157
def transform_fugou ( pl , pi , sou , dou , pro , da ) ret = { "piece" => pi } if pl [ "same" ] ret [ "same" ] = true else ret [ "to" ] = pl end ret [ "promote" ] = ( pro == "成") i p o if da ret [ "relative" ] = "H" else rel = soutai2relative ( sou ) + dousa2relative ( dou ) ret [ "relative" ] = rel unless rel . empt...
transfrom fugou to jkf
12,158
def match_spaces stack = [ ] matched = match_space while matched != :failed stack << matched matched = match_space end stack end
match space one or more
12,159
def transform_root_forks ( forks , moves ) fork_stack = [ { "te" => 0 , "moves" => moves } ] forks . each do | f | now_fork = f _fork = fork_stack . pop _fork = fork_stack . pop while _fork [ "te" ] > now_fork [ "te" ] move = _fork [ "moves" ] [ now_fork [ "te" ] - _fork [ "te" ] ] move [ "forks" ] ||= [ ] move [ "fork...
transfrom forks to jkf
12,160
def transform_initialboard ( lines ) board = [ ] 9 . times do | i | line = [ ] 9 . times do | j | line << lines [ j ] [ 8 - i ] end board << line end { "preset" => "OTHER" , "data" => { "board" => board } } end
transform initialboard to jkf
12,161
def transform_komabetsu_lines ( lines ) board = generate_empty_board hands = [ { "FU" => 0 , "KY" => 0 , "KE" => 0 , "GI" => 0 , "KI" => 0 , "KA" => 0 , "HI" => 0 } , { "FU" => 0 , "KY" => 0 , "KE" => 0 , "GI" => 0 , "KI" => 0 , "KA" => 0 , "HI" => 0 } ] all = { "FU" => 18 , "KY" => 4 , "KE" => 4 , "GI" => 4 , "KI" => ...
lines to jkf
12,162
def generate_empty_board board = [ ] 9 . times do | _i | line = [ ] 9 . times do | _j | line << { } end board << line end board end
return empty board jkf
12,163
def to_operations cloned = Marshal . load Marshal . dump ( operations ) operations . each do | op | op . source_account ||= self . source_account end end
Extracts the operations from this single transaction setting the source account on the extracted operations .
12,164
def send_amount s = success! return s . last . amount if s . offers . blank? source_asset = s . offers . first . asset_bought source_offers = s . offers . take_while { | o | o . asset_bought == source_asset } source_offers . map ( & :amount_bought ) . sum end
send_amount returns the actual amount paid for the corresponding PathPaymentOp to this result .
12,165
def signed_correctly? ( * key_pairs ) hash = tx . hash return false if signatures . empty? key_index = key_pairs . index_by ( & :signature_hint ) signatures . all? do | sig | key_pair = key_index [ sig . hint ] break false if key_pair . nil? key_pair . verify ( sig . signature , hash ) end end
Checks to ensure that every signature for the envelope is a valid signature of one of the provided key_pairs
12,166
def configure ( options = { } , & block ) configurator = Configurator . new ( self , options ) if block . arity == 1 yield configurator else configurator . instance_eval ( & block ) end self end
this is a convenience method to configure exchanges queues messages and handlers with a common set of options . allows one to call all register methods without the register_ prefix . returns self . if the passed in block has no parameters the block will be evaluated in the context of the client configurator .
12,167
def rpc ( message_name , data = nil , opts = { } ) message_name = validated_message_name ( message_name ) publisher . rpc ( message_name , data , opts ) end
sends the given message to one of the configured servers and returns the result of running the associated handler .
12,168
def trace ( queue_names = self . queues . keys , tracer = nil , & block ) queues_to_trace = self . queues . slice ( * queue_names ) queues_to_trace . each do | name , opts | opts . merge! :durable => false , :auto_delete => true , :amqp_name => queue_name_for_tracing ( opts [ :amqp_name ] ) end tracer ||= lambda do | m...
traces queues without consuming them . useful for debugging message flow .
12,169
def load ( glob ) b = binding Dir [ glob ] . each do | f | eval ( File . read ( f ) , b , f ) end end
evaluate the ruby files matching the given + glob + pattern in the context of the client instance .
12,170
def decode amqp_headers = header . attributes @uuid = amqp_headers [ :message_id ] @timestamp = amqp_headers [ :timestamp ] headers = amqp_headers [ :headers ] . symbolize_keys @format_version = headers [ :format_version ] . to_i @flags = headers [ :flags ] . to_i @expires_at = headers [ :expires_at ] . to_i rescue Exc...
extracts various values from the AMQP header properties
12,171
def key_exists? old_message = ! @store . msetnx ( msg_id , :status => "incomplete" , :expires => @expires_at , :timeout => now + timeout ) if old_message logger . debug "Beetle: received duplicate message: #{msg_id} on queue: #{@queue}" end old_message end
have we already seen this message? if not set the status to incomplete and store the message exipration timestamp in the deduplication store .
12,172
def process ( handler ) logger . debug "Beetle: processing message #{msg_id}" result = nil begin result = process_internal ( handler ) handler . process_exception ( @exception ) if @exception handler . process_failure ( result ) if result . failure? rescue Exception => e Beetle :: reraise_expectation_errors! logger . w...
process this message and do not allow any exception to escape to the caller
12,173
def ack! logger . debug "Beetle: ack! for message #{msg_id}" header . ack return if simple? if ! redundant? || @store . incr ( msg_id , :ack_count ) == 2 @store . del_keys ( msg_id ) end end
ack the message for rabbit . deletes all keys associated with this message in the deduplication store if we are sure this is the last message with the given msg_id .
12,174
def bunny_exceptions [ Bunny :: ConnectionError , Bunny :: ForcedChannelCloseError , Bunny :: ForcedConnectionCloseError , Bunny :: MessageError , Bunny :: ProtocolError , Bunny :: ServerDownError , Bunny :: UnsubscribeError , Bunny :: AcknowledgementError , Qrack :: BufferOverflowError , Qrack :: InvalidTypeError , Er...
list of exceptions potentially raised by bunny these need to be lazy because qrack exceptions are only defined after a connection has been established
12,175
def recycle_dead_servers recycle = [ ] @dead_servers . each do | s , dead_since | recycle << s if dead_since < 10 . seconds . ago end if recycle . empty? && @servers . empty? recycle << @dead_servers . keys . sort_by { | k | @dead_servers [ k ] } . first end @servers . concat recycle recycle . each { | s | @dead_server...
retry dead servers after ignoring them for 10 . seconds if all servers are dead retry the one which has been dead for the longest time
12,176
def with_failover end_time = Time . now . to_i + @config . redis_failover_timeout . to_i begin yield rescue Exception => e Beetle :: reraise_expectation_errors! logger . error "Beetle: redis connection error #{e} #{@config.redis_server} (#{e.backtrace[0]})" if Time . now . to_i < end_time sleep 1 logger . info "Beetle:...
performs redis operations by yielding a passed in block waiting for a new master to show up on the network if the operation throws an exception . if a new master doesn t appear after the configured timeout interval we raise an exception .
12,177
def extract_redis_master ( text ) system_name = @config . system_name redis_master = "" text . each_line do | line | parts = line . split ( '/' , 2 ) case parts . size when 1 redis_master = parts [ 0 ] when 2 name , master = parts redis_master = master if name == system_name end end redis_master end
extract redis master from file content and return the server for our system
12,178
def close_all_connections if @connections . empty? EM . stop_event_loop else server , connection = @connections . shift logger . debug "Beetle: closing connection to #{server}" connection . close { close_all_connections } end end
close all connections . this assumes the reactor is running
12,179
def setup_key_pair public_key , private_key = generate_key key_name = "foreman-#{id}#{Foreman.uuid}" client . create_ssh_key key_name , public_key KeyPair . create! :name => key_name , :compute_resource_id => id , :secret => private_key rescue StandardError => e logger . warn 'failed to generate key pair' logger . erro...
Creates a new key pair for each new DigitalOcean compute resource After creating the key it uploads it to DigitalOcean
12,180
def clear_nil_attributes ( hash ) hash . reject! do | key , value | if value . nil? return true elsif value . is_a? Hash value . reject! { | inner_key , inner_value | inner_value . nil? } end false end hash end
Remove any attributes with nil values in a saved query hash . The API will already assume missing attributes are nil
12,181
def with_connection connection_id = current_connection_id fresh_connection = true unless @reserved_connections [ connection_id ] yield connection ensure release_connection ( connection_id ) if fresh_connection end
If a connection already exists yield it to the block . If no connection exists checkout a connection yield it to the block and checkin the connection when finished .
12,182
def clear_stale_cached_connections! keys = @reserved_connections . keys - Thread . list . find_all { | t | t . alive? } . map { | thread | thread . object_id } keys . each do | key | checkin @reserved_connections [ key ] @reserved_connections . delete ( key ) end end
Return any checked - out connections back to the pool by threads that are no longer alive .
12,183
def merge_attributes ( attrs = { } ) @attributes = self . class . attributes_from_module @attributes . keys . each do | name | write_attribute name , attrs [ name ] if attrs [ name ] end @modified_attributes = { } unless new? end
Merges attributes provided as an argument to initialize with attributes from the module . fields array . Skips any fields that aren t in the module . fields array
12,184
def save_modified_attributes! ( opts = { } ) options = { :validate => true } . merge ( opts ) if options [ :validate ] raise InvalidRecord , @errors . full_messages . join ( ", " ) unless valid? end response = self . class . session . connection . set_entry ( self . class . _module . name , serialize_modified_attribute...
Wrapper for invoking save on modified_attributes sets the id if it s a new record
12,185
def find! ( target ) @associations . each do | a | return a if a . include? target end raise InvalidAssociation , "Could not lookup association for: #{target}" end
Looks up an association by object link_field or method . Raises an exception if not found
12,186
def query_association ( assoc , reload = false ) association = assoc . to_sym return @association_cache [ association ] if association_cached? ( association ) && ! reload collection = AssociationCollection . new ( self , association , true ) @association_cache [ association ] = collection collection end
Returns the records from the associated module or returns the cached copy if we ve already loaded it . Force a reload of the records with reload = true
12,187
def update_association_cache_for ( association , target , action = :add ) return unless association_cached? association case action when :add return if @association_cache [ association ] . collection . include? target @association_cache [ association ] . push ( target ) when :delete @association_cache [ association ] ....
Updates an association cache entry if it s been initialized
12,188
def changed? return false unless loaded? return true if added . length > 0 return true if removed . length > 0 false end
creates a new instance of an AssociationCollection Owner is the parent object and association is the target
12,189
def delete ( record ) load raise InvalidRecord , "#{record.class} does not have a valid :id!" if record . id . empty? @collection . delete record end
Removes a record from the collection uses the id of the record as a test for inclusion .
12,190
def << ( record ) load record . save! if record . new? result = true result = false if include? ( record ) @owner . update_association_cache_for ( @association , record , :add ) record . update_association_cache_for ( record . associations . find! ( @owner ) . link_field , @owner , :add ) result && self end
Add + records + to this association saving any unsaved records before adding them . Returns + self + so method calls may be chained . Be sure to call save on the association to commit any association changes
12,191
def method_missing ( method_name , * args , & block ) load @collection . send ( method_name . to_sym , * args , & block ) end
delegate undefined methods to the
12,192
def save! load added . each do | record | associate! ( record ) end removed . each do | record | disassociate! ( record ) end reload true end
Pushes collection changes to SugarCRM and updates the state of the collection
12,193
def load_associated_records array = @owner . class . session . connection . get_relationships ( @owner . class . _module . name , @owner . id , @association . to_s ) @loaded = true @collection = Array . wrap ( array ) . dup @original = Array . wrap ( array ) . freeze end
Loads related records for the given association
12,194
def class_for ( module_name ) begin class_const = @session . namespace_const . const_get ( module_name . classify ) klass = class_const . new rescue NameError raise InvalidModule , "Module: #{module_name} is not registered" end end
Returns an instance of class for the provided module name
12,195
def send! ( method , json , max_retry = 3 ) if max_retry == 0 raise SugarCRM :: RetryLimitExceeded , "SugarCRM::Connection Errors: \n#{@errors.reverse.join "\n\s\s"}" end @request = SugarCRM :: Request . new ( @url , method , json , @options [ :debug ] ) begin if @request . length > 3900 @response = @connection . post ...
Send a request to the Sugar Instance
12,196
def reconnect ( url = nil , user = nil , pass = nil , opts = { } ) @connection_pool . disconnect! connect ( url , user , pass , opts ) end
Re - uses this session and namespace if the user wants to connect with different credentials
12,197
def load_extensions self . class . validate_path @extensions_path Dir [ File . join ( @extensions_path , '**' , '*.rb' ) . to_s ] . each { | f | load ( f ) } end
load all the monkey patch extension files in the provided folder
12,198
def include? ( attribute ) return true if attribute . class == @target return true if attribute == link_field return true if methods . include? attribute false end
Creates a new instance of an Association Returns true if the association includes an attribute that matches the provided string
12,199
def resolve_target klass = @link_field . singularize . camelize namespace = @owner . class . session . namespace_const return namespace . const_get ( klass ) if namespace . const_defined? klass if @attributes [ "module" ] . length > 0 module_name = SugarCRM :: Module . find ( @attributes [ "module" ] , @owner . class ....
Attempts to determine the class of the target in the association