idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
6,200
def resource_specific ( responses , resource ) logger . verbose ( "Looking through #{responses.size} matching cache " "entries for resource #{resource}." ) responses . select { | response | response . resource == resource } . map ( & :token_response ) . first end
Searches a list of CachedTokenResponses for one that matches the resource .
6,201
def update_refresh_tokens ( mrrt ) fail ArgumentError , 'Token must contain an MRRT.' unless mrrt . mrrt? @token_cache . find . each do | entry | entry . refresh_token = mrrt . refresh_token if mrrt . can_refresh? ( entry ) end end
Updates the refresh tokens of all tokens in the cache that match a given MRRT .
6,202
def validate ( entries ) logger . verbose ( "Validating #{entries.size} possible cache matches." ) valid_entries = entries . group_by ( & :validate ) @token_cache . remove ( valid_entries [ false ] || [ ] ) valid_entries [ true ] || [ ] end
Checks if an array of current cache entries are still valid attempts to refresh those that have expired and discards those that cannot be .
6,203
def to_json ( _ = nil ) JSON . unparse ( authority : [ authority . host , authority . tenant ] , client_id : client_id , token_response : token_response ) end
Constructs a new CachedTokenResponse .
6,204
def can_refresh? ( other ) mrrt? && ( authority == other . authority ) && ( user_info == other . user_info ) && ( client_id == other . client_id ) end
Determines if self can be used to refresh other .
6,205
def validate ( expiration_buffer_sec = 0 ) return true if ( Time . now + expiration_buffer_sec ) . to_i < expires_on unless refresh_token logger . verbose ( 'Cached token is almost expired but no refresh token ' 'is available.' ) return false end logger . verbose ( 'Cached token is almost expired, attempting to refresh...
If the access token is within the expiration buffer of expiring an attempt will be made to retrieve a new token with the refresh token .
6,206
def refresh ( new_resource = resource ) token_response = TokenRequest . new ( authority , @client ) . get_with_refresh_token ( refresh_token , new_resource ) if token_response . instance_of? SuccessResponse token_response . parse_id_token ( id_token ) end token_response end
Attempts to refresh the access token for a given resource . Note that you can call this method with a different resource even if the token is not an MRRT but it will fail
6,207
def string_hash ( hash ) hash . map { | k , v | [ k . to_s , v . to_s ] } . to_h end
Converts every key and value of a hash to string .
6,208
def add ( entries ) entries = Array ( entries ) old_size = @entries . size @entries |= entries logger . verbose ( "Added #{entries.size - old_size} new entries to cache." ) end
Adds an array of objects to the cache .
6,209
def execute request = Net :: HTTP :: Post . new ( @endpoint_uri . path ) add_headers ( request ) request . body = URI . encode_www_form ( string_hash ( params ) ) TokenResponse . parse ( http ( @endpoint_uri ) . request ( request ) . body ) end
Requests and waits for a token from the endpoint .
6,210
def add_headers ( request ) return if Logging . correlation_id . nil? request . add_field ( CLIENT_REQUEST_ID . to_s , Logging . correlation_id ) request . add_field ( CLIENT_RETURN_CLIENT_REQUEST_ID . to_s , true ) end
Adds the necessary OAuth headers .
6,211
def authenticate! ( challenge , response , registration_public_key , registration_counter ) raise NoMatchingRequestError unless challenge == response . client_data . challenge raise ClientDataTypeError unless response . client_data . authentication? pem = U2F . public_key_pem ( registration_public_key ) raise Authentic...
Authenticate a response from the U2F device
6,212
def register! ( challenges , response ) challenges = [ challenges ] unless challenges . is_a? Array challenge = challenges . detect do | chg | chg == response . client_data . challenge end raise UnmatchedChallengeError unless challenge raise ClientDataTypeError unless response . client_data . registration? U2F . public...
Authenticate the response from the U2F device when registering
6,213
def verify ( app_id , public_key_pem ) data = [ :: U2F :: DIGEST . digest ( app_id ) , signature_data . byteslice ( 0 , 5 ) , :: U2F :: DIGEST . digest ( client_data_json ) ] . join public_key = OpenSSL :: PKey . read ( public_key_pem ) begin public_key . verify ( :: U2F :: DIGEST . new , signature , data ) rescue Open...
Verifies the response against an app id and the public key of the registered device
6,214
def verify ( app_id ) data = [ "\x00" , :: U2F :: DIGEST . digest ( app_id ) , :: U2F :: DIGEST . digest ( client_data_json ) , key_handle_raw , public_key_raw ] . join begin parsed_certificate . public_key . verify ( :: U2F :: DIGEST . new , signature , data ) rescue OpenSSL :: PKey :: PKeyError false end end
Verifies the registration data against the app id
6,215
def register_response ( challenge , error = false ) if error JSON . dump ( errorCode : 4 ) else client_data_json = client_data ( :: U2F :: ClientData :: REGISTRATION_TYP , challenge ) JSON . dump ( registrationData : reg_registration_data ( client_data_json ) , clientData : :: U2F . urlsafe_encode64 ( client_data_json ...
Initialize a new FakeU2F device for use in tests .
6,216
def sign_response ( challenge ) client_data_json = client_data ( :: U2F :: ClientData :: AUTHENTICATION_TYP , challenge ) JSON . dump ( clientData : :: U2F . urlsafe_encode64 ( client_data_json ) , keyHandle : :: U2F . urlsafe_encode64 ( key_handle_raw ) , signatureData : auth_signature_data ( client_data_json ) ) end
A SignResponse hash as returned by the u2f . sign JavaScript API .
6,217
def reg_registration_data ( client_data_json ) :: U2F . urlsafe_encode64 ( [ 5 , origin_public_key_raw , key_handle_raw . bytesize , key_handle_raw , cert_raw , reg_signature ( client_data_json ) ] . pack ( "CA65CA#{key_handle_raw.bytesize}A#{cert_raw.bytesize}A*" ) ) end
The registrationData field returns in a RegisterResponse Hash .
6,218
def reg_signature ( client_data_json ) payload = [ "\x00" , :: U2F :: DIGEST . digest ( app_id ) , :: U2F :: DIGEST . digest ( client_data_json ) , key_handle_raw , origin_public_key_raw ] . join cert_key . sign ( :: U2F :: DIGEST . new , payload ) end
The signature field of a registrationData field of a RegisterResponse .
6,219
def auth_signature ( client_data_json ) data = [ :: U2F :: DIGEST . digest ( app_id ) , 1 , counter , :: U2F :: DIGEST . digest ( client_data_json ) ] . pack ( 'A32CNA32' ) origin_key . sign ( :: U2F :: DIGEST . new , data ) end
The signature field of a signatureData field of a SignResponse Hash .
6,220
def client_data ( typ , challenge ) JSON . dump ( challenge : challenge , origin : app_id , typ : typ ) end
The clientData hash as returned by registration and authentication responses .
6,221
def cert @cert ||= OpenSSL :: X509 :: Certificate . new . tap do | c | c . subject = c . issuer = OpenSSL :: X509 :: Name . parse ( cert_subject ) c . not_before = Time . now c . not_after = Time . now + 365 * 24 * 60 * 60 c . public_key = cert_key c . serial = 0x1 c . version = 0x0 c . sign cert_key , :: U2F :: DIGEST...
The self - signed device attestation certificate .
6,222
def replace_on ( * types ) types . map do | type | self . class . send :define_method , "on_#{type}" do | node | if captures = match? ( node ) @match_index += 1 execute_replacement ( node , captures ) end super ( node ) end end end
Generate methods for all affected types .
6,223
def captures? ( fast = @fast ) case fast when Capture then true when Array then fast . any? ( & method ( :captures? ) ) when Find then captures? ( fast . token ) end end
Look recursively into
6,224
def find_captures ( fast = @fast ) return true if fast == @fast && ! captures? ( fast ) case fast when Capture then fast . captures when Array then fast . flat_map ( & method ( :find_captures ) ) . compact when Find then find_captures ( fast . token ) end end
Find search captures recursively .
6,225
def prepare_arguments ( expression , arguments ) case expression when Array expression . each do | item | prepare_arguments ( item , arguments ) end when Fast :: FindFromArgument expression . arguments = arguments when Fast :: Find prepare_arguments expression . token , arguments end end
Prepare arguments case the expression needs to bind extra arguments .
6,226
def ok_with ( combination ) @ok_experiments << combination return unless combination . is_a? ( Array ) combination . each do | element | @ok_experiments . delete ( element ) end end
Keep track of ok experiments depending on the current combination . It keep the combinations unique removing single replacements after the first round .
6,227
def run_partial_replacement_with ( combination ) content = partial_replace ( * combination ) experimental_file = experimental_filename ( combination ) File . open ( experimental_file , 'w+' ) { | f | f . puts content } raise 'No changes were made to the file.' if FileUtils . compare_file ( @file , experimental_file ) r...
Writes a new file with partial replacements based on the current combination . Raise error if no changes was made with the given combination indices .
6,228
def call probability = 1.0 graders . each do | lambda | instance = lambda . call ( description ) probability *= instance . call . to_f ** instance . weight end probability end
For given description computes probabilities returned by each graders by multipying them together .
6,229
def tableView ( _ , viewForHeaderInSection : index ) section = promotion_table_data . section ( index ) view = section [ :title_view ] view = section [ :title_view ] . new if section [ :title_view ] . respond_to? ( :new ) view . on_load if view . respond_to? ( :on_load ) view . title = section [ :title ] if view . resp...
Section header view methods
6,230
def webView ( in_web , shouldStartLoadWithRequest : in_request , navigationType : in_type ) if %w( http https ) . include? ( in_request . URL . scheme ) if self . external_links == true && in_type == UIWebViewNavigationTypeLinkClicked if defined? ( OpenInChromeController ) open_in_chrome in_request else open_in_safari ...
UIWebViewDelegate Methods - Camelcase
6,231
def splitViewController ( svc , willHideViewController : vc , withBarButtonItem : button , forPopoverController : _ ) button ||= self . displayModeButtonItem if self . respond_to? ( :displayModeButtonItem ) return unless button button . title = @pm_split_screen_button_title || vc . title svc . detail_screen . navigatio...
UISplitViewControllerDelegate methods iOS 7 and below
6,232
def splitViewController ( svc , willChangeToDisplayMode : display_mode ) vc = svc . viewControllers . first vc = vc . topViewController if vc . respond_to? ( :topViewController ) case display_mode when UISplitViewControllerDisplayModePrimaryHidden self . splitViewController ( svc , willHideViewController : vc , withBar...
iOS 8 and above
6,233
def closest_parent ( type , this_view = nil ) this_view ||= view_or_self . superview while this_view != nil do return this_view if this_view . is_a? type this_view = this_view . superview end nil end
iterate up the view hierarchy to find the parent element of type containing this view
6,234
def include? ( tod ) second = tod . to_i second += TimeOfDay :: NUM_SECONDS_IN_DAY if second < @range . first @range . cover? ( second ) end
Returns true if the time of day is inside the shift false otherwise .
6,235
def overlaps? ( other ) max_seconds = TimeOfDay :: NUM_SECONDS_IN_DAY a , b = [ self , other ] . map ( & :range ) . sort_by ( & :first ) op = a . exclude_end? ? :> : :>= return true if a . last . send ( op , b . first ) return false if ( a . last < max_seconds ) && ( b . last < max_seconds ) a = Range . new ( a . first...
Returns true if ranges overlap false otherwise .
6,236
def round ( round_sec = 1 ) down = self - ( self . to_i % round_sec ) up = down + round_sec difference_down = self - down difference_up = up - self if ( difference_down < difference_up ) return down else return up end end
Rounding to the given nearest number of seconds
6,237
def - ( other ) if other . instance_of? ( TimeOfDay ) TimeOfDay . from_second_of_day @second_of_day - other . second_of_day else TimeOfDay . from_second_of_day @second_of_day - other end end
Return a new TimeOfDay num_seconds less than self . It will wrap around at midnight .
6,238
def on ( date , time_zone = Tod :: TimeOfDay . time_zone ) time_zone . local date . year , date . month , date . day , @hour , @minute , @second end
Returns a Time instance on date using self as the time of day Optional time_zone will build time in that zone
6,239
def extract ( format , carrier ) case format when OpenTracing :: FORMAT_TEXT_MAP , OpenTracing :: FORMAT_BINARY , OpenTracing :: FORMAT_RACK return SpanContext :: NOOP_INSTANCE else warn 'Unknown extract format' nil end end
Extract a SpanContext in the given format from the given carrier .
6,240
def call return recipients unless mailable . respond_to? ( :conversation ) recipients . each_with_object ( [ ] ) do | recipient , array | array << recipient if mailable . conversation . has_subscriber? ( recipient ) end end
recipients can be filtered on a conversation basis
6,241
def generate sitemaps . group_by ( & :folder ) . each do | folder , sitemaps | index_path = "#{DynamicSitemaps.temp_path}/#{folder}/#{DynamicSitemaps.index_file_name}" if ! DynamicSitemaps . always_generate_index && sitemaps . count == 1 && sitemaps . first . files . count == 1 file_path = "#{DynamicSitemaps.temp_path}...
Array of sitemap results Initialize the class with an array of SitemapResult
6,242
def cpp_files_in ( some_dir ) raise ArgumentError , 'some_dir is not a Pathname' unless some_dir . is_a? Pathname return [ ] unless some_dir . exist? && some_dir . directory? real = some_dir . realpath files = Find . find ( real ) . map { | p | Pathname . new ( p ) } . reject ( & :directory? ) cpp = files . select { | ...
Get a list of all CPP source files in a directory and its subdirectories
6,243
def cpp_files_libraries ( aux_libraries ) arduino_library_src_dirs ( aux_libraries ) . map { | d | cpp_files_in ( d ) } . flatten . uniq end
CPP files that are part of the 3rd - party libraries we re including
6,244
def header_dirs real = @base_dir . realpath all_files = Find . find ( real ) . map { | f | Pathname . new ( f ) } . reject ( & :directory? ) unbundled = all_files . reject { | path | vendor_bundle? ( path ) } files = unbundled . select { | path | HPP_EXTENSIONS . include? ( path . extname . downcase ) } files . map ( &...
Find all directories in the project library that include C ++ header files
6,245
def run_gcc ( gcc_binary , * args , ** kwargs ) full_args = [ gcc_binary ] + args @last_cmd = " $ #{full_args.join(' ')}" ret = Host . run_and_capture ( * full_args , ** kwargs ) @last_err = ret [ :err ] @last_out = ret [ :out ] ret [ :success ] end
wrapper for the GCC command
6,246
def arduino_library_src_dirs ( aux_libraries ) subdirs = [ "" , "src" , "utility" ] all_aux_include_dirs_nested = aux_libraries . map do | libdir | subdirs . map { | subdir | Pathname . new ( @arduino_lib_dir ) + libdir + subdir } end all_aux_include_dirs_nested . flatten . select ( & :exist? ) . select ( & :directory?...
Arduino library directories containing sources
6,247
def include_args ( aux_libraries ) all_aux_include_dirs = arduino_library_src_dirs ( aux_libraries ) places = [ ARDUINO_HEADER_DIR , UNITTEST_HEADER_DIR ] + header_dirs + all_aux_include_dirs places . map { | d | "-I#{d}" } end
GCC command line arguments for including aux libraries
6,248
def execute error_preparing = prepare unless error_preparing . nil? @output . puts "Arduino force-install failed preparation: #{error_preparing}" return false end attempts = 0 loop do if File . exist? package_file @output . puts "Arduino package seems to have been downloaded already" if attempts . zero? break elsif att...
Forcibly install Arduino on linux from the web
6,249
def parse_pref_string ( arduino_output ) lines = arduino_output . split ( "\n" ) . select { | l | l . include? "=" } ret = lines . each_with_object ( { } ) do | e , acc | parts = e . split ( "=" , 2 ) acc [ parts [ 0 ] ] = parts [ 1 ] acc end ret end
Convert a preferences dump into a flat hash
6,250
def run_and_output ( * args , ** kwargs ) _wrap_run ( ( proc { | * a , ** k | Host . run_and_output ( * a , ** k ) } ) , * args , ** kwargs ) end
build and run the arduino command
6,251
def run_and_capture ( * args , ** kwargs ) ret = _wrap_run ( ( proc { | * a , ** k | Host . run_and_capture ( * a , ** k ) } ) , * args , ** kwargs ) @last_err = ret [ :err ] @last_out = ret [ :out ] ret end
run a command and capture its output
6,252
def install_boards ( boardfamily ) result = run_and_capture ( flag_install_boards , boardfamily ) already_installed = result [ :err ] . include? ( "Platform is already installed!" ) result [ :success ] || already_installed end
install a board by name
6,253
def _install_library ( library_name ) result = run_and_capture ( flag_install_library , library_name ) already_installed = result [ :err ] . include? ( "Library is already installed: #{library_name}" ) success = result [ :success ] || already_installed @libraries_indexed = ( @libraries_indexed || success ) if library_n...
install a library by name
6,254
def use_board! ( boardname ) return true if use_board ( boardname ) boardfamily = boardname . split ( ":" ) [ 0 .. 1 ] . join ( ":" ) puts "Board '#{boardname}' not found; attempting to install '#{boardfamily}'" return false unless install_boards ( boardfamily ) use_board ( boardname ) end
use a particular board for compilation installing it if necessary
6,255
def install_local_library ( path ) src_path = path . realpath library_name = src_path . basename destination_path = library_path ( library_name ) if destination_path . exist? uhoh = "There is already a library '#{library_name}' in the library directory" return destination_path if destination_path == src_path if destina...
ensure that the given library is installed or symlinked as appropriate return the path of the prepared library or nil
6,256
def validate_data ( rootname , source , schema ) return nil if source . nil? good_data = { } source . each do | key , value | ksym = key . to_sym expected_type = schema [ ksym ] . class == Class ? schema [ ksym ] : Hash if ! schema . include? ( ksym ) puts "Warning: unknown field '#{ksym}' under definition for #{rootna...
validate a data source according to a schema print out warnings for bad fields and return only the good ones
6,257
def load_yaml ( path ) yml = YAML . load_file ( path ) raise ConfigurationError , "The YAML file at #{path} failed to load" unless yml apply_configuration ( yml ) end
Load configuration yaml from a file
6,258
def apply_configuration ( yml ) if yml . include? ( "packages" ) yml [ "packages" ] . each do | k , v | valid_data = validate_data ( "packages" , v , PACKAGE_SCHEMA ) @package_info [ k ] = valid_data end end if yml . include? ( "platforms" ) yml [ "platforms" ] . each do | k , v | valid_data = validate_data ( "platform...
Load configuration from a hash
6,259
def with_config ( base_dir , val_when_no_match ) CONFIG_FILENAMES . each do | f | path = base_dir . nil? ? f : File . join ( base_dir , f ) return ( yield path ) if File . exist? ( path ) end val_when_no_match end
Get the config file at a given path if it exists and pass that to a block . Many config files may exist but only the first match is used
6,260
def from_example ( example_path ) base_dir = File . directory? ( example_path ) ? example_path : File . dirname ( example_path ) with_config ( base_dir , self ) { | path | with_override ( path ) } end
Produce a configuration override taken from an Arduino library example path handle either path to example file or example dir
6,261
def payment_service_for ( order , account , options = { } , & proc ) raise ArgumentError , "Missing block" unless block_given? integration_module = OffsitePayments :: integration ( options . delete ( :service ) . to_s ) service_class = integration_module . const_get ( 'Helper' ) form_options = options . delete ( :html ...
This helper allows the usage of different payment integrations through a single form helper . Payment integrations are the type of service where the user is redirected to the secure site of the service like Paypal or Chronopay .
6,262
def valid_sender? ( ip ) return true if OffsitePayments . mode == :test || production_ips . blank? production_ips . include? ( ip ) end
Check if the request comes from an official IP
6,263
def add_field ( name , value ) return if name . blank? || value . blank? @fields [ name . to_s ] = value . to_s end
Add an input in the form . Useful when gateway requires some uncommon fields not provided by the gem .
6,264
def []= ( name , value ) @column_keys << name @attrs [ to_key ( name ) ] = value define_accessor ( name ) unless respond_to? ( name ) end
Set the given attribute to value
6,265
def override_attributes! ( attrs = { } ) @column_keys = attrs . keys @attrs = HashWithIndifferentAccess . new ( Hash [ attrs . map { | k , v | [ to_key ( k ) , v ] } ] ) @attrs . map { | k , v | define_accessor ( k ) } end
Removes old and add new attributes for the record
6,266
def find ( id ) result = self . class . get ( worksheet_url + "/" + id ) . parsed_response check_and_raise_error ( result ) Record . new ( result_attributes ( result ) ) if result . present? && result [ "id" ] end
Returns record based given row id
6,267
def create ( record ) result = self . class . post ( worksheet_url , :body => { "fields" => record . fields } . to_json , :headers => { "Content-type" => "application/json" } ) . parsed_response check_and_raise_error ( result ) record . override_attributes! ( result_attributes ( result ) ) record end
Creates a record by posting to airtable
6,268
def update ( record ) result = self . class . put ( worksheet_url + "/" + record . id , :body => { "fields" => record . fields_for_update } . to_json , :headers => { "Content-type" => "application/json" } ) . parsed_response check_and_raise_error ( result ) record . override_attributes! ( result_attributes ( result ) )...
Replaces record in airtable based on id
6,269
def triu! ( k = 0 ) if ndim < 2 raise NArray :: ShapeError , "must be >= 2-dimensional array" end if contiguous? * shp , m , n = shape idx = tril_indices ( k - 1 ) reshape! ( * shp , m * n ) self [ false , idx ] = 0 reshape! ( * shp , m , n ) else store ( triu ( k ) ) end end
Upper triangular matrix . Fill the self elements below the k - th diagonal with zero .
6,270
def tril! ( k = 0 ) if ndim < 2 raise NArray :: ShapeError , "must be >= 2-dimensional array" end if contiguous? idx = triu_indices ( k + 1 ) * shp , m , n = shape reshape! ( * shp , m * n ) self [ false , idx ] = 0 reshape! ( * shp , m , n ) else store ( tril ( k ) ) end end
Lower triangular matrix . Fill the self elements above the k - th diagonal with zero .
6,271
def diag_indices ( k = 0 ) if ndim < 2 raise NArray :: ShapeError , "must be >= 2-dimensional array" end m , n = shape [ - 2 .. - 1 ] NArray . diag_indices ( m , n , k ) end
Return the k - th diagonal indices .
6,272
def diag ( k = 0 ) * shp , n = shape n += k . abs a = self . class . zeros ( * shp , n , n ) a . diagonal ( k ) . store ( self ) a end
Return a matrix whose diagonal is constructed by self along the last axis .
6,273
def trace ( offset = nil , axis = nil , nan : false ) diagonal ( offset , axis ) . sum ( nan : nan , axis : - 1 ) end
Return the sum along diagonals of the array .
6,274
def dot ( b ) t = self . class :: UPCAST [ b . class ] if defined? ( Linalg ) && [ SFloat , DFloat , SComplex , DComplex ] . include? ( t ) Linalg . dot ( self , b ) else b = self . class . asarray ( b ) case b . ndim when 1 mulsum ( b , axis : - 1 ) else case ndim when 0 b . mulsum ( self , axis : - 2 ) when 1 self [ ...
Dot product of two arrays .
6,275
def kron ( b ) b = NArray . cast ( b ) nda = ndim ndb = b . ndim shpa = shape shpb = b . shape adim = [ :new ] * ( 2 * [ ndb - nda , 0 ] . max ) + [ true , :new ] * nda bdim = [ :new ] * ( 2 * [ nda - ndb , 0 ] . max ) + [ :new , true ] * ndb shpr = ( - [ nda , ndb ] . max .. - 1 ) . map { | i | ( shpa [ i ] || 1 ) * (...
Kronecker product of two arrays .
6,276
def pending_collaborations ( fields : [ ] ) query = build_fields_query ( fields , COLLABORATION_FIELDS_QUERY ) query [ :status ] = :pending pending_collaborations , response = get ( COLLABORATIONS_URI , query : query ) pending_collaborations [ 'entries' ] end
these are pending collaborations for the current user ; use the As - User Header to request for different users
6,277
def redirect ( path , options = { } , & endpoint ) destination_path = @router . find ( options ) get ( path ) . redirect ( destination_path , options [ :code ] || 301 ) . tap do | route | route . dest = Hanami :: Routing :: RedirectEndpoint . new ( destination_path , route . dest ) end end
Defines an HTTP redirect
6,278
def recognize ( env , options = { } , params = nil ) require 'hanami/routing/recognized_route' env = env_for ( env , options , params ) responses , _ = * @router . recognize ( env ) Routing :: RecognizedRoute . new ( responses . nil? ? responses : responses . first , env , @router ) end
Recognize the given env path or name and return a route for testing inspection .
6,279
def env_for ( env , options = { } , params = nil ) env = case env when String Rack :: MockRequest . env_for ( env , options ) when Symbol begin url = path ( env , params || options ) return env_for ( url , options ) rescue Hanami :: Routing :: InvalidRouteException { } end else env end end
Fabricate Rack env for the given Rack env path or named route
6,280
def user_preferred_languages return [ ] if header . to_s . strip . empty? @user_preferred_languages ||= begin header . to_s . gsub ( / \s / , '' ) . split ( ',' ) . map do | language | locale , quality = language . split ( ';q=' ) raise ArgumentError , 'Not correctly formatted' unless locale =~ / \- \* /i locale = loca...
Returns a sorted array based on user preference in HTTP_ACCEPT_LANGUAGE . Browsers send this HTTP header so don t think this is holy .
6,281
def compatible_language_from ( available_languages ) user_preferred_languages . map do | preferred | preferred = preferred . downcase preferred_language = preferred . split ( '-' , 2 ) . first available_languages . find do | available | available = available . to_s . downcase preferred == available || preferred_languag...
Returns the first of the user_preferred_languages that is compatible with the available locales . Ignores region .
6,282
def sanitize_available_locales ( available_languages ) available_languages . map do | available | available . to_s . split ( / / ) . reject { | part | part . start_with? ( "x" ) } . join ( "-" ) end end
Returns a supplied list of available locals without any extra application info that may be attached to the locale for storage in the application .
6,283
def language_region_compatible_from ( available_languages ) available_languages = sanitize_available_locales ( available_languages ) user_preferred_languages . map do | preferred | preferred = preferred . downcase preferred_language = preferred . split ( '-' , 2 ) . first lang_group = available_languages . select do | ...
Returns the first of the user preferred languages that is also found in available languages . Finds best fit by matching on primary language first and secondarily on region . If no matching region is found return the first language in the group matching that primary language .
6,284
def update ( other_hash ) if other_hash . is_a? Hash super ( other_hash ) else other_hash . to_hash . each_pair do | key , value | if block_given? value = yield ( key , value ) end self [ key ] = value end self end end
make it protected
6,285
def has_callouts? parser = REXML :: Parsers :: PullParser . new ( File . new ( @docbook_file ) ) while parser . has_next? el = parser . pull if el . start_element? and ( el [ 0 ] == "calloutlist" or el [ 0 ] == "co" ) return true end end return false end
Returns true if the document has code callouts
6,286
def evaluate_block ( & block ) delegator = self . class . new ( resolver , DecoratorChain . empty ) delegator . instance_eval ( & block ) end
Evaluate color block
6,287
def decorate ( string , * colors ) return string if blank? ( string ) || ! enabled || colors . empty? ansi_colors = lookup ( * colors . dup . uniq ) if eachline string . dup . split ( eachline ) . map! do | line | apply_codes ( line , ansi_colors ) end . join ( eachline ) else apply_codes ( string . dup , ansi_colors )...
Apply ANSI color to the given string .
6,288
def strip ( * strings ) modified = strings . map { | string | string . dup . gsub ( ANSI_COLOR_REGEXP , '' ) } modified . size == 1 ? modified [ 0 ] : modified end
Strip ANSI color codes from a string .
6,289
def code ( * colors ) attribute = [ ] colors . each do | color | value = ANSI :: ATTRIBUTES [ color ] || ALIASES [ color ] if value attribute << value else validate ( color ) end end attribute end
Return raw color code without embeding it into a string .
6,290
def alias_color ( alias_name , * colors ) validate ( * colors ) if ! ( alias_name . to_s =~ / \w / ) fail InvalidAliasNameError , "Invalid alias name `#{alias_name}`" elsif ANSI :: ATTRIBUTES [ alias_name ] fail InvalidAliasNameError , "Cannot alias standard color `#{alias_name}`" end ALIASES [ alias_name . to_sym ] = ...
Define a new colors alias
6,291
def import color_aliases = env [ 'PASTEL_COLORS_ALIASES' ] return unless color_aliases color_aliases . split ( ',' ) . each do | color_alias | new_color , old_colors = color_alias . split ( '=' ) if ! new_color || ! old_colors output . puts "Bad color mapping `#{color_alias}`" else color . alias_color ( new_color . to_...
Create alias importer
6,292
def draw_js_spreadsheet ( data , element_id = SecureRandom . uuid ) js = '' js << "\n function #{chart_function_name(element_id)}() {" js << "\n var query = new google.visualization.Query('#{data}');" js << "\n query.send(#{query_response_function_name(element_id)});" js << "\n }" js << "\n function #{query_response_...
Generates JavaScript function for rendering the chart when data is URL of the google spreadsheet
6,293
def to_js_full_script ( element_id = SecureRandom . uuid ) js = '' js << '\n<script type=\'text/javascript\'>' js << load_js ( element_id ) js << draw_js ( element_id ) js << '\n</script>' js end
Generates JavaScript and renders the Google Chart DataTable in the final HTML output
6,294
def draw_js ( element_id ) js = '' js << "\n function #{chart_function_name(element_id)}() {" js << "\n #{to_js}" js << "\n var table = new google.visualization.Table(" js << "document.getElementById('#{element_id}'));" js << add_listeners_js ( 'table' ) js << "\n table.draw(data_table, #{js_parameters(@optio...
Generates JavaScript function for rendering the google chart table .
6,295
def draw_js_spreadsheet ( data , element_id ) js = '' js << "\n function #{chart_function_name(element_id)}() {" js << "\n var query = new google.visualization.Query('#{data}');" js << "\n query.send(#{query_response_function_name(element_id)});" js << "\n }" js << "\n function #{query_response_function_name(elemen...
Generates JavaScript function for rendering the google chart table when data is URL of the google spreadsheet
6,296
def to_html_iruby ( placeholder = random_canvas_id ) @div_id = placeholder load_dependencies ( 'iruby' ) chart_hash_must_be_present script = high_chart_css ( placeholder ) script << high_chart_iruby ( extract_chart_class , placeholder , self ) script end
This method is not needed if to_html generates the same code . Here to_html generates the code with onload so there is need of high_chart_iruby which doesn t use onload in chart script .
6,297
def load_dependencies ( type ) dep_js = extract_dependencies if type == 'iruby' LazyHighCharts . init_iruby ( dep_js ) unless dep_js . nil? elsif type == 'web_frameworks' dep_js . nil? ? '' : LazyHighCharts . init_javascript ( dep_js ) end end
Loads the dependent mapdata and dependent modules of the chart
6,298
def export_iruby ( export_type = 'png' , file_name = 'chart' ) js = '' js << to_html_iruby js << extract_export_code_iruby ( @div_id , export_type , file_name ) IRuby . html js end
Exports chart to different formats in IRuby notebook
6,299
def extract_export_code ( placeholder = random_canvas_id , export_type = 'png' , file_name = 'chart' ) js = '' js << "\n <script>" js << "\n (function() {" js << "\n \tvar onload = window.onload;" js << "\n \twindow.onload = function(){" js << "\n \t\tif (typeof onload == 'function') onload();" js << "\n \t\tvar chartD...
Returns the script to export the chart in different formats for web frameworks