idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
6,700
def mask ( s = "%n!%u@%h" ) s = s . gsub ( / / ) { case $1 when "n" @name when "u" self . user when "h" self . host when "r" self . realname when "a" self . authname end } Mask . new ( s ) end
Generates a mask for the user .
6,701
def monitor if @bot . irc . isupport [ "MONITOR" ] > 0 @bot . irc . send "MONITOR + #@name" else refresh @monitored_timer = Timer . new ( @bot , interval : 30 ) { refresh } @monitored_timer . start end @monitored = true end
Starts monitoring a user s online state by either using MONITOR or periodically running WHOIS .
6,702
def online = ( bool ) notify = self . __send__ ( "online?_unsynced" ) != bool && @monitored sync ( :online? , bool , true ) return unless notify if bool @bot . handlers . dispatch ( :online , nil , self ) else @bot . handlers . dispatch ( :offline , nil , self ) end end
Updates the user s online state and dispatch the correct event .
6,703
def start setup if connect @sasl_remaining_methods = @bot . config . sasl . mechanisms . reverse send_cap_ls send_login reading_thread = start_reading_thread sending_thread = start_sending_thread ping_thread = start_ping_thread reading_thread . join sending_thread . kill ping_thread . kill end end
Establish a connection .
6,704
def log ( messages , event = :debug , level = event ) return unless will_log? ( level ) @mutex . synchronize do Array ( messages ) . each do | message | message = format_general ( message ) message = format_message ( message , event ) next if message . nil? @output . puts message . encode ( "locale" , { :invalid => :re...
Logs a message .
6,705
def find_ensured ( name ) downcased_name = name . irc_downcase ( @bot . irc . isupport [ "CASEMAPPING" ] ) @mutex . synchronize do @cache [ downcased_name ] ||= Channel . new ( name , @bot ) end end
Finds or creates a channel .
6,706
def topic = ( new_topic ) if new_topic . size > @bot . irc . isupport [ "TOPICLEN" ] && @bot . strict? raise Exceptions :: TopicTooLong , new_topic end @bot . irc . send "TOPIC #@name :#{new_topic}" end
Sets the topic .
6,707
def kick ( user , reason = nil ) if reason . to_s . size > @bot . irc . isupport [ "KICKLEN" ] && @bot . strict? raise Exceptions :: KickReasonTooLong , reason end @bot . irc . send ( "KICK #@name #{user} :#{reason}" ) end
Kicks a user from the channel .
6,708
def join ( key = nil ) if key . nil? and self . key != true key = self . key end @bot . irc . send "JOIN #{[@name, key].compact.join(" ")}" end
Joins the channel
6,709
def send ( text , notice = false ) text = text . to_s split_start = @bot . config . message_split_start || "" split_end = @bot . config . message_split_end || "" command = notice ? "NOTICE" : "PRIVMSG" prefix = ":#{@bot.mask} #{command} #{@name} :" text . lines . map ( & :chomp ) . each do | line | splitted = split_mes...
Sends a PRIVMSG to the target .
6,710
def start ( plugins = true ) @reconnects = 0 @plugins . register_plugins ( @config . plugins . plugins ) if plugins begin @user_list . each do | user | user . in_whois = false user . unsync_all end @channel_list . each do | channel | channel . unsync_all end @channels = [ ] @join_handler . unregister if @join_handler @...
Connects the bot to a server .
6,711
def part ( channel , reason = nil ) channel = Channel ( channel ) channel . part ( reason ) channel end
Part a channel .
6,712
def generate_next_nick! ( base = nil ) nicks = @config . nicks || [ ] if base if ! nicks . include? ( base ) new_nick = base + "_" else new_index = nicks . index ( base ) + 1 if nicks [ new_index ] new_nick = nicks [ new_index ] else new_nick = base + "_" end end else new_nick = @config . nicks ? @config . nicks . firs...
Try to create a free nick first by cycling through all available alternatives and then by appending underscores .
6,713
def metadata { :definitions => representer_attrs . grep ( Definition ) . map { | definition | definition . name } , :links => representer_attrs . grep ( Link ) . map { | link | link . options [ :as ] ? { link . rel => { 'as' => link . options [ :as ] } } : link . rel } } end
represents the representer s schema in JSON format
6,714
def requested_by? ( resource ) user = resource . respond_to? ( :owner ) ? resource . owner : resource case when current_resource_owner . nil? false when ! user . is_a? ( current_resource_owner . class ) false when current_resource_owner . id == user . id true else false end end
Check if the current resource is the same as the requester . The resource must respond to resource . id method .
6,715
def valid? ( options ) valid_options = Loaf :: Configuration :: VALID_ATTRIBUTES options . each_key do | key | unless valid_options . include? ( key ) fail Loaf :: InvalidOptions . new ( key , valid_options ) end end true end
Check if options are valid or not
6,716
def to_hash VALID_ATTRIBUTES . reduce ( { } ) { | acc , k | acc [ k ] = send ( k ) ; acc } end
Setup this configuration
6,717
def breadcrumb ( name , url , options = { } ) _breadcrumbs << Loaf :: Crumb . new ( name , url , options ) end
Adds breadcrumbs inside view .
6,718
def breadcrumb_trail ( options = { } ) return enum_for ( :breadcrumb_trail ) unless block_given? valid? ( options ) options = Loaf . configuration . to_hash . merge ( options ) _breadcrumbs . each do | crumb | name = title_for ( crumb . name ) path = url_for ( _expand_url ( crumb . url ) ) current = current_crumb? ( pa...
Renders breadcrumbs inside view .
6,719
def _expand_url ( url ) case url when String , Symbol respond_to? ( url ) ? send ( url ) : url when Proc url . call ( self ) else url end end
Expand url in the current context of the view
6,720
def find_title ( title , options = { } ) return title if title . nil? || title . empty? options [ :scope ] ||= translation_scope options [ :default ] = Array ( options [ :default ] ) options [ :default ] << title if options [ :default ] . empty? I18n . t ( title . to_s , options ) end
Translate breadcrumb title
6,721
def tokenize_layout ( layout_spec ) spec = String . new ( layout_spec ) within_braces = false spec . chars . each_with_index do | char , index | case char when '{' within_braces = true when '}' within_braces = false when '-' spec [ index ] = '|' if within_braces end end tokens = spec . split ( '-' ) tokens . map { | t ...
Breaks apart the host input string into chunks suitable for processing by the generator . Returns an array of substrings of the input spec string .
6,722
def settings_string_to_map ( host_settings ) stringscan = StringScanner . new ( host_settings ) object = nil object_depth = [ ] current_depth = 0 loop do blob = stringscan . scan_until ( / \[ \] / ) break if blob . nil? if stringscan . pos ( ) == 1 object = { } object_depth . push ( object ) next end current_type = obj...
Transforms the arbitrary host settings map from a string representation to a proper hash map data structure for merging into the host configuration . Supports arbitrary nested hashes and arrays .
6,723
def get_platform_info ( bhg_version , platform , hypervisor ) info = get_osinfo ( bhg_version ) [ platform ] { } . deep_merge! ( info [ :general ] ) . deep_merge! ( info [ hypervisor ] ) end
Returns the fully parsed map of information of the specified OS platform for the specified hypervisor . This map should be suitable for outputting to the user as it will have the intermediate organizational branches of the get_osinfo map removed .
6,724
def extract_templates ( config ) templates_hosts = config [ 'HOSTS' ] . values . group_by { | h | h [ 'template' ] } templates_hosts . each do | template , hosts | templates_hosts [ template ] = hosts . count end end
Given an existing fully - specified host configuration count the number of hosts using each template and return a map of template name to host count .
6,725
def generate ( layout , options ) layout = prepare ( layout ) tokens = tokenize_layout ( layout ) config = { } . deep_merge ( BASE_CONFIG ) nodeid = Hash . new ( 1 ) ostype = nil bhg_version = options [ :osinfo_version ] || 0 tokens . each do | token | if is_ostype_token? ( token , bhg_version ) if nodeid [ ostype ] ==...
Main host generation entry point returns a Ruby map for the given host specification and optional configuration .
6,726
def coordinate_documents ( docs ) regex = document_url_regex approved = { } docs . each do | doc | lang = doc . data [ 'lang' ] || @default_lang url = doc . url . gsub ( regex , '/' ) doc . data [ 'permalink' ] = url next if @file_langs [ url ] == @active_lang next if @file_langs [ url ] == @default_lang && lang != @ac...
assigns natural permalinks to documents and prioritizes documents with active_lang languages over others
6,727
def process_documents ( docs ) return if @active_lang == @default_lang url = config . fetch ( 'url' , false ) rel_regex = relative_url_regex abs_regex = absolute_url_regex ( url ) docs . each do | doc | relativize_urls ( doc , rel_regex ) if url then relativize_absolute_urls ( doc , abs_regex , url ) end end end
performs any necesarry operations on the documents before rendering them
6,728
def extract_handler_and_format_and_variant ( * args ) if args . first . end_with? ( 'md.erb' ) path = args . shift path = path . gsub ( / \. \. \z / , '.md+erb' ) args . unshift ( path ) end return original_extract_handler_and_format_and_variant ( * args ) end
Different versions of rails have different method signatures here path is always first
6,729
def make_request ( method , path , options = { } ) raise ArgumentError , 'options must be a hash' unless options . is_a? ( Hash ) options [ :headers ] ||= { } options [ :headers ] = @headers . merge ( options [ :headers ] ) Request . new ( @connection , method , @path_prefix + path , options ) . request end
Initialize an APIService
6,730
def enumerator response = get_initial_response Enumerator . new do | yielder | loop do response . records . each { | item | yielder << item } after_cursor = response . after break if after_cursor . nil? @options [ :params ] ||= { } @options [ :params ] = @options [ :params ] . merge ( after : after_cursor ) response = ...
initialize a paginator
6,731
def custom_options ( options ) return default_options if options . nil? return default_options . merge ( options ) unless options [ :default_headers ] opts = default_options . merge ( options ) opts [ :default_headers ] = default_options [ :default_headers ] . merge ( options [ :default_headers ] ) opts end
Get customized options .
6,732
def extract ( contents ) file_text , matches = parse ( contents ) extracted_ruby = + '' last_match = [ 0 , 0 ] matches . each do | start_index , end_index | handle_region_before ( start_index , last_match . last , file_text , extracted_ruby ) extracted_ruby << extract_match ( file_text , start_index , end_index ) last_...
Extracts Ruby code from an ERB template .
6,733
def run require 'ruumba' analyzer = Ruumba :: Analyzer . new ( @options ) puts 'Running Ruumba...' exit ( analyzer . run ( @dir ) ) end
Executes the custom Rake task .
6,734
def run ( files_or_dirs = ARGV ) if options [ :tmp_folder ] analyze ( File . expand_path ( options [ :tmp_folder ] ) , files_or_dirs ) else Dir . mktmpdir do | dir | analyze ( dir , files_or_dirs ) end end end
Performs static analysis on the provided directory .
6,735
def error ( message ) message = message . red unless message . color? puts ( stderr , message ) end
Logs a message to stderr . Unless otherwise specified the message will be printed in red .
6,736
def giftCardAuth_reversal ( options ) transaction = GiftCardAuthReversal . new transaction . litleTxnId = options [ 'litleTxnId' ] transaction . card = GiftCardCardType . from_hash ( options , 'card' ) transaction . originalRefCode = options [ 'originalRefCode' ] transaction . originalAmount = options [ 'originalAmount...
XML 11 . 0
6,737
def fast_access_funding ( options ) transaction = FastAccessFunding . new transaction . reportGroup = get_report_group ( options ) transaction . transactionId = options [ 'id' ] transaction . customerId = options [ 'customerId' ] transaction . fundingSubmerchantId = options [ 'fundingSubmerchantId' ] transaction . subm...
11 . 4 Begin
6,738
def finish_request File . open ( @path_to_request , 'w' ) do | f | f . puts ( build_request_header ( ) ) File . foreach ( @path_to_batches ) do | li | f . puts li end f . puts '</litleRequest>' end File . rename ( @path_to_request , @path_to_request + COMPLETE_FILE_SUFFIX ) File . delete ( @path_to_batches ) end
Called when you wish to finish adding batches to your request this method rewrites the aggregate batch file to the final LitleRequest xml doc with the appropos LitleRequest tags .
6,739
def parse ( argv ) parser , options = parse_main ( argv ) options = { :help => true } if options [ :help ] options = { :version => true } if options [ :version ] validate_options! ( options ) @options = options @help_text = parser . to_s self end
Parses an Array of command - line arguments into an equivalent Hash .
6,740
def load_site_configs ( * files ) files = files [ 0 ] if files . length == 1 && files [ 0 ] . is_a? ( Array ) load_files ( * files ) end
Load the config files as specified via + files + .
6,741
def load ( * configs ) configs . each do | config | config . each do | k , v | if self [ k ] && self [ k ] . is_a? ( Array ) self [ k ] += v else self [ k ] = v end end end self end
Take a collection of config hashes and cascade them meaning values in later ones override values in earlier ones .
6,742
def load_env Inq :: Text . puts "Using configuration from environment variables." gh_token = ENV [ "INQ_GITHUB_TOKEN" ] || ENV [ "HOWIS_GITHUB_TOKEN" ] gh_username = ENV [ "INQ_GITHUB_USERNAME" ] || ENV [ "HOWIS_GITHUB_USERNAME" ] raise "INQ_GITHUB_TOKEN environment variable is not set" unless gh_token raise "INQ_GITHU...
Load config info from environment variables .
6,743
def date_le ( left , right ) left = str_to_dt ( left ) right = str_to_dt ( right ) left <= right end
Check if + left + is less than or equal to + right + where both are string representations of a date .
6,744
def date_ge ( left , right ) left = str_to_dt ( left ) right = str_to_dt ( right ) left >= right end
Check if + left + is greater than or equal to + right + where both are string representations of a date .
6,745
def metadata ( repository ) end_date = DateTime . strptime ( @date , "%Y-%m-%d" ) friendly_end_date = end_date . strftime ( "%B %d, %y" ) { sanitized_repository : repository . tr ( "/" , "-" ) , repository : repository , date : end_date , friendly_date : friendly_end_date , } end
Generates the metadata for the collection of Reports .
6,746
def to_h results = { } defaults = @config [ "default_reports" ] || { } @config [ "repositories" ] . map { | repo_config | repo = repo_config [ "repository" ] config = config_for ( repo ) config [ "reports" ] . map { | format , report_config | filename = silence_warnings { tmp_filename = report_config [ "filename" ] || ...
Converts a ReportCollection to a Hash .
6,747
def save_all reports = to_h reports . each do | file , report | File . write ( file , report ) end reports . keys end
Save all of the reports to the corresponding files .
6,748
def asset_precompiled? ( logical_path ) if precompiled_assets . include? ( logical_path ) true elsif ! config . cache_classes precompiled_assets ( true ) . include? ( logical_path ) else false end end
Called from asset helpers to alert you if you reference an asset URL that isn t precompiled and hence won t be available in production .
6,749
def precompiled_assets ( clear_cache = false ) @precompiled_assets = nil if clear_cache @precompiled_assets ||= assets_manifest . find ( config . assets . precompile ) . map ( & :logical_path ) . to_set end
Lazy - load the precompile list so we don t cause asset compilation at app boot time but ensure we cache the list so we don t recompute it for each request or test case .
6,750
def handle ( item ) case item when "WEIGHTS" self . type = :weights self . weights = [ ] when "AGGREGATE" self . type = :aggregate when nil raise ( Redis :: CommandError , "ERR syntax error" ) else send "handle_#{type}" , item end self end
Decides how to handle an item depending on where we are in the arguments
6,751
def computed_values unless defined? ( @computed_values ) && @computed_values @computed_values = hashes if weights . all? { | weight | weight == 1 } @computed_values ||= hashes . each_with_index . map do | hash , index | weight = weights [ index ] Hash [ hash . map { | k , v | [ k , ( v * weight ) ] } ] end end @compute...
Apply the weightings to the hashes
6,752
def _floatify ( str , increment = true ) if ( ( inf = str . to_s . match ( / /i ) ) ) ( inf [ 1 ] == "-" ? - 1.0 : 1.0 ) / 0.0 elsif ( ( number = str . to_s . match ( / \( \d /i ) ) ) number [ 1 ] . to_i + ( increment ? 1 : - 1 ) else Float str . to_s end rescue ArgumentError raise Redis :: CommandError , "ERR value is...
Originally lifted from redis - rb
6,753
def uuid ( value = nil ) if value . nil? timeuuid_generator . now elsif value . is_a? ( Time ) timeuuid_generator . at ( value ) elsif value . is_a? ( DateTime ) timeuuid_generator . at ( Time . at ( value . to_f ) ) else Type :: Timeuuid . instance . cast ( value ) end end
Create a UUID
6,754
def find ( command , options = { } , & block ) case command when Integer record ( command ) when Array command . map { | i | record ( i ) } when :all find_all ( options , & block ) when :first find_first ( options ) end end
Find records using a simple ActiveRecord - like syntax .
6,755
def record ( index ) seek_to_record ( index ) return nil if deleted_record? DBF :: Record . new ( @data . read ( record_length ) , columns , version , @memo ) end
Retrieve a record by index number . The record will be nil if it has been deleted but not yet pruned from the database .
6,756
def to_csv ( path = nil ) out_io = path ? File . open ( path , 'w' ) : $stdout csv = CSV . new ( out_io , force_quotes : true ) csv << column_names each { | record | csv << record . to_a } end
Dumps all records to a CSV file . If no filename is given then CSV is output to STDOUT .
6,757
def get ( url , version : nil , locale : nil ) @client . get ( url , headers : headers ( version : version , locale : locale ) ) end
Get the response from a URL from the cache if possible . Stores to the cache on misses .
6,758
def inject ( clients = { } ) @_injected_clients = true clients . each_pair do | name , client | _close_if_present ( @_connections [ name ] ) @_connections [ name ] = Redis :: Namespace . new ( DEFAULT_NAMESPACE , redis : client ) end end
Allow to inject pre - built Redis clients
6,759
def keep_trying ( timeout = 10 , tries = 0 ) puts "Try: #{tries}" if @announce_env yield rescue RSpec :: Expectations :: ExpectationNotMetError if tries < timeout sleep 1 tries += 1 retry else raise end end
this is a horrible hack to make sure that it s done what it needs to do before we do our next step
6,760
def perform_command ( remove_components = true , & block ) txt = File . read ( File . join ( root_path , "bower.json" ) ) json = JSON . parse ( txt ) dot_bowerrc = JSON . parse ( File . read ( File . join ( root_path , '.bowerrc' ) ) ) rescue { } dot_bowerrc [ "directory" ] = components_directory if json . reject { | k...
run the passed bower block in appropriate folders
6,761
def with_shard ( shard ) shard = cluster . to_shard ( shard ) old_shard = current_shard old_fixed = fixed_shard self . current_shard = shard self . fixed_shard = shard yield ensure self . fixed_shard = old_fixed self . current_shard = old_shard end
Fix connection to given shard in block
6,762
def with_all ( continue_on_error = false ) cluster . shards . map do | shard | begin with_shard ( shard ) { yield } rescue Exception => err unless continue_on_error raise err end err end end end
Send queries to all shards in this cluster
6,763
def with_default_and_all ( continue_on_error = false ) ( [ default_shard ] + cluster . shards ) . map do | shard | begin with_shard ( shard ) { yield } rescue Exception => err unless continue_on_error raise err end err end end end
Send queries to default connection and all shards in this cluster
6,764
def parse_headers ( header_data_for_multiple_responses ) @headers = { } responses = Patron :: HeaderParser . parse ( header_data_for_multiple_responses ) last_response = responses [ - 1 ] @status_line = last_response . status_line last_response . headers . each do | line | hdr , val = line . split ( ":" , 2 ) val . str...
Called by the C code to parse and set the headers
6,765
def auth_type = ( type = :basic ) @auth_type = case type when :basic , "basic" Request :: AuthBasic when :digest , "digest" Request :: AuthDigest when :any , "any" Request :: AuthAny else raise "#{type.inspect} is an unknown authentication type" end end
Set the type of authentication to use for this request .
6,766
def action = ( action ) if ! VALID_ACTIONS . include? ( action . to_s . upcase ) raise ArgumentError , "Action must be one of #{VALID_ACTIONS.join(', ')}" end @action = action . downcase . to_sym end
Sets the HTTP verb for the request
6,767
def handle_cookies ( file_path = nil ) if file_path path = Pathname ( file_path ) . expand_path if ! File . exists? ( file_path ) && ! File . writable? ( path . dirname ) raise ArgumentError , "Can't create file #{path} (permission error)" elsif File . exists? ( file_path ) && ! File . writable? ( file_path ) raise Arg...
Create a new Session object for performing requests .
6,768
def post ( url , data , headers = { } ) if data . is_a? ( Hash ) data = data . map { | k , v | urlencode ( k . to_s ) + '=' + urlencode ( v . to_s ) } . join ( '&' ) headers [ 'Content-Type' ] = 'application/x-www-form-urlencoded' end request ( :post , url , headers , :data => data ) end
Uploads the passed data to the specified url using an HTTP POST .
6,769
def post_multipart ( url , data , filename , headers = { } ) request ( :post , url , headers , { :data => data , :file => filename , :multipart => true } ) end
Uploads the contents of filename to the specified url using an HTTP POST in combination with given form fields passed in data .
6,770
def build_request ( action , url , headers , options = { } ) headers [ 'Expect' ] ||= '' Request . new . tap do | req | req . action = action req . headers = self . headers . merge headers req . automatic_content_encoding = options . fetch :automatic_content_encoding , self . automatic_content_encoding req . timeout = ...
Builds a request object that can be used by ++ handle_request ++ Note that internally ++ handle_request ++ uses instance variables of the Request object and not it s public methods .
6,771
def clean_tag_borders ( string ) result = string . gsub ( / \s \* \* \s / ) do | match | preserve_border_whitespaces ( match , default_border : ReverseMarkdown . config . tag_border ) do match . strip . sub ( '** ' , '**' ) . sub ( ' **' , '**' ) end end result = result . gsub ( / \s \_ \_ \s / ) do | match | preserve_...
Find non - asterisk content that is enclosed by two or more asterisks . Ensure that only one whitespace occurs in the border area . Same for underscores and brackets .
6,772
def glob_map ( map = { } , ** options , & block ) map = Mapper === map ? map : Mapper . new ( map , ** options ) mapped = glob ( * map . to_h . keys ) . map { | f | [ f , unescape ( map [ f ] ) ] } block ? mapped . map ( & block ) : Hash [ mapped ] end
Allows to search for files an map these onto other strings .
6,773
def cp ( map = { } , recursive : false , ** options ) utils_opts , opts = split_options ( :preserve , :dereference_root , :remove_destination , ** options ) cp_method = recursive ? :cp_r : :cp glob_map ( map , ** opts ) { | o , n | f . send ( cp_method , o , n , ** utils_opts ) } end
Copies files based on a pattern mapping .
6,774
def mv ( map = { } , ** options ) utils_opts , opts = split_options ( ** options ) glob_map ( map , ** opts ) { | o , n | f . mv ( o , n , ** utils_opts ) } end
Moves files based on a pattern mapping .
6,775
def ln ( map = { } , symbolic : false , ** options ) utils_opts , opts = split_options ( ** options ) link_method = symbolic ? :ln_s : :ln glob_map ( map , ** opts ) { | o , n | f . send ( link_method , o , n , ** utils_opts ) } end
Creates links based on a pattern mapping .
6,776
def ln_sf ( map = { } , ** options ) ln ( map , symbolic : true , force : true , ** options ) end
Creates symbolic links based on a pattern mapping . Overrides potentailly existing files .
6,777
def pattern_with_glob_pattern ( * pattern , ** options ) options [ :uri_decode ] ||= false pattern = Mustermann . new ( * pattern . flatten , ** options ) @glob_patterns ||= { } @glob_patterns [ pattern ] ||= GlobPattern . generate ( pattern ) [ pattern , @glob_patterns [ pattern ] ] end
Create a Mustermann pattern from whatever the input is and turn it into a glob pattern .
6,778
def pump ( string , inject_with : :+ , initial : nil , with_size : false ) substring = string results = Array ( initial ) patterns . each do | pattern | result , size = yield ( pattern , substring ) return unless result results << result size ||= result substring = substring [ size .. - 1 ] end results = results . inje...
used to generate results for various methods by scanning through an input string
6,779
def combined_ast payload = patterns . map { | p | AST :: Node [ :group ] . new ( p . to_ast . payload ) } AST :: Node [ :root ] . new ( payload ) end
generates one big AST from all patterns will not check if patterns support AST generation
6,780
def | ( other ) return super unless converted = self . class . try_convert ( other , ** options ) return super unless converted . names . empty? or names . empty? self . class . new ( safe_string + "|" + converted . safe_string , ** options ) end
Creates a pattern that matches any string matching either one of the patterns . If a string is supplied it is treated as a fully escaped Sinatra pattern .
6,781
def scan_until ( pattern , ** options ) result , prefix = check_until_with_prefix ( pattern , ** options ) track_result ( prefix , result ) end
Checks if the given pattern matches any substring starting at any position after the current position .
6,782
def unscan raise ScanError , 'unscan failed: previous match record not exist' if @history . empty? previous = @history [ 0 .. - 2 ] reset previous . each { | r | track_result ( * r ) } self end
Reverts the last operation that advanced the position .
6,783
def check ( pattern , ** options ) params , length = create_pattern ( pattern , ** options ) . peek_params ( rest ) ScanResult . new ( self , @position , length , params ) if params end
Checks if the given pattern matches any substring starting at the current position .
6,784
def expand ( behavior = nil , values = { } ) return to_s if values . empty? or behavior == :ignore raise ExpandError , "cannot expand with keys %p" % values . keys . sort if behavior == :raise raise ArgumentError , "unknown behavior %p" % behavior if behavior != :append params = values . map { | key , value | @@uri . e...
Identity patterns support expanding .
6,785
def new ( * args , version : nil , ** options ) return super ( * args , ** options ) unless versions . any? self [ version ] . new ( * args , ** options ) end
Checks if class has mulitple versions available and picks one that matches the version option .
6,786
def version ( * list , inherit_from : nil , & block ) superclass = self [ inherit_from ] || self subclass = Class . new ( superclass , & block ) list . each { | v | versions [ v ] = subclass } end
Defines a new version .
6,787
def [] ( version ) return versions . values . last unless version detected = versions . detect { | v , _ | version . start_with? ( v ) } raise ArgumentError , 'unsupported version %p' % version unless detected detected . last end
Resolve a subclass for a given version string .
6,788
def cast ( hash ) return hash if empty? merge = { } hash . delete_if do | key , value | next unless casted = lazy . map { | e | e . cast ( key , value ) } . detect { | e | e } casted = { key => casted } unless casted . respond_to? :to_hash merge . update ( casted . to_hash ) end hash . update ( merge ) end
Transforms a Hash .
6,789
def update ( map ) map . to_h . each_pair do | input , output | input = Mustermann . new ( input , ** @options ) output = Expander . new ( * output , additional_values : @additional_values , ** @options ) unless output . is_a? Expander @map << [ input , output ] end end
Creates a new mapper .
6,790
def convert ( input , values = { } ) @map . inject ( input ) do | current , ( pattern , expander ) | params = pattern . params ( current ) params &&= Hash [ values . merge ( params ) . map { | k , v | [ k . to_s , v ] } ] expander . expandable? ( params ) ? expander . expand ( params ) : current end end
Convert a string according to mappings . You can pass in additional params .
6,791
def escape ( value ) string_pointer = Curl . easy_escape ( handle , value , value . bytesize ) returned_string = string_pointer . read_string Curl . free ( string_pointer ) returned_string end
Clones libcurl session handle . This means that all options that is set in the current handle will be set on duplicated handle . Url escapes the value .
6,792
def token_frequency tokens . each_with_object ( Hash . new ( 0 ) ) { | token , hash | hash [ token ] += 1 } . sort_by_value_desc end
Returns a sorted two - dimensional array where each member array is a token and its frequency . The array is sorted by frequency in descending order .
6,793
def token_lengths tokens . uniq . each_with_object ( { } ) { | token , hash | hash [ token ] = token . length } . sort_by_value_desc end
Returns a sorted two - dimensional array where each member array is a token and its length . The array is sorted by length in descending order .
6,794
def token_density ( precision : 2 ) token_frequency . each_with_object ( { } ) { | ( token , freq ) , hash | hash [ token ] = ( freq / token_count . to_f ) . round ( precision ) } . sort_by_value_desc end
Returns a sorted two - dimensional array where each member array is a token and its density as a float rounded to a precision of two decimal places . It accepts a precision argument which defaults to 2 .
6,795
def tokenise ( pattern : TOKEN_REGEXP , exclude : nil ) filter_proc = filter_to_proc ( exclude ) @input . scan ( pattern ) . map ( & :downcase ) . reject { | token | filter_proc . call ( token ) } end
Initialises state with the string to be tokenised .
6,796
def filter_to_proc ( filter ) if filter . respond_to? ( :to_a ) filter_procs_from_array ( filter ) elsif filter . respond_to? ( :to_str ) filter_proc_from_string ( filter ) elsif regexp_filter = Regexp . try_convert ( filter ) -> ( token ) { token =~ regexp_filter } elsif filter . respond_to? ( :to_proc ) filter . to_p...
The following methods convert any arguments into a callable object . The return value of this lambda is then used to determine whether a token should be excluded from the final list .
6,797
def to_hash Hash [ instance_variables . map { | name | [ name . to_s . delete ( '@' ) . to_sym , instance_variable_get ( name ) ] } ] end
Return the Configuration object as a hash with symbols as keys .
6,798
def cat ( * args ) in_files = [ ] page_ranges = [ ] file_handle = "A" output = normalize_path args . pop args . flatten . compact . each do | in_file | if in_file . is_a? Hash path = in_file . keys . first page_ranges . push * in_file . values . first . map { | range | "#{file_handle}#{range}" } else path = in_file pag...
concatenate documents can optionally specify page ranges
6,799
def to_pdf_data pdf_data = header @data . each do | key , value | if Hash === value value . each do | sub_key , sub_value | pdf_data << field ( "#{key}_#{sub_key}" , sub_value ) end else pdf_data << field ( key , value ) end end pdf_data << footer return encode_data ( pdf_data ) end
generate PDF content in this data format