idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
11,000
def select_data_code ( options = { } ) paginate = ( options . key? ( :paginate ) ? options [ :paginate ] : @table . paginate? ) unless @table . options . keys . include? ( :order ) columns = @table . table_columns @table . options [ :order ] = ( columns . any? ? columns . first . name . to_sym : { id : :desc } ) end cl...
Generate select code for the table taking all parameters in account
11,001
def includes_reflections hash = [ ] @table . columns . each do | column | hash << column . reflection . name if column . respond_to? ( :reflection ) end hash end
Compute includes Hash
11,002
def conditions_code conditions = @table . options [ :conditions ] code = '' case conditions when Array case conditions [ 0 ] when String code << '[' + conditions . first . inspect code << conditions [ 1 .. - 1 ] . collect { | p | ', ' + sanitize_condition ( p ) } . join if conditions . size > 1 code << ']' when Symbol ...
Generate the code from a conditions option
11,003
def default_load_paths paths = [ ] paths << "#{::Rails.root}/config" if rails? paths << CONFIG_ROOT if defined? ( CONFIG_ROOT ) && Dir . exists? ( CONFIG_ROOT ) paths << CONFIG_PATH if defined? ( CONFIG_PATH ) && Dir . exists? ( CONFIG_PATH ) config_dir = File . join ( app_root , 'config' ) paths << config_dir if Dir ....
Checks environment for default configuration load paths . Adds them to load paths if found .
11,004
def read ( file , name , ext ) contents = File . read ( file ) contents = ERB . new ( contents ) . result parse ( contents , name , ext ) end
Reads and parses the config data from the specified file .
11,005
def parse ( contents , name , ext ) hash = case ext when * YML_FILE_TYPES YAML :: load ( contents ) when * XML_FILE_TYPES parse_xml ( contents , name ) when * CNF_FILE_TYPES RConfig :: PropertiesFile . parse ( contents ) else raise ConfigError , "Unknown File type: #{ext}" end hash . freeze end
Parses contents of the config file based on file type . XML files expect the root element to be the same as the file name .
11,006
def parse_xml ( contents , name ) hash = Hash . from_xml ( contents ) hash = hash [ name ] if hash . size == 1 && hash . key? ( name ) RConfig :: PropertiesFile . parse_references ( hash ) end
Parses xml file and processes any references in the property values .
11,007
def merge_hashes ( hashes ) hashes . inject ( { } ) { | n , h | n . weave ( h , true ) } end
Returns a merge of hashes .
11,008
def make_indifferent ( hash ) case hash when Hash unless hash . frozen? hash . each do | k , v | hash [ k ] = make_indifferent ( v ) end hash = RConfig :: Config . new . merge! ( hash ) . freeze end logger . debug "make_indefferent: x = #{hash.inspect}:#{hash.class}" when Array unless hash . frozen? hash . collect! do ...
Recursively makes hashes into frozen IndifferentAccess Config Hash Arrays are also traversed and frozen .
11,009
def flush_cache ( name = nil ) if name name = name . to_s self . cache_hash [ name ] &&= nil else logger . warn "RConfig: Flushing config data cache." self . suffixes = { } self . cache = { } self . cache_files = { } self . cache_hash = { } self . last_auto_check = { } self end end
If a config file name is specified flushes cached config values for specified config file . Otherwise flushes all cached config data . The latter should be avoided in production environments if possible .
11,010
def overlay = ( value ) reload ( false ) if self . overlay != value self . overlay = value && value . dup . freeze end
Sets a custome overlay for
11,011
def suffixes_for ( name ) name = name . to_s self . suffixes [ name ] ||= begin ol = overlay name_x = name . dup if name_x . sub! ( / / , '' ) ol = $1 end name_x . freeze result = if ol ol_ = ol . upcase ol = ol . downcase x = [ ] SUFFIXES . each do | suffix | x << suffix x << [ ol_ , suffix ] end [ name_x , x . freeze...
Returns a list of suffixes to try for a given config name .
11,012
def load_config_files ( name , force = false ) name = name . to_s return self . cache_config_files [ name ] if self . reload_disabled? && self . cache_config_files [ name ] logger . info "Loading config files for: #{name}" logger . debug "load_config_files(#{name.inspect})" now = Time . now config_files = self . get_co...
Get each config file s yaml hash for the given config name to be merged later . Files will only be loaded if they have not been loaded before or the files have changed within the last five minutes or force is explicitly set to true .
11,013
def config_changed? ( name ) logger . debug "config_changed?(#{name.inspect})" name = name . to_s ! ( self . cache_files [ name ] === get_config_files ( name ) ) end
Returns whether or not the config for the given config name has changed since it was last loaded .
11,014
def get_config_data ( name ) logger . debug "get_config_data(#{name.inspect})" name = name . to_s unless result = self . cache_hash [ name ] result = self . cache_hash [ name ] = make_indifferent ( merge_hashes ( load_config_files ( name ) ) ) logger . debug "get_config_data(#{name.inspect}): reloaded" end result end
Get the merged config hash for the named file . Returns a cached indifferent access faker hash merged from all config files for a name .
11,015
def check_for_changes ( name = nil ) changed = [ ] if name == nil self . cache_hash . keys . dup . each do | name | if reload_on_change ( name ) changed << name end end else name = name . to_s if reload_on_change ( name ) changed << name end end logger . debug "check_for_changes(#{name.inspect}) => #{changed.inspect}" ...
If name is specified checks that file for changes and reloads it if there are . Otherwise checks all files in the cache reloading the changed files .
11,016
def reload_on_change ( name ) logger . debug "reload_on_change(#{name.inspect}), reload_disabled=#{self.reload_disabled?}" if changed = config_changed? ( name ) && reload? if self . cache_hash [ name ] flush_cache ( name ) fire_on_load ( name ) end end changed end
If config files have changed caches are flushed on_load triggers are run .
11,017
def with_file ( name , * args ) logger . debug "with_file(#{name.inspect}, #{args.inspect})" result = args . inject ( config_for ( name ) ) { | v , i | logger . debug "v = #{v.inspect}, i = #{i.inspect}" case v when Hash v [ i . to_s ] when Array i . is_a? ( Integer ) ? v [ i ] : nil else nil end } logger . debug "with...
Get the value specified by the args in the file specified by th name
11,018
def config_for ( name ) name = name . to_s check_for_changes ( name ) if auto_check? ( name ) data = get_config_data ( name ) logger . debug "config_for(#{name.inspect}) => #{data.inspect}" data end
Get a hash of merged config data . Will auto check every 5 minutes for longer running apps unless reload is disabled .
11,019
def method_missing ( method , * args ) value = with_file ( method , * args ) logger . debug "#{self}.method_missing(#{method.inspect}, #{args.inspect}) => #{value.inspect}" value end
Short - hand access to config file by its name .
11,020
def query ( sql , & blk ) layer = SimplerTiles :: Query . new ( sql , & blk ) add_query layer end
Add a query to this Layer s c list .
11,021
def layer ( source , & blk ) layer = SimplerTiles :: VectorLayer . new ( source , & blk ) add_vector_layer layer end
Add a layer to the c list of layers and yield the new layer .
11,022
def raster_layer ( source , & blk ) layer = SimplerTiles :: RasterLayer . new ( source , & blk ) add_raster_layer layer end
Add a raster layer
11,023
def ar_layer ( & blk ) if ! defined? ( ActiveRecord ) raise "ActiveRecord not available" end config = ActiveRecord :: Base . connection . instance_variable_get ( "@config" ) params = { :dbname => config [ :database ] , :user => config [ :username ] , :host => config [ :host ] , :port => config [ :port ] , :password => ...
A convienence method to use Active Record configuration and add a new layer .
11,024
def to_png data = "" to_png_stream Proc . new { | chunk | data += chunk } yield data if block_given? data end
Render the data to a blob of png data .
11,025
def styles ( styles ) styles . each do | k , v | style = SimplerTiles :: Style . new k , v add_style style end end
Initialize a query with a string containing OGR SQL . Styles will take a hash of style declarations and adds them to the internal c list .
11,026
def add_load_path ( path ) if path = parse_load_paths ( path ) . first self . load_paths << path self . load_paths . uniq! return reload ( true ) end false end
Adds the specified path to the list of directories to search for configuration files . It only allows one path to be entered at a time .
11,027
def enable_reload = ( reload ) raise ArgumentError , 'Argument must be true or false.' unless [ true , false ] . include? ( reload ) self . enable_reload = reload end
Sets the flag indicating whether or not reload should be executed .
11,028
def reload_interval = ( interval ) raise ArgumentError , 'Argument must be Integer.' unless interval . kind_of? ( Integer ) self . enable_reload = false if interval == 0 self . reload_interval = interval end
Sets the number of seconds between reloading of config files and automatic reload checks . Defaults to 5 minutes . Setting
11,029
def reload ( force = false ) raise ArgumentError , 'Argument must be true or false.' unless [ true , false ] . include? ( force ) if force || reload? flush_cache return true end false end
Flushes cached config data so that it can be reloaded from disk . It is recommended that this should be used with caution and any need to reload in a production setting should minimized or completely avoided if possible .
11,030
def noko ( & block ) doc = :: Nokogiri :: XML . parse ( NOKOHEAD ) fragment = doc . fragment ( "" ) :: Nokogiri :: XML :: Builder . with fragment , & block fragment . to_xml ( encoding : "US-ASCII" ) . lines . map do | l | l . gsub ( / \s \n / , "" ) end end
block for processing XML document fragments as XHTML to allow for HTMLentities
11,031
def anchor_names ( docxml ) initial_anchor_names ( docxml ) back_anchor_names ( docxml ) note_anchor_names ( docxml . xpath ( ns ( "//table | //example | //formula | " "//figure" ) ) ) note_anchor_names ( docxml . xpath ( ns ( SECTIONS_XPATH ) ) ) example_anchor_names ( docxml . xpath ( ns ( SECTIONS_XPATH ) ) ) list_a...
extract names for all anchors xref and label
11,032
def figure_cleanup ( docxml ) docxml . xpath ( FIGURE_WITH_FOOTNOTES ) . each do | f | key = figure_get_or_make_dl ( f ) f . xpath ( ".//aside" ) . each do | aside | figure_aside_process ( f , aside , key ) end end docxml end
move footnotes into key and get rid of footnote reference since it is in diagram
11,033
def preface_names ( clause ) return if clause . nil? @anchors [ clause [ "id" ] ] = { label : nil , level : 1 , xref : preface_clause_name ( clause ) , type : "clause" } clause . xpath ( ns ( "./clause | ./terms | ./term | ./definitions | ./references" ) ) . each_with_index do | c , i | preface_names1 ( c , c . at ( ns...
in StanDoc prefaces have no numbering ; they are referenced only by title
11,034
def destroy_sandbox if File . directory? ( Strainer . sandbox_path ) Strainer . ui . debug " Destroying sandbox at '#{Strainer.sandbox_path}'" FileUtils . rm_rf ( Strainer . sandbox_path ) else Strainer . ui . debug " Sandbox does not exist... skipping" end end
Destroy the current sandbox if it exists
11,035
def create_sandbox unless File . directory? ( Strainer . sandbox_path ) Strainer . ui . debug " Creating sandbox at '#{Strainer.sandbox_path}'" FileUtils . mkdir_p ( Strainer . sandbox_path ) end copy_globals place_knife_rb copy_cookbooks end
Create the sandbox unless it already exits
11,036
def load_cookbooks ( cookbook_names ) Strainer . ui . debug "Sandbox#load_cookbooks(#{cookbook_names.inspect})" cookbook_names . collect { | cookbook_name | load_cookbook ( cookbook_name ) } end
Load a cookbook from the given array of cookbook names
11,037
def load_cookbook ( cookbook_name ) Strainer . ui . debug "Sandbox#load_cookbook('#{cookbook_name.inspect}')" cookbook_path = cookbooks_paths . find { | path | path . join ( cookbook_name ) . exist? } cookbook = if cookbook_path path = cookbook_path . join ( cookbook_name ) Strainer . ui . debug " found cookbook at '#...
Load an individual cookbook by its name
11,038
def load_self Strainer . ui . debug "Sandbox#load_self" begin Berkshelf :: CachedCookbook . from_path ( File . expand_path ( '.' ) ) rescue Berkshelf :: CookbookNotFound raise Strainer :: Error :: CookbookNotFound , "'#{File.expand_path('.')}' existed, but I could not extract a cookbook. Is there a 'metadata.rb'?" end ...
Load the current root entirely as a cookbook . This is useful when testing within a cookbook instead of a chef repo
11,039
def cookbooks_and_dependencies loaded_dependencies = Hash . new ( false ) dependencies = @cookbooks . dup dependencies . each do | cookbook | loaded_dependencies [ cookbook . cookbook_name ] = true cookbook . metadata . dependencies . keys . each do | dependency_name | unless loaded_dependencies [ dependency_name ] dep...
Collect all cookbooks and the dependencies specified in their metadata . rb for copying
11,040
def chef_repo? @_chef_repo ||= begin chef_folders = %w( .chef certificates config cookbooks data_bags environments roles ) ( root_folders & chef_folders ) . size > 2 end end
Determines if the current project is a chef repo
11,041
def root_folders @root_folders ||= Dir . glob ( "#{Dir.pwd}/*" , File :: FNM_DOTMATCH ) . collect do | f | File . basename ( f ) if File . directory? ( f ) end . reject { | dir | %w( . .. ) . include? ( dir ) } . compact! end
Return a list of all directory folders at the root of the repo . This is useful for detecting if it s a chef repo or cookbook repo .
11,042
def run! @cookbooks . each do | name , c | cookbook = c [ :cookbook ] strainerfile = c [ :strainerfile ] Strainer . ui . debug "Starting Runner for #{cookbook.cookbook_name} (#{cookbook.version})" Strainer . ui . header ( "# Straining '#{cookbook.cookbook_name} (v#{cookbook.version})'" ) strainerfile . commands . each ...
Creates a Strainer runner
11,043
def commands @commands ||= if @options [ :except ] @all_commands . reject { | command | @options [ :except ] . include? ( command . label ) } elsif @options [ :only ] @all_commands . select { | command | @options [ :only ] . include? ( command . label ) } else @all_commands end end
Instantiate an instance of this class from a cookbook
11,044
def load! return if @all_commands contents = File . read @strainerfile contents . strip! contents . gsub! '$COOKBOOK' , @cookbook . cookbook_name contents . gsub! '$SANDBOX' , Strainer . sandbox_path . to_s lines = contents . split ( "\n" ) lines . reject! { | line | line . strip . empty? || line . strip . start_with? ...
Parse the given Strainerfile
11,045
def speak ( message , options = { } ) message . to_s . strip . split ( "\n" ) . each do | line | next if line . strip . empty? line . gsub! Strainer . sandbox_path . to_s , @cookbook . original_path . dirname . to_s Strainer . ui . say label_with_padding + line , options end end
Have this command output text prefixing with its output with the command name
11,046
def inside_sandbox ( & block ) Strainer . ui . debug "Changing working directory to '#{Strainer.sandbox_path}'" original_pwd = ENV [ 'PWD' ] ENV [ 'PWD' ] = Strainer . sandbox_path . to_s success = Dir . chdir ( Strainer . sandbox_path , & block ) ENV [ 'PWD' ] = original_pwd Strainer . ui . debug "Restored working dir...
Execute a block inside the sandbox directory defined in Strainer . sandbox_path . This will first change the PWD env variable to the sandbox path and then pass the given block into Dir . chdir . PWD is restored to the original value when the block is finished .
11,047
def inside_cookbook ( & block ) cookbook_path = File . join ( Strainer . sandbox_path . to_s , @cookbook . cookbook_name ) Strainer . ui . debug "Changing working directory to '#{cookbook_path}'" original_pwd = ENV [ 'PWD' ] ENV [ 'PWD' ] = cookbook_path success = Dir . chdir ( cookbook_path , & block ) ENV [ 'PWD' ] =...
Execute a block inside the sandboxed cookbook directory .
11,048
def run_as_pty ( command ) Strainer . ui . debug 'Using PTY' PTY . spawn ( command ) do | r , _ , pid | begin r . sync r . each_line { | line | speak line } rescue Errno :: EIO => e ensure :: Process . wait pid end end end
Run a command using PTY
11,049
def error ( message , color = :red ) Strainer . log . error ( message ) return if quiet? message = set_color ( message , * color ) if color super ( message ) end
Print a red error message to the STDERR .
11,050
def token_value ( object , options , language ) if object . is_a? ( Array ) if object . empty? return raise Tr8n :: TokenException . new ( "Invalid array value for a token: #{full_name}" ) end if object . first . kind_of? ( Enumerable ) return token_array_value ( object , options , language ) end return evaluate_token_...
evaluate all possible methods for the token value and return sanitized result
11,051
def update_rules @rules = rules_by_dependency ( parse_language_rules ) unless params [ :rule_action ] return render ( :partial => "edit_rules" ) end if params [ :rule_action ] . index ( "add_at" ) position = params [ :rule_action ] . split ( "_" ) . last . to_i cls = Tr8n :: Config . language_rule_dependencies [ params...
ajax method for updating language rules in edit mode
11,052
def update_language_cases @cases = parse_language_cases unless params [ :case_action ] return render ( :partial => "edit_cases" ) end if params [ :case_action ] . index ( "add_at" ) position = params [ :case_action ] . split ( "_" ) . last . to_i @cases . insert ( position , Tr8n :: LanguageCase . new ( :language => tr...
ajax method for updating language cases in edit mode
11,053
def update_language_case_rules cases = parse_language_cases case_index = params [ :case_index ] . to_i lcase = cases [ case_index ] if params [ :case_action ] . index ( "add_rule_at" ) position = params [ :case_action ] . split ( "_" ) . last . to_i rule_data = params [ :edit_rule ] . merge ( :language => tr8n_current_...
ajax method for updating language case rules in edit mode
11,054
def select @inline_translations_allowed = false @inline_translations_enabled = false if tr8n_current_user_is_translator? unless tr8n_current_translator . blocked? @inline_translations_allowed = true @inline_translations_enabled = tr8n_current_translator . enable_inline_translations? end else @inline_translations_allowe...
language selector window
11,055
def switch language_action = params [ :language_action ] return redirect_to_source if tr8n_current_user_is_guest? if tr8n_current_user_is_translator? if language_action == "toggle_inline_mode" if tr8n_current_translator . enable_inline_translations? language_action = "disable_inline_mode" else language_action = "enable...
language selector processor
11,056
def parse_language_rules rulz = [ ] return rulz unless params [ :rules ] Tr8n :: Config . language_rule_classes . each do | cls | next unless params [ :rules ] [ cls . dependency ] index = 0 while params [ :rules ] [ cls . dependency ] [ "#{index}" ] rule_params = params [ :rules ] [ cls . dependency ] [ "#{index}" ] r...
parse with safety - we don t want to disconnect existing translations from those rules
11,057
def index @maps = Tr8n :: LanguageCaseValueMap . where ( "language_id = ? and (reported is null or reported = ?)" , tr8n_current_language . id , false ) @maps = @maps . where ( "keyword like ?" , "%#{params[:search]}%" ) unless params [ :search ] . blank? @maps = @maps . order ( "updated_at desc" ) . page ( page ) . pe...
used by a client app
11,058
def validate_current_translator if tr8n_current_user_is_translator? and tr8n_current_translator . blocked? trfe ( "Your translation privileges have been revoked. Please contact the site administrator for more details." ) return redirect_to ( Tr8n :: Config . default_url ) end return if Tr8n :: Config . current_user_is_...
make sure that the current user is a translator
11,059
def validate_language_management return if tr8n_current_user_is_admin? if tr8n_current_language . default? trfe ( "Only administrators can modify this language" ) return redirect_to ( tr8n_features_tabs . first [ :link ] ) end unless tr8n_current_user_is_translator? and tr8n_current_translator . manager? trfe ( "In ord...
make sure that the current user is a language manager
11,060
def client return @client unless @client . nil? @client = :: Elasticsearch :: Client . new ( hosts : hosts , retry_on_failure : true , log : true , logger : :: Logger . new ( 'es_client.log' , 10 , 1_024_000 ) ) end
Sets up the Elasticsearch client
11,061
def tr8n_client_sdk_tag ( opts = { } ) opts [ :scheduler_interval ] ||= Tr8n :: Config . default_client_interval opts [ :enable_inline_translations ] = ( Tr8n :: Config . current_user_is_translator? and Tr8n :: Config . current_translator . enable_inline_translations? and ( not Tr8n :: Config . current_language . defau...
Creates an instance of tr8nProxy object
11,062
def gen log ( "Creating zip archivement" , env_conf . name ) start = Time . now ebextensions = env_conf . ebextensions tmp_file = raw_zip_archive tmp_folder = Dir . mktmpdir Zip :: File . open ( tmp_file . path ) do | z | ebextensions . each do | ex_folder | z . remove_folder ex_folder unless ex_folder == ".ebextension...
Create zip archivement
11,063
def reload! clear @mixins . each do | file | mixin ( file ) end @callbacks . each do | callback | callback . call ( self ) end end
Reload all mixins .
11,064
def called_from location = caller . detect ( 'unknown:0' ) do | line | line . match ( / \/ \/ / ) . nil? end file , line , _ = location . split ( ':' ) { :file => file , :line => line } end
Return the first callee outside the liquid - ext gem
11,065
def read_line ( frame ) file , line_number = frame . split ( / / , 2 ) line_number = line_number . to_i lines = File . readlines ( file ) lines [ line_number - 1 ] end
Return the calling line
11,066
def method ( method_name ) __context__ = __actual_context__ ( method_name ) begin __context__ . method ( method_name ) rescue :: NoMethodError __context_singleton__ = __extract_singleton_class__ ( __context__ ) __context_singleton__ . public_instance_method ( method_name ) . bind ( __context__ ) end end
Returns a corresponding public method object of the actual context .
11,067
def public_method ( method_name , * required_contexts , direction : default_direction ) public_trigger ( * required_contexts , direction : direction ) . method ( method_name ) end
Gets the method object taken from the context that can respond to it . Considers only public methods .
11,068
def private_method ( method_name , * required_contexts , direction : default_direction ) private_trigger ( * required_contexts , direction : direction ) . method ( method_name ) end
Gets the method object taken from the context that can respond to it . Considers private methods and public methods .
11,069
def public_trigger ( * required_contexts , direction : default_direction ) PublicTrigger . new ( * required_contexts , context_direction : direction , & closure ) end
Factory method that instantiates a public trigger with the desired execution context the direction of method dispatching and the closure that needs to be performed .
11,070
def private_trigger ( * required_contexts , direction : default_direction ) PrivateTrigger . new ( * required_contexts , context_direction : direction , & closure ) end
Factory method that instantiates a private trigger with the desired execution context the direction of method dispatching and the closure that needs to be performed .
11,071
def trace ( bitmap = nil , params = nil , & block ) if block_given? do_trace ( bitmap || @bitmap , params || @params , & block ) else do_trace ( bitmap || @bitmap , params || @params ) end end
Trace the given + bitmap +
11,072
def method_missing ( name , * args , & block ) getter_name = name [ 0 .. - 2 ] if name =~ / / && ! respond_to? ( getter_name ) define_accessor ( getter_name , args . first ) else super end end
New values can be assigned to context on - the - fly but it s not possible to change anything .
11,073
def handle_user_input while true begin break if ! wait_for_prompt input = $stdin . gets . chomp! execute_action ( input , true ) rescue SignalException => e return false end end wait end
Expose the running process to manual input on the terminal and write stdout back to the user .
11,074
def execute_action action , silence = false action = action . strip if wait_for_prompt stdout . puts ( action ) unless silence @prompted = false process_runner . puts action end end
Execute a single action .
11,075
def run ( subscribe_opts : { } ) @rabbitmq_connection . start subscribe_opts = { block : true , manual_ack : true } . merge ( subscribe_opts ) queue . subscribe ( subscribe_opts ) do | delivery_info , headers , payload | begin message = Message . new ( payload , headers , delivery_info ) @statsd_client . increment ( "#...
Create a new consumer
11,076
def update_status sig = 0 pid_int = Integer ( "#{ @pid }" ) begin Process :: kill sig , pid_int true rescue Errno :: ESRCH false end end
Send an update signal to the process .
11,077
def bytes ( num = 10 ) num = [ [ 2048 , num . to_i ] . min , 0 ] . max numbers = [ ] response = REXML :: Document . new ( open ( "https://www.fourmilab.ch/cgi-bin/Hotbits?fmt=xml&nbytes=#{num}" ) ) status = REXML :: XPath . first ( response , "//status" ) case status . attributes [ 'result' ] . to_i when 200 data = REX...
Random bytes generator .
11,078
def should_repair_executable path return ( File . exists? ( path ) && ! File . directory? ( path ) && File . read ( path ) . match ( / \# \! \/ \/ / ) ) end
Determine if we should call + repair_executable + for the file at the provided + path + String .
11,079
def integers ( options = { } ) url_params = { max : clean ( options [ :max ] ) || 100 , min : clean ( options [ :min ] ) || 1 , num : clean ( options [ :num ] ) || 10 , base : clean ( options [ :base ] ) || 10 , rnd : 'new' , format : 'plain' , col : 1 } numbers = [ ] check_for_http_errors { response = open ( "#{@websi...
Random Integers Generator .
11,080
def sequence ( min , max ) url_params = { max : clean ( max ) || 10 , min : clean ( min ) || 1 , rnd : 'new' , format : 'plain' , col : 1 } sequence_numbers = [ ] check_for_http_errors { response = open ( "#{@website}sequences/?max=#{url_params[:max]}&min=#{url_params[:min]}&col=#{url_params[:col]}&rnd=#{url_params[:rn...
The Sequence Generator
11,081
def strings ( options = { } ) url_params = { num : clean ( options [ :num ] ) || 10 , len : clean ( options [ :len ] ) || 8 , digits : check_on_off ( options [ :digits ] ) || 'on' , unique : check_on_off ( options [ :unique ] ) || 'on' , upperalpha : check_on_off ( options [ :upperalpha ] ) || 'on' , loweralpha : check...
Random Strings Generator .
11,082
def add_library name , path if path . is_a? ( Array ) path = path . collect { | p | expand_local_path ( p ) } else path = expand_local_path path end library = Sprout :: Library . new ( :name => name , :path => path , :file_target => self ) libraries << library library end
Add a library to the package .
11,083
def add_executable name , path path = expand_local_path path executables << OpenStruct . new ( :name => name , :path => path , :file_target => self ) end
Add an executable to the RubyGem package .
11,084
def execute ( tool , options = '' ) Sprout . stdout . puts ( "#{tool} #{options}" ) runner = get_and_execute_process_runner ( tool , options ) error = runner . read_err result = runner . read if ( result . size > 0 ) Sprout . stdout . puts result end if ( error . size > 0 ) raise Sprout :: Errors :: ExecutionError . ne...
Creates a new process executes the command and returns whatever the process wrote to stdout or stderr .
11,085
def execute_thread tool , options = '' , prompt = nil , & block t = Thread . new do Thread . current . abort_on_exception = true runner = execute_silent ( tool , options ) Thread . current [ 'runner' ] = runner out = read_from runner . r , prompt , & block err = read_from runner . e , prompt , & block out . join && err...
Execute a new process in a separate thread and yield whatever output is written to its stderr and stdout .
11,086
def get_and_execute_process_runner tool , options = nil runner = get_process_runner runner . execute_open4 clean_path ( tool ) , options runner end
Get a process runner and execute the provided + executable + with the provided + options + .
11,087
def get_and_execute_process_runner tool , options = nil tool = clean_path find_tool ( tool ) runner = get_process_runner runner . execute_win32 tool , options runner end
Gets the process runner and calls platform - specific execute method
11,088
def build_new_exception e e . class . new ( e . message ) rescue Exception . new e . message end
Needs for cases when custom exceptions needs a several required arguments
11,089
def streak return [ ] if streaks . empty? streaks . last . last . date >= Date . today - 1 ? streaks . last : [ ] end
Set a custom streaks value that takes into account GitHub which makes available streak data for longer than a year
11,090
def guess_user ( names = [ ] ) names << Rugged :: Config . global [ 'github.user' ] if USE_RUGGED names << ENV [ 'USER' ] names . find { | name | name } || ( raise 'Failed to guess username' ) end
Guesses the user s name based on system environment
11,091
def real_streak_rewind ( partial_streak ) new_data = download ( partial_streak . first . date - 1 ) old_data = partial_streak . map ( & :to_a ) new_stats = GithubStats :: Data . new ( new_data + old_data ) partial_streak = new_stats . streaks . last return partial_streak if partial_streak . first . date != new_stats . ...
Set a custom longest_streak that takes into account GitHub s historical records
11,092
def download ( to_date = nil ) url = to_date ? @url + "?to=#{to_date.strftime('%Y-%m-%d')}" : @url res = Curl :: Easy . perform ( url ) code = res . response_code raise ( "Failed loading data from GitHub: #{url} #{code}" ) if code != 200 html = Nokogiri :: HTML ( res . body_str ) html . css ( '.day' ) . map do | x | x ...
Downloads new data from Github
11,093
def to_s ( format = :default ) title_suffix = " (#{title})" if has_title? formatted_name = "#{family_name.upcase}, #{given_name}#{title_suffix}" formatted_nhs_number = " (#{nhs_number})" if nhs_number . present? case format when :default then formatted_name when :long then "#{formatted_name}#{formatted_nhs_number}" els...
Overrides Personable mixin
11,094
def ssh_cleanup_known_hosts! ( hosts = [ host , public_ip ] ) hosts = [ hosts ] unless hosts . respond_to? :each hosts . compact . each do | name | system_run "ssh-keygen -R %s" % name end end
remove hostname and corresponding from known_hosts file . Avoids warning when reusing elastic_ip and less likely if amazone reassigns ip . By default removes both dns_name and ip
11,095
def to_h @raw . reduce ( Hash . new ( 0 ) ) do | acc , elem | acc . merge ( elem . date => elem . score ) end end
Create a data object and turn on caching
11,096
def streaks streaks = @raw . each_with_object ( Array . new ( 1 , [ ] ) ) do | point , acc | point . score . zero? ? acc << [ ] : acc . last << point end streaks . reject! ( & :empty? ) streaks end
All streaks for a user
11,097
def outliers return [ ] if scores . uniq . size < 5 scores . select { | x | ( ( mean - x ) / std_var ) . abs > GITHUB_MAGIC } . uniq end
Outliers of the set
11,098
def quartiles quartiles = Array . new ( 5 ) { [ ] } @raw . each_with_object ( quartiles ) do | elem , acc | acc [ quartile ( elem . score ) ] << elem end end
Return the list split into quartiles
11,099
def quartile ( score ) return nil if score < 0 || score > max . score quartile_boundaries . count { | bound | score > bound } end
Return the quartile of a given score