idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
20,700
def each ( status , identities = nil ) choices = if identities && ! identities . empty? identities . inject ( [ ] ) { | c , i | if b = @brokers_hash [ i ] then c << b else c end } else @brokers end choices . select do | b | if b . send ( "#{status}?" . to_sym ) yield ( b ) if block_given? true end end end
Iterate over clients that have the specified status
20,701
def use ( options ) choices = [ ] select = options [ :order ] if options [ :brokers ] && ! options [ :brokers ] . empty? options [ :brokers ] . each do | identity | if choice = @brokers_hash [ identity ] choices << choice else logger . exception ( "Invalid broker identity #{identity.inspect}, check server configuration" ) end end else choices = @brokers select ||= @select end if select == :random choices . sort_by { rand } else choices end end
Select the broker clients to be used in the desired order
20,702
def handle_return ( identity , to , reason , message ) @brokers_hash [ identity ] . update_status ( :stopping ) if reason == "ACCESS_REFUSED" if context = @published . fetch ( message ) @return_stats . update ( "#{alias_(identity)} (#{reason.to_s.downcase})" ) context . record_failure ( identity ) name = context . name options = context . options || { } token = context . token one_way = context . one_way persistent = options [ :persistent ] mandatory = true remaining = ( context . brokers - context . failed ) & connected logger . info ( "RETURN reason #{reason} token <#{token}> to #{to} from #{context.from} brokers #{context.brokers.inspect} " + "failed #{context.failed.inspect} remaining #{remaining.inspect} connected #{connected.inspect}" ) if remaining . empty? if ( persistent || one_way ) && [ "ACCESS_REFUSED" , "NO_CONSUMERS" ] . include? ( reason ) && ! ( remaining = context . brokers & connected ) . empty? mandatory = false else t = token ? " <#{token}>" : "" logger . info ( "NO ROUTE #{aliases(context.brokers).join(", ")} [#{name}]#{t} to #{to}" ) @non_delivery . call ( reason , context . type , token , context . from , to ) if @non_delivery @non_delivery_stats . update ( "no route" ) end end unless remaining . empty? t = token ? " <#{token}>" : "" p = persistent ? ", persistent" : "" m = mandatory ? ", mandatory" : "" logger . info ( "RE-ROUTE #{aliases(remaining).join(", ")} [#{context.name}]#{t} to #{to}#{p}#{m}" ) exchange = { :type => :queue , :name => to , :options => { :no_declare => true } } publish ( exchange , message , options . merge ( :no_serialize => true , :brokers => remaining , :persistent => persistent , :mandatory => mandatory ) ) end else @return_stats . update ( "#{alias_(identity)} (#{reason.to_s.downcase} - missing context)" ) logger . info ( "Dropping message returned from broker #{identity} for reason #{reason} " + "because no message context available for re-routing it to #{to}" ) end true rescue Exception => e logger . exception ( "Failed to handle #{reason} return from #{identity} for message being routed to #{to}" , e , :trace ) @exception_stats . track ( "return" , e ) end
Handle message returned by broker because it could not deliver it If agent still active resend using another broker If this is last usable broker and persistent is enabled allow message to be queued on next send even if the queue has no consumers so there is a chance of message eventually being delivered If persistent or one - way request and all usable brokers have failed try one more time without mandatory flag to give message opportunity to be queued If there are no more usable broker clients send non - delivery message to original sender
20,703
def method_missing ( method_name , * args ) setter = method_name . to_s . ends_with? ( '=' ) attr_name = method_name . to_s . gsub ( / / , "" ) if setter attributes [ attr_name ] = args . first else attributes [ attr_name ] end end
Overrides method missing to catch undefined methods . If + method_name + is one of the keys on + attributes + returns the value of that attribute . If + method_name + is not one of + attributes + passes up the chain to super .
20,704
def visit ( source , target , & block ) @matches . clear @id_mtchs . clear add_match ( source , target ) super ( source ) { | src | visit_matched ( src , & block ) } end
Creates a new visitor which matches source and target domain object references . The domain attributes to visit are determined by calling the selector block given to this initializer . The selector arguments consist of the match source and target .
20,705
def visit_matched ( source ) tgt = @matches [ source ] || return if @matchable then mas = @matchable . call ( source ) - attributes_to_visit ( source ) mas . each { | ma | match_reference ( source , tgt , ma ) } end block_given? ? yield ( source , tgt ) : tgt end
Visits the given source domain object .
20,706
def match_reference ( source , target , attribute ) srcs = source . send ( attribute ) . to_enum tgts = target . send ( attribute ) . to_enum mtchd_tgts = Set . new unmtchd_srcs = srcs . reject do | src | tgt = match_for ( src ) mtchd_tgts << tgt if tgt end unmtchd_tgts = tgts . difference ( mtchd_tgts ) logger . debug { "#{qp} matching #{unmtchd_tgts.qp}..." } if @verbose and not unmtchd_tgts . empty? rsd_mtchs = @matcher . match ( unmtchd_srcs , unmtchd_tgts , source , attribute ) rsd_mtchs . each { | src , tgt | add_match ( src , tgt ) } logger . debug { "#{qp} matched #{rsd_mtchs.qp}..." } if @verbose and not rsd_mtchs . empty? matches = srcs . to_compact_hash { | src | match_for ( src ) or copy_unmatched ( src ) } matches end
Matches the given source and target attribute references . The match is performed by this visitor s matcher .
20,707
def extract_source_from_file ( file_path , env = { } ) source = HtmlMockup :: Template . open ( file_path , :partials_path => self . project . partial_path , :layouts_path => self . project . layouts_path ) . render ( env . dup ) if @options [ :url_relativize ] source = relativize_urls ( source , file_path ) end source end
Runs the extractor on a single file and return processed source .
20,708
def build_json_serializer ( object , options = { } ) ScopedSerializer . for ( object , { :scope => serializer_scope , :super => true } . merge ( options . merge ( default_serializer_options ) ) ) end
JSON serializer to use .
20,709
def format ( number ) case number when Float then format_float ( number ) when Integer then format_integer ( number ) else fail ArgumentError end end
Initialize a formatter with the desired options .
20,710
def remove_stale_symlinks ( path ) Dir . glob ( "#{path}/*" ) . each { | f | File . unlink ( f ) if not File . exist? ( f ) } end
just loop through a directory and get rid of any stale symlinks
20,711
def start ( queue = nil ) queue . nil? and queue = @queue logger . debug "Listener starts..." @thread = Thread . new { @connfu_stream . start_listening } while continue do logger . debug "Waiting for a message from connFu stream" message = @connfu_stream . get @counter = @counter + 1 logger . debug "#{self.class} got message => #{message}" queue . put ( message ) end end
max amount of messages to receive
20,712
def owner = ( obj ) if obj . nil? then op , ov = effective_owner_property_value || return else op = self . class . owner_properties . detect { | prop | prop . type === obj } end if op . nil? then raise NoMethodError . new ( "#{self.class.qp} does not have an owner attribute for #{obj}" ) end set_property_value ( op . attribute , obj ) end
Sets this dependent s owner attribute to the given domain object .
20,713
def references ( attributes = nil ) attributes ||= self . class . domain_attributes attributes . map { | pa | send ( pa ) } . flatten . compact end
Returns the domain object references for the given attributes .
20,714
def direct_dependents ( attribute ) deps = send ( attribute ) case deps when Enumerable then deps when nil then Array :: EMPTY_ARRAY else [ deps ] end end
Returns the attribute references which directly depend on this owner . The default is the attribute value .
20,715
def match_in ( others ) return self if others . include? ( self ) unless others . all? { | other | self . class === other } then others = others . filter { | other | self . class === other } end match_unique_object_with_attributes ( others , self . class . primary_key_attributes ) or match_unique_object_with_attributes ( others , self . class . secondary_key_attributes ) or match_unique_object_with_attributes ( others , self . class . alternate_key_attributes ) end
Matches this dependent domain object with the others on type and key attributes in the scope of a parent object . Returns the object in others which matches this domain object or nil if none .
20,716
def visit_path ( * path , & operator ) visitor = ReferencePathVisitor . new ( self . class , path ) visitor . visit ( self , & operator ) end
Applies the operator block to this object and each domain object in the reference path . This method visits the transitive closure of each recursive path attribute .
20,717
def printable_content ( attributes = nil , & reference_printer ) attributes ||= printworthy_attributes vh = value_hash ( attributes ) vh . transform_value { | value | printable_value ( value , & reference_printer ) } end
Returns this domain object s attributes content as an attribute = > value hash suitable for printing .
20,718
def validate_mandatory_attributes invalid = missing_mandatory_attributes unless invalid . empty? then logger . error ( "Validation of #{qp} unsuccessful - missing #{invalid.join(', ')}:\n#{dump}" ) raise ValidationError . new ( "Required attribute value missing for #{self}: #{invalid.join(', ')}" ) end validate_owner end
Validates that this domain object contains a non - nil value for each mandatory attribute .
20,719
def validate_owner return unless owner . nil? if self . class . owner_attributes . size > 1 then vh = value_hash ( self . class . owner_attributes ) if vh . size > 1 then raise ValidationError . new ( "Dependent #{self} references multiple owners #{vh.pp_s}:\n#{dump}" ) end end if self . class . bidirectional_java_dependent? then raise ValidationError . new ( "Dependent #{self} does not reference an owner" ) end end
Validates that this domain object either doesn t have an owner attribute or has a unique effective owner .
20,720
def printable_value ( value , & reference_printer ) Jinx :: Collector . on ( value ) do | item | if Resource === item then block_given? ? yield ( item ) : printable_value ( item ) { | ref | ReferencePrinter . new ( ref ) } else item end end end
Returns a value suitable for printing . If value is a domain object then the block provided to this method is called . The default block creates a new ReferencePrinter on the value .
20,721
def printworthy_attributes if self . class . primary_key_attributes . all? { | pa | ! ! send ( pa ) } then self . class . primary_key_attributes elsif not self . class . secondary_key_attributes . empty? then self . class . secondary_key_attributes elsif not self . class . nondomain_java_attributes . empty? then self . class . nondomain_java_attributes else self . class . fetched_attributes end end
Returns an attribute = > value hash which identifies the object . If this object has a complete primary key than the primary key attributes are returned . Otherwise if there are secondary key attributes then they are returned . Otherwise if there are nondomain attributes then they are returned . Otherwise if there are fetched attributes then they are returned .
20,722
def empty_value ( attribute ) type = java_type ( attribute ) || return if type . primitive? then type . name == 'boolean' ? false : 0 else self . class . empty_value ( attribute ) end end
Returns 0 if attribute is a Java primitive number + false + if attribute is a Java primitive boolean an empty collectin if the Java attribute is a collection nil otherwise .
20,723
def java_type ( attribute ) prop = self . class . property ( attribute ) prop . property_descriptor . attribute_type if JavaProperty === prop end
Returns the Java type of the given attribute or nil if attribute is not a Java property attribute .
20,724
def match_unique_object_with_attributes ( others , attributes ) vh = value_hash ( attributes ) return if vh . empty? or vh . size < attributes . size matches = others . select do | other | self . class == other . class and vh . all? { | pa , v | other . matches_attribute_value? ( pa , v ) } end matches . first if matches . size == 1 end
Returns the object in others which uniquely matches this domain object on the given attributes or nil if there is no unique match . This method returns nil if any attributes value is nil .
20,725
def non_id_search_attribute_values key_props = self . class . secondary_key_attributes pas = key_props . empty? ? self . class . nondomain_java_attributes : key_props attr_values = pas . to_compact_hash { | pa | send ( pa ) } key_props . empty? ? attr_values . delete_if { | pa , value | value . nil? } : attr_values end
Returns the attribute = > value hash to use for matching this domain object .
20,726
def render_csv ( filename = nil , view_name = nil ) filename ||= params [ :action ] view_name ||= params [ :action ] filename . downcase! filename += '.csv' unless filename [ - 4 .. - 1 ] == '.csv' headers [ 'Content-Type' ] = 'text/csv' headers [ 'Content-Disposition' ] = "attachment; filename=\"#{filename}\"" render view_name , layout : false end
Renders the view as a CSV file .
20,727
def authorize! ( * accepted_groups ) begin unless logged_in? store_location if ( auth_url = :: Incline :: UserManager . begin_external_authentication ( request ) ) :: Incline :: Log . debug 'Redirecting for external authentication.' redirect_to auth_url return false end raise_not_logged_in "You need to login to access '#{request.fullpath}'." , 'nobody is logged in' end if system_admin? log_authorize_success 'user is system admin' else accepted_groups ||= [ ] accepted_groups . flatten! accepted_groups . delete false accepted_groups . delete '' if accepted_groups . include? ( true ) raise_authorize_failure "Your are not authorized to access '#{request.fullpath}'." , 'requires system administrator' elsif accepted_groups . blank? log_authorize_success 'only requires authenticated user' else accepted_groups = accepted_groups . map { | v | v . to_s . upcase } . sort result = current_user . has_any_group? ( * accepted_groups ) unless result raise_authorize_failure "You are not authorized to access '#{request.fullpath}'." , "requires one of: #{accepted_groups.inspect}" end log_authorize_success "user has #{result.inspect}" end end rescue :: Incline :: NotAuthorized => err flash [ :danger ] = err . message redirect_to main_app . root_url return false end true end
Authorizes access for the action .
20,728
def valid_user? if require_admin_for_request? authorize! true elsif require_anon_for_request? if logged_in? flash [ :warning ] = 'The specified action cannot be performed while logged in.' redirect_to incline . user_path ( current_user ) end elsif allow_anon_for_request? true else action = Incline :: ActionSecurity . valid_items [ self . class . controller_path , params [ :action ] ] if action && action . groups . count > 0 authorize! action . groups . pluck ( :name ) else authorize! end end end
Validates that the current user is authorized for the current request .
20,729
def get ( profile = 'default' ) raise 'Config File does not exist' unless File . exists? ( @file ) @credentials = parse if @credentials . nil? raise 'The profile is not specified in the config file' unless @credentials . has_key? ( profile ) @credentials [ profile ] end
returns hash of AWS credential
20,730
def build trace "gem build #{gemspec}" spec = load_gemspec package = :: Gem :: Package . build ( spec ) mkdir_p ( pkgdir ) unless File . directory? ( pkgdir ) mv ( package , pkgdir ) end
Create a gem package .
20,731
def create_gemspec ( file = nil ) file = gemspec if ! file yaml = project . to_gemspec . to_yaml File . open ( file , 'w' ) do | f | f << yaml end status File . basename ( file ) + " updated." return file end
Create a gemspec file from project metadata .
20,732
def lookup_gemspec dot_gemspec = ( project . root + '.gemspec' ) . to_s if File . exist? ( dot_gemspec ) dot_gemspec . to_s else project . metadata . name + '.gemspec' end end
Lookup gemspec file . If not found returns default path .
20,733
def load_gemspec file = gemspec if yaml? ( file ) :: Gem :: Specification . from_yaml ( File . new ( file ) ) else :: Gem :: Specification . load ( file ) end end
Load gemspec file .
20,734
def yaml? ( file ) line = open ( file ) { | f | line = f . gets } line . index "!ruby/object:Gem::Specification" end
If the gemspec a YAML gemspec?
20,735
def default handler_name = @handler_name proc { comp = @context . elements [ handler_name ] [ :content ] if comp . kind_of? ( Proc ) comp . call else Context . wipe handler_name Context . render comp , handler_name end } end
Render the default content for this component as it is defined in the context .
20,736
def do ( delay : nil , exceptions : nil , handlers : nil , tries : nil , & block ) Retry . do ( delay : delay || self . delay , exceptions : exceptions || self . exceptions , handlers : handlers || self . handlers , tries : tries || self . tries , & block ) end
Initialises a new Engine instance
20,737
def fmod_with_float ( other ) other = Node . match ( other , typecode ) . new other unless other . matched? if typecode < FLOAT_ or other . typecode < FLOAT_ fmod other else fmod_without_float other end end
Modulo operation for floating point numbers
20,738
def to_type ( dest ) if dimension == 0 and variables . empty? target = typecode . to_type dest target . new ( simplify . get ) . simplify else key = "to_#{dest.to_s.downcase}" Hornetseye :: ElementWise ( proc { | x | x . to_type dest } , key , proc { | t | t . to_type dest } ) . new ( self ) . force end end
Convert array elements to different element type
20,739
def to_type_with_rgb ( dest ) if typecode < RGB_ if dest < FLOAT_ lazy { r * 0.299 + g * 0.587 + b * 0.114 } . to_type dest elsif dest < INT_ lazy { ( r * 0.299 + g * 0.587 + b * 0.114 ) . round } . to_type dest else to_type_without_rgb dest end else to_type_without_rgb dest end end
Convert RGB array to scalar array
20,740
def reshape ( * ret_shape ) target_size = ret_shape . inject 1 , :* if target_size != size raise "Target is of size #{target_size} but should be of size #{size}" end Hornetseye :: MultiArray ( typecode , ret_shape . size ) . new * ( ret_shape + [ :memory => memorise . memory ] ) end
Get array with same elements but different shape
20,741
def conditional ( a , b ) a = Node . match ( a , b . matched? ? b : nil ) . new a unless a . matched? b = Node . match ( b , a . matched? ? a : nil ) . new b unless b . matched? if dimension == 0 and variables . empty? and a . dimension == 0 and a . variables . empty? and b . dimension == 0 and b . variables . empty? target = typecode . cond a . typecode , b . typecode target . new simplify . get . conditional ( proc { a . simplify . get } , proc { b . simplify . get } ) else Hornetseye :: ElementWise ( proc { | x , y , z | x . conditional y , z } , :conditional , proc { | t , u , v | t . cond u , v } ) . new ( self , a , b ) . force end end
Element - wise conditional selection of values
20,742
def transpose ( * order ) if ( 0 ... dimension ) . to_a != order . sort raise 'Each array index must be specified exactly once!' end term = self variables = shape . reverse . collect do | i | var = Variable . new Hornetseye :: INDEX ( i ) term = term . element var var end . reverse order . collect { | o | variables [ o ] } . inject ( term ) { | retval , var | Lambda . new var , retval } end
Element - wise comparison of values
20,743
def unroll ( n = 1 ) if n < 0 roll - n else order = ( 0 ... dimension ) . to_a n . times { order = [ order . last ] + order [ 0 ... - 1 ] } transpose * order end end
Reverse - cycle indices of array
20,744
def collect ( & action ) var = Variable . new typecode block = action . call var conversion = proc { | t | t . to_type action . call ( Variable . new ( t . typecode ) ) . typecode } Hornetseye :: ElementWise ( action , block . to_s , conversion ) . new ( self ) . force end
Perform element - wise operation on array
20,745
def inject ( * args , & action ) options = args . last . is_a? ( Hash ) ? args . pop : { } unless action or options [ :block ] unless [ 1 , 2 ] . member? args . size raise "Inject expected 1 or 2 arguments but got #{args.size}" end initial , symbol = args [ - 2 ] , args [ - 1 ] action = proc { | a , b | a . send symbol , b } else raise "Inject expected 0 or 1 arguments but got #{args.size}" if args . size > 1 initial = args . empty? ? nil : args . first end unless initial . nil? initial = Node . match ( initial ) . new initial unless initial . matched? initial_typecode = initial . typecode else initial_typecode = typecode end var1 = options [ :var1 ] || Variable . new ( initial_typecode ) var2 = options [ :var2 ] || Variable . new ( typecode ) block = options [ :block ] || action . call ( var1 , var2 ) if dimension == 0 if initial block . subst ( var1 => initial , var2 => self ) . simplify else demand end else index = Variable . new Hornetseye :: INDEX ( nil ) value = element ( index ) . inject nil , :block => block , :var1 => var1 , :var2 => var2 value = typecode . new value unless value . matched? if initial . nil? and index . size . get == 0 raise "Array was empty and no initial value for injection was given" end Inject . new ( value , index , initial , block , var1 , var2 ) . force end end
Perform cummulative operation on array
20,746
def range ( initial = nil ) min ( initial ? initial . min : nil ) .. max ( initial ? initial . max : nil ) end
Find range of values of array
20,747
def normalise ( range = 0 .. 0xFF ) if range . exclude_end? raise "Normalisation does not support ranges with end value " + "excluded (such as #{range})" end lower , upper = min , max if lower . is_a? RGB or upper . is_a? RGB current = [ lower . r , lower . g , lower . b ] . min .. [ upper . r , upper . g , upper . b ] . max else current = min .. max end if current . last != current . first factor = ( range . last - range . first ) . to_f / ( current . last - current . first ) collect { | x | x * factor + ( range . first - current . first * factor ) } else self + ( range . first - current . first ) end end
Check values against boundaries
20,748
def clip ( range = 0 .. 0xFF ) if range . exclude_end? raise "Clipping does not support ranges with end value " + "excluded (such as #{range})" end collect { | x | x . major ( range . begin ) . minor range . end } end
Clip values to specified range
20,749
def stretch ( from = 0 .. 0xFF , to = 0 .. 0xFF ) if from . exclude_end? raise "Stretching does not support ranges with end value " + "excluded (such as #{from})" end if to . exclude_end? raise "Stretching does not support ranges with end value " + "excluded (such as #{to})" end if from . last != from . first factor = ( to . last - to . first ) . to_f / ( from . last - from . first ) collect { | x | ( ( x - from . first ) * factor ) . major ( to . first ) . minor to . last } else ( self <= from . first ) . conditional to . first , to . last end end
Stretch values from one range to another
20,750
def diagonal ( initial = nil , options = { } ) if dimension == 0 demand else if initial initial = Node . match ( initial ) . new initial unless initial . matched? initial_typecode = initial . typecode else initial_typecode = typecode end index0 = Variable . new Hornetseye :: INDEX ( nil ) index1 = Variable . new Hornetseye :: INDEX ( nil ) index2 = Variable . new Hornetseye :: INDEX ( nil ) var1 = options [ :var1 ] || Variable . new ( initial_typecode ) var2 = options [ :var2 ] || Variable . new ( typecode ) block = options [ :block ] || yield ( var1 , var2 ) value = element ( index1 ) . element ( index2 ) . diagonal initial , :block => block , :var1 => var1 , :var2 => var2 term = Diagonal . new ( value , index0 , index1 , index2 , initial , block , var1 , var2 ) index0 . size = index1 . size Lambda . new ( index0 , term ) . force end end
Apply accumulative operation over elements diagonally
20,751
def table ( filter , & action ) filter = Node . match ( filter , typecode ) . new filter unless filter . matched? if filter . dimension > dimension raise "Filter has #{filter.dimension} dimension(s) but should " + "not have more than #{dimension}" end filter = Hornetseye :: lazy ( 1 ) { filter } while filter . dimension < dimension if filter . dimension == 0 action . call self , filter else Hornetseye :: lazy { | i , j | self [ j ] . table filter [ i ] , & action } end end
Compute table from two arrays
20,752
def convolve ( filter ) filter = Node . match ( filter , typecode ) . new filter unless filter . matched? array = self ( dimension - filter . dimension ) . times { array = array . roll } array . table ( filter ) { | a , b | a * b } . diagonal { | s , x | s + x } end
Convolution with other array of same dimension
20,753
def histogram ( * ret_shape ) options = ret_shape . last . is_a? ( Hash ) ? ret_shape . pop : { } options = { :weight => UINT . new ( 1 ) , :safe => true } . merge options unless options [ :weight ] . matched? options [ :weight ] = Node . match ( options [ :weight ] ) . maxint . new options [ :weight ] end if ( shape . first != 1 or dimension == 1 ) and ret_shape . size == 1 [ self ] . histogram * ( ret_shape + [ options ] ) else ( 0 ... shape . first ) . collect { | i | unroll [ i ] } . histogram * ( ret_shape + [ options ] ) end end
Compute histogram of this array
20,754
def lut ( table , options = { } ) if ( shape . first != 1 or dimension == 1 ) and table . dimension == 1 [ self ] . lut table , options else ( 0 ... shape . first ) . collect { | i | unroll [ i ] } . lut table , options end end
Perform element - wise lookup
20,755
def warp ( * field ) options = field . last . is_a? ( Hash ) ? field . pop : { } options = { :safe => true , :default => typecode . default } . merge options if options [ :safe ] if field . size > dimension raise "Number of arrays for warp (#{field.size}) is greater than the " + "number of dimensions of source (#{dimension})" end Hornetseye :: lazy do ( 0 ... field . size ) . collect { | i | ( field [ i ] >= 0 ) . and ( field [ i ] < shape [ i ] ) } . inject :and end . conditional Lut . new ( * ( field + [ self ] ) ) , options [ :default ] else field . lut self , :safe => false end end
Warp an array
20,756
def integral left = allocate block = Integral . new left , self if block . compilable? GCCFunction . run block else block . demand end left end
Compute integral image
20,757
def components ( options = { } ) if shape . any? { | x | x <= 1 } raise "Every dimension must be greater than 1 (shape was #{shape})" end options = { :target => UINT , :default => typecode . default } . merge options target = options [ :target ] default = options [ :default ] default = typecode . new default unless default . matched? left = Hornetseye :: MultiArray ( target , dimension ) . new * shape labels = Sequence . new target , size ; labels [ 0 ] = 0 rank = Sequence . uint size ; rank [ 0 ] = 0 n = Hornetseye :: Pointer ( INT ) . new ; n . store INT . new ( 0 ) block = Components . new left , self , default , target . new ( 0 ) , labels , rank , n if block . compilable? Hornetseye :: GCCFunction . run block else block . demand end labels = labels [ 0 .. n . demand . get ] left . lut labels . lut ( labels . histogram ( labels . size , :weight => target . new ( 1 ) ) . minor ( 1 ) . integral - 1 ) end
Perform connected component labeling
20,758
def mask ( m ) check_shape m left = MultiArray . new typecode , * ( shape . first ( dimension - m . dimension ) + [ m . size ] ) index = Hornetseye :: Pointer ( INT ) . new index . store INT . new ( 0 ) block = Mask . new left , self , m , index if block . compilable? GCCFunction . run block else block . demand end left [ 0 ... index [ ] ] . roll end
Select values from array using a mask
20,759
def unmask ( m , options = { } ) options = { :safe => true , :default => typecode . default } . merge options default = options [ :default ] default = typecode . new default unless default . matched? m . check_shape default if options [ :safe ] if m . to_ubyte . sum > shape . last raise "#{m.to_ubyte.sum} value(s) of the mask are true but the last " + "dimension of the array for unmasking only has #{shape.last} value(s)" end end left = Hornetseye :: MultiArray ( typecode , dimension - 1 + m . dimension ) . coercion ( default . typecode ) . new * ( shape [ 1 .. - 1 ] + m . shape ) index = Hornetseye :: Pointer ( INT ) . new index . store INT . new ( 0 ) block = Unmask . new left , self , m , index , default if block . compilable? GCCFunction . run block else block . demand end left end
Distribute values in a new array using a mask
20,760
def flip ( * dimensions ) field = ( 0 ... dimension ) . collect do | i | if dimensions . member? i Hornetseye :: lazy ( * shape ) { | * args | shape [ i ] - 1 - args [ i ] } else Hornetseye :: lazy ( * shape ) { | * args | args [ i ] } end end warp * ( field + [ :safe => false ] ) end
Mirror the array
20,761
def shift ( * offset ) if offset . size != dimension raise "#{offset.size} offset(s) were given but array has " + "#{dimension} dimension(s)" end retval = Hornetseye :: MultiArray ( typecode , dimension ) . new * shape target , source , open , close = [ ] , [ ] , [ ] , [ ] ( shape . size - 1 ) . step ( 0 , - 1 ) do | i | callcc do | pass | delta = offset [ i ] % shape [ i ] source [ i ] = 0 ... shape [ i ] - delta target [ i ] = delta ... shape [ i ] callcc do | c | open [ i ] = c pass . call end source [ i ] = shape [ i ] - delta ... shape [ i ] target [ i ] = 0 ... delta callcc do | c | open [ i ] = c pass . call end close [ i ] . call end end retval [ * target ] = self [ * source ] unless target . any? { | t | t . size == 0 } for i in 0 ... shape . size callcc do | c | close [ i ] = c open [ i ] . call end end retval end
Create array with shifted elements
20,762
def downsample ( * rate ) options = rate . last . is_a? ( Hash ) ? rate . pop : { } options = { :offset => rate . collect { | r | r - 1 } } . merge options offset = options [ :offset ] if rate . size != dimension raise "#{rate.size} sampling rate(s) given but array has " + "#{dimension} dimension(s)" end if offset . size != dimension raise "#{offset.size} sampling offset(s) given but array has " + "#{dimension} dimension(s)" end ret_shape = ( 0 ... dimension ) . collect do | i | ( shape [ i ] + rate [ i ] - 1 - offset [ i ] ) . div rate [ i ] end field = ( 0 ... dimension ) . collect do | i | Hornetseye :: lazy ( * ret_shape ) { | * args | args [ i ] * rate [ i ] + offset [ i ] } end warp * ( field + [ :safe => false ] ) end
Downsampling of arrays
20,763
def signatures ( transaction , names : [ :primary ] ) transaction . inputs . map do | input | path = input . output . metadata [ :wallet_path ] node = self . path ( path ) sig_hash = transaction . sig_hash ( input , node . script ) node . signatures ( sig_hash , names : names ) end end
Takes a Transaction ready to be signed .
20,764
def authorize ( transaction , * signers ) transaction . set_script_sigs * signers do | input , * sig_dicts | node = self . path ( input . output . metadata [ :wallet_path ] ) signatures = combine_signatures ( * sig_dicts ) node . script_sig ( signatures ) end transaction end
Takes a Transaction and any number of Arrays of signature dictionaries . Each sig_dict in an Array corresponds to the Input with the same index .
20,765
def combine_signatures ( * sig_dicts ) combined = { } sig_dicts . each do | sig_dict | sig_dict . each do | tree , signature | decoded_sig = decode_base58 ( signature ) low_s_der_sig = Bitcoin :: Script . is_low_der_signature? ( decoded_sig ) ? decoded_sig : Bitcoin :: OpenSSL_EC . signature_to_low_s ( decoded_sig ) combined [ tree ] = Bitcoin :: OpenSSL_EC . repack_der_signature ( low_s_der_sig ) end end combined . sort_by { | tree , value | tree } . map { | tree , sig | sig } end
Takes any number of signature dictionaries which are Hashes where the keys are tree names and the values are base58 - encoded signatures for a single input .
20,766
def evaluable? ! lambda? && ! aop? && ( ! args || args . all? { | a | Evaller . evaluable? a } ) && ( ! custom_target? || Evaller . evaluable? ( custom_target? ) ) end
def delegatable? !aop? && !custom_target? && !all? && !chain? && !args && !lambda? end
20,767
def fetch ( ) url = "http://www.gog.com/" page = Net :: HTTP . get ( URI ( url ) ) @data = JSON . parse ( page [ / / , 1 ] ) end
Fetches raw data from source .
20,768
def parse ( data ) items = [ ] data [ "on_sale" ] . each do | item | sale_item = SaleItem . new ( get_title ( item ) , get_current_price ( item ) , get_original_price ( item ) , get_discount_percentage ( item ) , get_discount_amount ( item ) ) if @type . nil? items . push ( sale_item ) else if ( @type == "games" && is_game? ( item ) ) items . push ( sale_item ) end if ( @type == "movies" && is_movie? ( item ) ) items . push ( sale_item ) end end end unless @limit . nil? items . take ( @limit ) else items end end
Parses raw data and returns sale items .
20,769
def choose_hypothesis total = 0 roll = Kernel . rand ( total_weight ) + 1 hypothesis = nil hypotheses . each do | h | if roll <= ( total += h . weight ) hypothesis ||= h end end hypothesis ||= hypotheses . first return hypothesis end
Returns a random hypothesis with weighted probability
20,770
def same_structure? ( experiment ) return nil if name . to_sym != experiment . name . to_sym return nil if goal_hash . keys != experiment . goal_hash . keys return nil if hypothesis_hash . keys != experiment . hypothesis_hash . keys return experiment end
Returns true if the experiment has the same name goals and hypotheses as this one
20,771
def current? output_mapping . each do | file , format | return false if outofdate? ( file , * dnote_session . files ) end "DNotes are current (#{output})" end
Check the output file and see if they are older than the input files .
20,772
def document session = dnote_session output_mapping . each do | file , format | dir = File . dirname ( file ) mkdir_p ( dir ) unless File . directory? ( dir ) session . output = file session . format = format session . run report "Updated #{file.sub(Dir.pwd+'/','')}" end end
Generate notes documents .
20,773
def reset output . each do | file , format | if File . exist? ( file ) utime ( 0 , 0 , file ) report "Marked #{file} as out-of-date." end end end
Reset output files marking them as out - of - date .
20,774
def purge output . each do | file , format | if File . exist? ( file ) rm ( file ) report "Removed #{file}" end end end
Remove output files .
20,775
def output_mapping @output_mapping ||= ( hash = { } case output when Array output . each do | path | hash [ path ] = format ( path ) end when String hash [ output ] = format ( output ) when Hash hash = output end hash ) end
Convert output into a hash of file = > format .
20,776
def format ( file ) type = File . extname ( file ) . sub ( '.' , '' ) type = DEFAULT_FORMAT if type . empty? type end
The format of the file based on the extension . If the file has no extension then the value of DEFAULT_FORMAT is returned .
20,777
def dnote_session :: DNote :: Session . new do | s | s . paths = files s . exclude = exclude s . ignore = ignore s . labels = labels s . title = title s . context = lines s . dryrun = trial? end end
DNote Session instance .
20,778
def get ( path , query = nil , headers = { } ) response = execute :get , path , query , headers hash = JSON . parse response . body end
Raw HTTP methods
20,779
def request http_segments = @segments . clone @params . each do | key , value | http_segments [ key ] = value end uri = URI :: HTTP . build ( :host => HOST , :path => @action_path , :query => URI . encode_www_form ( http_segments ) ) . to_s result = JSON . parse ( HTTParty . get ( uri ) . parsed_response ) Baidumap :: Response . new ( result , self ) end
send http request
20,780
def bind ( param , target ) raise ScopeError unless scope . include? target @_params . fetch ( param ) . bind target end
Binds a parameter to a target value .
20,781
def inspect format INSPECT_FORMAT , name : self . class . name , object_id : object_id , params : params_with_types , type : Value . canonicalize ( @_value . class ) end
Produces a readable string representation of the parameterized object .
20,782
def each_parameterized return to_enum ( __callee__ ) unless block_given? @_params . each do | _ , param | next if param . constant? target = param . target yield target if target . is_a? Parameterized end end
Iterates over the parameterized objects currently bound to the parameters .
20,783
def create_token ( credential , opts = { } ) data , _status_code , _headers = create_token_with_http_info ( credential , opts ) return data end
Creates a new token
20,784
def to_h { enable_db_auth : enable_db_auth? , enable_ldap_auth : enable_ldap_auth? , ldap_host : ldap_host . to_s , ldap_port : ldap_port . to_s . to_i , ldap_ssl : ldap_ssl? , ldap_base_dn : ldap_base_dn . to_s , ldap_browse_user : ldap_browse_user . to_s , ldap_browse_password : ldap_browse_password . to_s , ldap_auto_activate : ldap_auto_activate? , ldap_system_admin_groups : ldap_system_admin_groups . to_s , } end
Converts the configuration to a hash .
20,785
def send_to receiver , publicly : true if publicly receiver . public_send symbol , * args , & block else receiver . send symbol , * args , & block end end
Send this instance to a receiver object .
20,786
def logger = logger Util :: Logger . loggers . delete ( self . logger . resource ) if self . logger if logger . is_a? ( Util :: Logger ) @logger = logger else @logger = Util :: Logger . new ( logger ) end end
Set current object logger instance
20,787
def ui = ui if ui . is_a? ( Util :: Console ) @ui = ui else @ui = Util :: Console . new ( ui ) end end
Set current object console instance
20,788
def ui_group ( resource , color = :cyan ) ui_resource = ui . resource ui . resource = Util :: Console . colorize ( resource , color ) yield ( ui ) ensure ui . resource = ui_resource end
Contextualize console operations in a code block with a given resource name .
20,789
def log ( part , msg , verbose = false , & block ) if ! verbose || verbose && self . project . options [ :verbose ] self . project . shell . say "\033[37m#{part.class.to_s}\033[0m" + " : " + msg . to_s , nil , true end if block_given? begin self . project . shell . padding = self . project . shell . padding + 1 yield ensure self . project . shell . padding = self . project . shell . padding - 1 end end end
Write out a log message
20,790
def validate_stack! mockup_options = { } relativizer_options = { } run_relativizer = true if @extractor_options mockup_options = { :env => @extractor_options [ :env ] } relativizer_options = { :url_attributes => @extractor_options [ :url_attributes ] } run_relativizer = @extractor_options [ :url_relativize ] end unless @stack . find { | ( processor , options ) | processor . class == HtmlMockup :: Release :: Processors :: Mockup } @stack . unshift ( [ HtmlMockup :: Release :: Processors :: UrlRelativizer . new , relativizer_options ] ) @stack . unshift ( [ HtmlMockup :: Release :: Processors :: Mockup . new , mockup_options ] ) end end
Checks if deprecated extractor options have been set Checks if the mockup will be runned
20,791
def delete ( item ) original_length = @length k = 1 while k <= @length if @queue [ k ] == item swap ( k , @length ) @length -= 1 sink ( k ) @queue . pop else k += 1 end end @length != original_length end
Deletes all items from self that are equal to item .
20,792
def sink ( k ) while ( j = ( 2 * k ) ) <= @length do j += 1 if j < @length && ! ordered? ( j , j + 1 ) break if ordered? ( k , j ) swap ( k , j ) k = j end end
Percolate down to maintain heap invariant .
20,793
def swim ( k ) while k > 1 && ! ordered? ( k / 2 , k ) do swap ( k , k / 2 ) k = k / 2 end end
Percolate up to maintain heap invariant .
20,794
def add ( obj , params = { } ) text = obj . to_s params = { :width => style . width , :align => style . align } . merge! params if params [ :width ] width = params [ :width ] words = text . gsub ( $/ , ' ' ) . split ( ' ' ) unless params [ :raw ] words ||= [ text ] buff = '' words . each do | word | if buff . size + word . size >= width and not buff . empty? _add_ buff , params buff = '' end buff << ' ' unless buff . empty? buff << word end unless buff . empty? _add_ buff , params end else text . each_line do | line | _add_ line , params end end end
Adds a line text to this box
20,795
def separator ( params = { } ) params = style . separator . merge params params [ :width ] ||= style . width raise Exception :: new ( 'Define a width for using separators' ) unless params [ :width ] line = fill ( params [ :pattern ] , params [ :width ] ) params [ :width ] = style . width add line , params end
Adds a line separator .
20,796
def render content = output_capture ( @block ) do instance_exec ( * @args , & @block ) end content_wrapped = output_capture ( ) { wrap ( content ) } output_concat content_wrapped end
Renders output to the template or returns it as a string .
20,797
def app_instance_name @app_instance_name ||= begin yaml = Rails . root . join ( 'config' , 'instance.yml' ) if File . exist? ( yaml ) yaml = ( YAML . load ( ERB . new ( File . read ( yaml ) ) . result ) || { } ) . symbolize_keys yaml [ :name ] . blank? ? 'default' : yaml [ :name ] else 'default' end end end
Gets the application instance name .
20,798
def restart_pending? return false unless File . exist? ( restart_file ) request_time = File . mtime ( restart_file ) request_time > Incline . start_time end
Is a restart currently pending .
20,799
def request_restart! Incline :: Log :: info 'Requesting an application restart.' FileUtils . touch restart_file File . mtime restart_file end
Updates the restart file to indicate we want to restart the web app .