idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
8,400
def max_polyfill_size ( geo_polygon , resolution ) geo_polygon = geo_json_to_coordinates ( geo_polygon ) if geo_polygon . is_a? ( String ) Bindings :: Private . max_polyfill_size ( build_polygon ( geo_polygon ) , resolution ) end
Derive the maximum number of H3 indexes that could be returned from the input .
8,401
def polyfill ( geo_polygon , resolution ) geo_polygon = geo_json_to_coordinates ( geo_polygon ) if geo_polygon . is_a? ( String ) max_size = max_polyfill_size ( geo_polygon , resolution ) out = H3Indexes . of_size ( max_size ) Bindings :: Private . polyfill ( build_polygon ( geo_polygon ) , resolution , out ) out . rea...
Derive a list of H3 indexes that fall within a given geo polygon structure .
8,402
def h3_set_to_linked_geo ( h3_indexes ) h3_set = H3Indexes . with_contents ( h3_indexes ) linked_geo_polygon = LinkedGeoPolygon . new Bindings :: Private . h3_set_to_linked_geo ( h3_set , h3_indexes . size , linked_geo_polygon ) extract_linked_geo_polygon ( linked_geo_polygon ) . first ensure Bindings :: Private . dest...
Derive a nested array of coordinates from a list of H3 indexes .
8,403
def geo_to_h3 ( coords , resolution ) raise ArgumentError unless coords . is_a? ( Array ) && coords . count == 2 lat , lon = coords if lat > 90 || lat < - 90 || lon > 180 || lon < - 180 raise ( ArgumentError , "Invalid coordinates" ) end coords = GeoCoord . new coords [ :lat ] = degs_to_rads ( lat ) coords [ :lon ] = d...
Derive H3 index for the given set of coordinates .
8,404
def h3_to_geo ( h3_index ) coords = GeoCoord . new Bindings :: Private . h3_to_geo ( h3_index , coords ) [ rads_to_degs ( coords [ :lat ] ) , rads_to_degs ( coords [ :lon ] ) ] end
Derive coordinates for a given H3 index .
8,405
def h3_to_geo_boundary ( h3_index ) geo_boundary = GeoBoundary . new Bindings :: Private . h3_to_geo_boundary ( h3_index , geo_boundary ) geo_boundary [ :verts ] . take ( geo_boundary [ :num_verts ] ) . map do | d | [ rads_to_degs ( d [ :lat ] ) , rads_to_degs ( d [ :lon ] ) ] end end
Derive the geographical boundary as coordinates for a given H3 index .
8,406
def h3_indexes_from_unidirectional_edge ( edge ) max_hexagons = 2 out = H3Indexes . of_size ( max_hexagons ) Bindings :: Private . h3_indexes_from_unidirectional_edge ( edge , out ) out . read end
Derive origin and destination H3 indexes from edge .
8,407
def h3_unidirectional_edges_from_hexagon ( origin ) max_edges = 6 out = H3Indexes . of_size ( max_edges ) Bindings :: Private . h3_unidirectional_edges_from_hexagon ( origin , out ) out . read end
Derive unidirectional edges for a H3 index .
8,408
def h3_unidirectional_edge_boundary ( edge ) geo_boundary = GeoBoundary . new Bindings :: Private . h3_unidirectional_edge_boundary ( edge , geo_boundary ) geo_boundary [ :verts ] . take ( geo_boundary [ :num_verts ] ) . map do | d | [ rads_to_degs ( d [ :lat ] ) , rads_to_degs ( d [ :lon ] ) ] end end
Derive coordinates for edge boundary .
8,409
def hex_ring ( origin , k ) max_hexagons = max_hex_ring_size ( k ) out = H3Indexes . of_size ( max_hexagons ) pentagonal_distortion = Bindings :: Private . hex_ring ( origin , k , out ) raise ( ArgumentError , "The hex ring contains a pentagon" ) if pentagonal_distortion out . read end
Derives the hollow hexagonal ring centered at origin with sides of length k .
8,410
def hex_ranges ( h3_set , k , grouped : true ) h3_range_indexes = hex_ranges_ungrouped ( h3_set , k ) return h3_range_indexes unless grouped h3_range_indexes . each_slice ( max_kring_size ( k ) ) . each_with_object ( { } ) do | indexes , out | h3_index = indexes . first out [ h3_index ] = k_rings_for_hex_range ( indexe...
Derives H3 indexes within k distance for each H3 index in the set .
8,411
def k_ring_distances ( origin , k ) max_out_size = max_kring_size ( k ) out = H3Indexes . of_size ( max_out_size ) distances = FFI :: MemoryPointer . new ( :int , max_out_size ) Bindings :: Private . k_ring_distances ( origin , k , out , distances ) hexagons = out . read distances = distances . read_array_of_int ( max_...
Derives the k - ring for the given origin at k distance sub - grouped by distance .
8,412
def h3_to_string ( h3_index ) h3_str = FFI :: MemoryPointer . new ( :char , H3_TO_STR_BUF_SIZE ) Bindings :: Private . h3_to_string ( h3_index , h3_str , H3_TO_STR_BUF_SIZE ) h3_str . read_string end
Derives the hexadecimal string representation for a given H3 index .
8,413
def geo_json_to_coordinates ( input ) geom = RGeo :: GeoJSON . decode ( input ) coordinates = fetch_coordinates ( geom ) swap_lat_lon ( coordinates ) || failed_to_parse! rescue JSON :: ParserError failed_to_parse! end
Convert a GeoJSON document to a nested array of coordinates .
8,414
def coordinates_to_geo_json ( coordinates ) coordinates = swap_lat_lon ( coordinates ) outer_coords , * inner_coords = coordinates factory = RGeo :: Cartesian . simple_factory exterior = factory . linear_ring ( outer_coords . map { | lon , lat | factory . point ( lon , lat ) } ) interior_rings = inner_coords . map do |...
Convert a nested array of coordinates to a GeoJSON document
8,415
def h3_to_children ( h3_index , child_resolution ) max_children = max_h3_to_children_size ( h3_index , child_resolution ) out = H3Indexes . of_size ( max_children ) Bindings :: Private . h3_to_children ( h3_index , child_resolution , out ) out . read end
Derive child hexagons contained within the hexagon at the given H3 index .
8,416
def max_uncompact_size ( compacted_set , resolution ) h3_set = H3Indexes . with_contents ( compacted_set ) size = Bindings :: Private . max_uncompact_size ( h3_set , compacted_set . size , resolution ) raise ( ArgumentError , "Couldn't estimate size. Invalid resolution?" ) if size . negative? size end
Find the maximum uncompacted size of the given set of H3 indexes .
8,417
def compact ( h3_set ) h3_set = H3Indexes . with_contents ( h3_set ) out = H3Indexes . of_size ( h3_set . size ) failure = Bindings :: Private . compact ( h3_set , out , out . size ) raise "Couldn't compact given indexes" if failure out . read end
Compact a set of H3 indexes as best as possible .
8,418
def uncompact ( compacted_set , resolution ) max_size = max_uncompact_size ( compacted_set , resolution ) out = H3Indexes . of_size ( max_size ) h3_set = H3Indexes . with_contents ( compacted_set ) failure = Bindings :: Private . uncompact ( h3_set , compacted_set . size , out , max_size , resolution ) raise "Couldn't ...
Uncompact a set of H3 indexes to the given resolution .
8,419
def to ( target , options = { } ) conversion = conversions [ source || detect ( object , false ) , detect ( target ) ] conversion . call ( object , options ) end
Runs a given conversion
8,420
def detect ( object , symbol_as_object = true ) case object when TrueClass , FalseClass then :boolean when Integer then :integer when Class then object . name . downcase else if object . is_a? ( Symbol ) && symbol_as_object object else object . class . name . downcase end end end
Detect object type and coerce into known key type
8,421
def load ArrayConverters . load ( self ) BooleanConverters . load ( self ) DateTimeConverters . load ( self ) NumericConverters . load ( self ) RangeConverters . load ( self ) end
Creates a new conversions map
8,422
def register ( converter = nil , & block ) converter ||= Converter . create ( & block ) key = generate_key ( converter ) converter = add_config ( converter , @configuration ) return false if converter_map . key? ( key ) converter_map [ key ] = converter true end
Register a converter
8,423
def add_config ( converter , config ) converter . instance_exec ( :" " ) do | var | instance_variable_set ( var , config ) end converter end
Inject config into converter
8,424
def [] ( index_or_column ) case index_or_column when Integer super when String , Symbol map { | h | h [ index_or_column . to_s ] } else fail ArgumentError , 'Expected integer or string/symbol index' ", got #{index_or_column.class}" end end
Allows access to one column or row .
8,425
def columns ( * names ) names . map! ( & :to_s ) DataTable . new ( map { | h | names . map { | n | [ n , h [ n ] ] } . to_h } ) end
Slice of a DataTable with only specified columns left .
8,426
def to_h keys . map { | k | [ k , map { | h | h [ k ] } ] } . to_h end
Represents DataTable as a column name = > all values in columns hash .
8,427
def copy_to ( _ , directory ) FileUtils . rm_rf ( directory ) if directory . exist? FileUtils . mkdir_p ( directory . parent ) FileUtils . ln_s ( @dir . expand_path , directory ) nil end
Copies the directory to the given other directory
8,428
def identify ( directory ) raw = json ( directory ) dependencies = raw [ 'dependencies' ] . to_h dependency_sources = raw [ 'dependency-sources' ] . to_h . merge ( @dependency_sources ) dependencies . map do | package , constraint | constraints = Utils . transform_constraint constraint type = if dependency_sources . ke...
Identifies dependencies from a directory
8,429
def uri_type ( url , branch ) uri = GitCloneUrl . parse ( url ) case uri when URI :: SshGit :: Generic Type :: Git ( Uri :: Ssh ( uri ) , branch ) when URI :: HTTP Type :: Git ( Uri :: Http ( uri ) , branch ) end end
Returns the type from the given arguments .
8,430
def json ( directory ) path = File . join ( directory , 'elm-package.json' ) JSON . parse ( File . read ( path ) ) rescue JSON :: ParserError warn "Invalid JSON in file: #{path.bold}" rescue Errno :: ENOENT warn "Could not find file: #{path.bold}" end
Returns the contents of the elm - package . json for the given directory .
8,431
def transform_constraint ( elm_constraint ) elm_constraint . gsub! ( / \s / , '' ) CONVERTERS . map { | regexp , prefix | [ elm_constraint . match ( regexp ) , prefix ] } . select { | ( match ) | match } . map { | ( match , prefix ) | "#{prefix} #{match[1]}" } . map { | constraint | Solve :: Constraint . new constraint...
Transform an elm constraint into a proper one .
8,432
def results Solve . it! ( @graph , initial_solve_constraints ) . map do | name , version | dep = @resolver . dependencies [ name ] dep . version = Semverse :: Version . new ( version ) dep end end
Returns the results of solving
8,433
def initial_solve_constraints @identifier . initial_dependencies . flat_map do | dependency | dependency . constraints . map do | constraint | [ dependency . name , constraint ] end end end
Returns the inital constraints
8,434
def resolve_dependency ( dependency ) @dependencies [ dependency . name ] ||= dependency dependency . source . versions ( dependency . constraints , @identifier . initial_elm_version , ! @options [ :skip_update ] , @options [ :only_update ] ) . each do | version | next if @graph . artifact? ( dependency . name , versio...
Resolves the dependencies of a dependency
8,435
def resolve_dependencies ( main , version ) dependencies = @identifier . identify ( main . source . fetch ( version ) ) artifact = @graph . artifact main . name , version dependencies . each do | dependency | dependency . constraints . each do | constraint | artifact . depends dependency . name , constraint end resolve...
Resolves the dependencies of a dependency and version
8,436
def fetch ( version ) ref = case @branch when Branch :: Just @branch . ref when Branch :: Nothing case version when String version else version . to_simple end end repository . checkout ref end
Downloads the version into a temporary directory
8,437
def copy_to ( version , directory ) FileUtils . rm_rf ( directory ) if directory . exist? FileUtils . mkdir_p directory FileUtils . cp_r ( "#{fetch(version).path}/." , directory ) FileUtils . rm_rf ( File . join ( directory , '.git' ) ) nil end
Copies the version into the given directory
8,438
def versions ( constraints , elm_version , should_update , only_update ) if repository . cloned? && ! repository . fetched && should_update && ( ! only_update || only_update == package_name ) Logger . arrow "Getting updates for: #{package_name.bold}" repository . fetch end case @branch when Branch :: Just [ identifier ...
Returns the available versions for a repository
8,439
def matching_versions ( constraints , elm_version ) repository . versions . select do | version | elm_version_of ( version . to_s ) == elm_version && constraints . all? { | constraint | constraint . satisfies? ( version ) } end . sort . reverse end
Returns the matchign versions for a repository for the given constraints
8,440
def log_dependency ( dependency ) log = "#{dependency.name} - " log += dependency . source . to_log . to_s log += " (#{dependency.version.to_simple})" Logger . dot log nil end
Logs the dependency with a dot
8,441
def versions @versions ||= repo . tags . map ( & :name ) . select { | tag | tag =~ / \. \. / } . map { | tag | Semverse :: Version . try_new tag } . compact end
Returns the versions of the repository
8,442
def enum_option_pairs ( record , enum , encode_as_value = false ) reader = enum . to_s . pluralize record = record . class unless record . respond_to? ( reader ) record . send ( reader ) . map { | key , value | name = record . human_enum_name ( enum , key ) if record . respond_to? ( :human_enum_name ) name ||= translat...
A helper to build forms with Rails form builder built to be used with f . select helper .
8,443
def array_to_ranges ( ar ) prev = ar [ 0 ] ranges = ar . slice_before do | e | prev2 = prev prev = e prev2 + 1 != e end . map { | a | a [ 0 ] .. a [ - 1 ] } ranges end
converts an array of integers into array of ranges
8,444
def find_local_alignment ( hit , prediction , hsp ) hit_local = hit . raw_sequence [ hsp . hit_from - 1 .. hsp . hit_to - 1 ] query_local = prediction . raw_sequence [ hsp . match_query_from - 1 .. hsp . match_query_to - 1 ] if @type == :nucleotide s = Bio :: Sequence :: NA . new ( query_local ) query_local = s . trans...
Only run if the BLAST output does not contain hit alignmment
8,445
def print warn "Cluster: mean = #{mean}, density = #{density}" lengths . sort { | a , b | a <=> b } . each do | elem | warn "#{elem[0]}, #{elem[1]}" end warn '--------------------------' end
Prints the current cluster
8,446
def get_info_on_query_sequence ( seq_type = @config [ :type ] , index = @config [ :idx ] ) query = GeneValidator . extract_input_fasta_sequence ( index ) parse_query = query . scan ( / \n \n \n / ) [ 0 ] prediction = Query . new prediction . definition = parse_query [ 0 ] . delete ( "\n" ) prediction . identifier = pre...
get info about the query
8,447
def length_validation_scores ( validations , scores ) lcv = validations . select { | v | v . class == LengthClusterValidationOutput } lrv = validations . select { | v | v . class == LengthRankValidationOutput } if lcv . length == 1 && lrv . length == 1 score_lcv = ( lcv [ 0 ] . result == lcv [ 0 ] . expected ) score_lr...
Since there are two length validations it is necessary to adjust the scores accordingly
8,448
def turn_off_automated_sorting js_file = File . join ( @dirs [ :output_dir ] , 'html_files/js/gv.compiled.min.js' ) original_content = File . read ( js_file ) updated_content = original_content . gsub ( ',sortList:[[0,0]]' , '' ) File . open ( "#{script_file}.tmp" , 'w' ) { | f | f . puts updated_content } FileUtils . ...
By default on page load the results are automatically sorted by the index . However since the whole idea is that users would sort by JSON this is not wanted here .
8,449
def overview_html_hash ( evaluation , less ) data = [ @overview [ :scores ] . group_by { | a | a } . map do | k , vs | { 'key' : k , 'value' : vs . length , 'main' : false } end ] { data : data , type : :simplebars , aux1 : 10 , aux2 : '' , title : 'Overall GeneValidator Score Evaluation' , footer : '' , xtitle : 'Vali...
make the historgram with the resulted scores
8,450
def push_notifications pending = find_pending to_send = pending . map do | notification | notification_type . new notification . destinations , notification . data end pusher = build_pusher pusher . push to_send pending . each_with_index do | p , i | p . update_attributes! results : to_send [ i ] . results end end
This method will find all notifications owned by this app and push them .
8,451
def replace ( other_array ) original_target = load_target . dup other_array . each { | val | raise_on_type_mismatch! ( val ) } target_ids = reflection . options [ :target_ids ] owner [ target_ids ] = other_array . map ( & :id ) old_records = original_target - other_array old_records . each do | record | @target . delet...
full replace simplely
8,452
def concat ( * records ) load_target flatten_records = records . flatten flatten_records . each { | val | raise_on_type_mismatch! ( val ) } target_ids = reflection . options [ :target_ids ] owner [ target_ids ] ||= [ ] owner [ target_ids ] . concat ( flatten_records . map ( & :id ) ) flatten_records . each do | record ...
no need transaction
8,453
def association ( name ) association = association_instance_get ( name ) if association . nil? reflection = self . class . reflect_on_association ( name ) if reflection . options [ :active_model ] association = ActiveRecord :: Associations :: HasManyForActiveModelAssociation . new ( self , reflection ) else association...
use by association accessor
8,454
def choose validate_path search_paths_list = search_paths if search_paths_list . empty? puts "\nThere is no /schema[^\/]*.rb$/ in the directory #{@path}" exit end search_paths_list . each_with_index { | path , indx | puts "#{indx}. #{path}" } begin print "\nSelect a path to the target schema: " end while search_paths_l...
Return the chosen path
8,455
def load_config @config = YAML . safe_load ( ERB . new ( File . read ( config_path ) ) . result ) @queue_ahead = @config [ "queue_ahead" ] || Task :: DEFAULT_QUEUE_AHEAD_MINUTES @queue_name = @config [ "queue_name" ] || "default" @time_zone = @config [ "tz" ] || Time . zone . tzinfo . name @config . delete ( "queue_ahe...
Load the global scheduler config from the YAML file .
8,456
def queue_future_jobs tasks . each do | task | new_run_times = task . future_run_times - task . existing_run_times new_run_times . each do | time | SimpleScheduler :: FutureJob . set ( queue : @queue_name , wait_until : time ) . perform_later ( task . params , time . to_i ) end end end
Queue each of the future jobs into Sidekiq from the defined tasks .
8,457
def tasks @config . map do | task_name , options | task_params = options . symbolize_keys task_params [ :queue_ahead ] ||= @queue_ahead task_params [ :name ] = task_name task_params [ :tz ] ||= @time_zone Task . new ( task_params ) end end
The array of tasks loaded from the config YAML .
8,458
def existing_jobs @existing_jobs ||= SimpleScheduler :: Task . scheduled_set . select do | job | next unless job . display_class == "SimpleScheduler::FutureJob" task_params = job . display_args [ 0 ] . symbolize_keys task_params [ :class ] == job_class_name && task_params [ :name ] == name end . to_a end
Returns an array of existing jobs matching the job class of the task .
8,459
def future_run_times future_run_times = existing_run_times . dup last_run_time = future_run_times . last || at - frequency last_run_time = last_run_time . in_time_zone ( time_zone ) while future_run_times . length < 2 || minutes_queued_ahead ( last_run_time ) < queue_ahead last_run_time = frequency . from_now ( last_ru...
Returns an array Time objects for future run times based on the current time and the given minutes to look ahead .
8,460
def perform ( task_params , scheduled_time ) @task = Task . new ( task_params ) @scheduled_time = Time . at ( scheduled_time ) . in_time_zone ( @task . time_zone ) raise Expired if expired? queue_task end
Perform the future job as defined by the task .
8,461
def expire_duration split_duration = @task . expires_after . split ( "." ) duration = split_duration [ 0 ] . to_i duration_units = split_duration [ 1 ] duration . send ( duration_units ) end
The duration between the scheduled run time and actual run time that will cause the job to expire . Expired jobs will not be executed .
8,462
def expired? return false if @task . expires_after . blank? expire_duration . from_now ( @scheduled_time ) < Time . now . in_time_zone ( @task . time_zone ) end
Returns whether or not the job has expired based on the time between the scheduled run time and the current time .
8,463
def handle_expired_task ( exception ) exception . run_time = Time . now . in_time_zone ( @task . time_zone ) exception . scheduled_time = @scheduled_time exception . task = @task SimpleScheduler . expired_task_blocks . each do | block | block . call ( exception ) end end
Handle the expired task by passing the task and run time information to a block that can be creating in a Rails initializer file .
8,464
def queue_task if @task . job_class . instance_method ( :perform ) . arity . zero? @task . job_class . send ( perform_method ) else @task . job_class . send ( perform_method , @scheduled_time . to_i ) end end
Queue the task with the scheduled time if the job allows .
8,465
def parsed_time return @parsed_time if @parsed_time @parsed_time = parsed_day change_hour = next_hour if change_hour == 24 @parsed_time = 1 . day . from_now ( @parsed_time ) change_hour = 0 end @parsed_time = @parsed_time . change ( hour : change_hour , min : at_min ) @parsed_time += at_wday? ? 1 . week : 1 . day if no...
Returns the very first time a job should be run for the scheduled task .
8,466
def exchange_names ( * names ) @_exchange_names ||= [ ] @_exchange_names += names . flatten . map ( & :to_s ) if @_exchange_names . empty? return [ :: ActionSubscriber . config . default_exchange ] else return @_exchange_names . compact . uniq end end
Explicitly set the name of the exchange
8,467
def queue_name_for_method ( method_name ) return queue_names [ method_name ] if queue_names [ method_name ] queue_name = generate_queue_name ( method_name ) queue_for ( method_name , queue_name ) return queue_name end
Build the queue for a given method .
8,468
def routing_key_name_for_method ( method_name ) return routing_key_names [ method_name ] if routing_key_names [ method_name ] routing_key_name = generate_routing_key_name ( method_name ) routing_key_for ( method_name , routing_key_name ) return routing_key_name end
Build the routing_key for a given method .
8,469
def double return self if infinity? gamma = field . mod ( ( 3 * x * x + @group . param_a ) * field . inverse ( 2 * y ) ) new_x = field . mod ( gamma * gamma - 2 * x ) new_y = field . mod ( gamma * ( x - new_x ) - y ) self . class . new ( group , new_x , new_y ) end
Returns the point added to itself .
8,470
def multiply_by_scalar ( i ) raise ArgumentError , 'Scalar is not an integer.' if ! i . is_a? ( Integer ) raise ArgumentError , 'Scalar is negative.' if i < 0 result = group . infinity v = self while i > 0 result = result . add_to_point ( v ) if i . odd? v = v . double i >>= 1 end result end
Returns the point multiplied by a non - negative integer .
8,471
def square_roots ( n ) raise ArgumentError , "Not a member of the field: #{n}." if ! include? ( n ) case when prime == 2 then [ n ] when ( prime % 4 ) == 3 then square_roots_for_p_3_mod_4 ( n ) when ( prime % 8 ) == 5 then square_roots_for_p_5_mod_8 ( n ) else square_roots_default ( n ) end end
Finds all possible square roots of the given field element .
8,472
def write_header ( sample_frame_count ) extensible = @format . channels > 2 || ( @format . sample_format == :pcm && @format . bits_per_sample != 8 && @format . bits_per_sample != 16 ) || ( @format . channels == 1 && @format . speaker_mapping != [ :front_center ] ) || ( @format . channels == 2 && @format . speaker_mappi...
Internal Writes the RIFF chunk header format chunk and the header for the data chunk . After this method is called the file will be queued up and ready for writing actual sample data .
8,473
def obfuscate_id_default_spin alphabet = Array ( "a" .. "z" ) number = name . split ( "" ) . collect do | char | alphabet . index ( char ) end number . shift ( 12 ) . join . to_i end
Generate a default spin from the Model name This makes it easy to drop obfuscate_id onto any model and produce different obfuscated ids for different models
8,474
def handle! ( summary : , request : , stage : , errors : nil , exception : nil , ** opts ) documentation = Docs :: LinkBuilder . instance . for_request request Responses :: ValidationError . new ( summary : summary , errors : errors , exception : exception , documentation : documentation , ** opts ) end
Should return the Response to send back
8,475
def validate ( action , validate_body : false ) return if response_name == :validation_error unless ( response_definition = action . responses [ response_name ] ) raise Exceptions :: Validation , "Attempting to return a response with name #{response_name} " "but no response definition with that name can be found" end r...
Validates the response
8,476
def define ( key = nil , type = Attributor :: Struct , ** opts , & block ) if key . nil? && type != Attributor :: Struct raise Exceptions :: InvalidConfiguration . new ( "You cannot define the top level configuration with a non-Struct type. Got: #{type.inspect}" ) end case key when String , Symbol , NilClass top = key ...
You can define the configuration in different ways
8,477
def derive_content_type ( handler_name ) possible_values = if self . content_type . match 'text/plain' _ , content_type_attribute = self . headers_attribute && self . headers_attribute . attributes . find { | k , v | k . to_s =~ / /i } if content_type_attribute && content_type_attribute . options . key? ( :values ) con...
Determine an appropriate default content_type for this part given the preferred handler_name if possible .
8,478
def precomputed_header_keys_for_rack @precomputed_header_keys_for_rack ||= begin @headers . attributes . keys . each_with_object ( Hash . new ) do | key , hash | name = key . to_s name = "HTTP_#{name.gsub('-','_').upcase}" unless ( name == "CONTENT_TYPE" || name == "CONTENT_LENGTH" ) hash [ name ] = key end end end
Good optimization to avoid creating lots of strings and comparisons on a per - request basis . However this is hacky as it is rack - specific and does not really belong here
8,479
def derive_content_type ( example , handler_name ) if example . kind_of? Praxis :: Types :: MultipartArray return MediaTypeIdentifier . load ( example . content_type ) end _ , content_type_attribute = self . headers && self . headers . attributes . find { | k , v | k . to_s =~ / /i } if content_type_attribute && conten...
Determine the content_type to report for a given example using handler_name if possible .
8,480
def without_parameters if self . parameters . empty? self else MediaTypeIdentifier . load ( type : self . type , subtype : self . subtype , suffix : self . suffix ) end end
If parameters are empty return self ; otherwise return a new object consisting of this type minus parameters .
8,481
def validate_status! ( response ) return unless status if response . status != status raise Exceptions :: Validation . new ( "Invalid response code detected. Response %s dictates status of %s but this response is returning %s." % [ name , status . inspect , response . status . inspect ] ) end end
Validates Status code
8,482
def validate_location! ( response ) return if location . nil? || location === response . headers [ 'Location' ] raise Exceptions :: Validation . new ( "LOCATION does not match #{location.inspect}" ) end
Validates Location header
8,483
def validate_content_type! ( response ) return unless media_type response_content_type = response . content_type expected_content_type = Praxis :: MediaTypeIdentifier . load ( media_type . identifier ) unless expected_content_type . match ( response_content_type ) raise Exceptions :: Validation . new ( "Bad Content-Typ...
Validates Content - Type header and response media type
8,484
def validate_body! ( response ) return unless media_type return if media_type . kind_of? SimpleMediaType errors = self . media_type . validate ( self . media_type . load ( response . body ) ) if errors . any? message = "Invalid response body for #{media_type.identifier}." + "Errors: #{errors.inspect}" raise Exceptions ...
Validates response body
8,485
def load ( * paths ) paths . flatten . each do | path | window . load ( path . to_s ) end self end
Create new page containing given document .
8,486
def read_config ( io = nil ) unless io root_path = :: Middleman :: Application . root config_file_path = File . join ( root_path , ".s3_sync" ) return unless File . exists? ( config_file_path ) io = File . open ( config_file_path , "r" ) end config = ( YAML . load ( io ) || { } ) . symbolize_keys config . each do | key...
Read config options from an IO stream and set them on self . Defaults to reading from the . s3_sync file in the MM project root if it exists .
8,487
def strfcoord ( formatstr ) h = full_hash DIRECTIVES . reduce ( formatstr ) do | memo , ( from , to ) | memo . gsub ( from ) do to = to . call ( Regexp . last_match ) if to . is_a? ( Proc ) res = to % h res , carrymin = guard_seconds ( to , res ) h [ carrymin ] += 1 if carrymin res end end end
Formats coordinates according to directives in + formatstr + .
8,488
def read_attr ( attr_name , to_call = nil ) val = self [ attr_name ] val && to_call ? val . __send__ ( to_call ) : val end
Helper method to read an attribute
8,489
def write_attr ( attr_name , value , to_call = nil ) self [ attr_name ] = value && to_call ? value . __send__ ( to_call ) : value end
Helper method to write a value to an attribute
8,490
def namespace = ( namespaces ) case namespaces when Nokogiri :: XML :: Namespace super namespaces when String ns = self . add_namespace nil , namespaces super ns end end
Attach a namespace to the node
8,491
def default_property_value ( attr , value ) if value . is_a? ( TrueClass ) || value . is_a? ( FalseClass ) send ( "#{attr.to_sym}=" , value ) if send ( attr . to_sym ) . nil? else send ( "#{attr.to_sym}=" , send ( attr . to_sym ) . presence || value ) end end
Sets a default value for the property if not currently set .
8,492
def format_property_value ( attr , type ) return unless send ( attr . to_sym ) . present? case type . to_sym when :integer send ( "#{attr.to_sym}=" , send ( attr . to_sym ) . to_i ) when :float send ( "#{attr.to_sym}=" , send ( attr . to_sym ) . to_f ) when :boolean send ( "#{attr.to_sym}=" , ActiveModel :: Type :: Boo...
Converts the type of the property .
8,493
def nested_models model_entities = [ ] nested_attributes . each { | attr | model_entities << send ( attr . to_sym ) } if nested_attributes? model_entities . flatten end
For each attribute name in nested_attributes extract and return the nested model objects .
8,494
def assign_nested_attributes ( association_name , attributes , options = { } ) attributes = validate_attributes ( attributes ) association_name = association_name . to_sym send ( "#{association_name}=" , [ ] ) if send ( association_name ) . nil? attributes . each_value do | params | if params [ 'id' ] . blank? unless r...
Assigns the given nested child attributes .
8,495
def assign_to_or_mark_for_destruction ( record , attributes ) record . assign_attributes ( attributes . except ( * UNASSIGNABLE_KEYS ) ) record . mark_for_destruction if destroy_flag? ( attributes ) end
Updates an object with attributes or marks it for destruction if has_destroy_flag? .
8,496
def find_entity ( id_or_name , parent = nil ) key = CloudDatastore . dataset . key name , id_or_name key . parent = parent if parent . present? retry_on_exception { CloudDatastore . dataset . find key } end
Retrieves an entity by id or name and by an optional parent .
8,497
def all ( options = { } ) next_cursor = nil query = build_query ( options ) query_results = retry_on_exception { CloudDatastore . dataset . run query } if options [ :limit ] next_cursor = query_results . cursor if query_results . size == options [ :limit ] return from_entities ( query_results . all ) , next_cursor end ...
Queries entities from Cloud Datastore by named kind and using the provided options . When a limit option is provided queries up to the limit and returns results with a cursor .
8,498
def find_by ( args ) query = CloudDatastore . dataset . query name query . ancestor ( args [ :ancestor ] ) if args [ :ancestor ] query . limit ( 1 ) query . where ( args . keys [ 0 ] . to_s , '=' , args . values [ 0 ] ) query_results = retry_on_exception { CloudDatastore . dataset . run query } from_entity ( query_resu...
Finds the first entity matching the specified condition .
8,499
def query_sort ( query , options ) query . order ( options [ :order ] ) if options [ :order ] query . order ( options [ :desc_order ] , :desc ) if options [ :desc_order ] query end
Adds sorting to the results by a property name if included in the options .