idx
int64
0
24.9k
question
stringlengths
68
4.14k
target
stringlengths
9
749
20,400
def analysis @analysis ||= Hash . new do | h , time | time = time . to_sym times = @times [ time ] h [ time ] = MoreMath :: Sequence . new ( times ) end end
Returns a Hash of Sequence object for all of TIMES s time keys .
20,401
def cover? ( other ) time = self . case . compare_time . to_sym analysis [ time ] . cover? ( other . analysis [ time ] , self . case . covering . alpha_level . abs ) end
Return true if other s mean value is indistinguishable from this object s mean after filtering out the noise from the measurements with a Welch s t - Test . This mean s that differences in the mean of both clocks might not inidicate a real performance difference and may be caused by chance .
20,402
def to_a if @repeat >= 1 ( :: Bullshit :: Clock :: ALL_COLUMNS ) . map do | t | analysis [ t ] . elements end . transpose else [ ] end end
Returns the measurements as an array of arrays .
20,403
def take_time @time , times = Time . now , Process . times user_time = times . utime + times . cutime system_time = times . stime + times . cstime total_time = user_time + system_time [ @time . to_f , total_time , user_time , system_time ] end
Takes the times an returns an array consisting of the times in the order of enumerated in the TIMES constant .
20,404
def measure before = take_time yield after = take_time @repeat += 1 @times [ :repeat ] << @repeat @times [ :scatter ] << @scatter bs = self . case . batch_size . abs if bs and bs > 1 TIMES . each_with_index { | t , i | @times [ t ] << ( after [ i ] - before [ i ] ) / bs } else TIMES . each_with_index { | t , i | @times [ t ] << after [ i ] - before [ i ] } end @analysis = nil end
Take a single measurement . This method should be called with the code to benchmark in a block .
20,405
def detect_autocorrelation ( time ) analysis [ time . to_sym ] . detect_autocorrelation ( self . case . autocorrelation . max_lags . to_i , self . case . autocorrelation . alpha_level . abs ) end
Returns the q value for the Ljung - Box statistic of this + time + s analysis . detect_autocorrelation method .
20,406
def autocorrelation_plot ( time ) r = autocorrelation time start = @times [ :repeat ] . first ende = ( start + r . size ) ( start ... ende ) . to_a . zip ( r ) end
Returns the arrays for the autocorrelation plot the first array for the numbers of lag measured the second for the autocorrelation value .
20,407
def truncate_data ( offset ) for t in ALL_COLUMNS times = @times [ t ] @times [ t ] = @times [ t ] [ offset , times . size ] @repeat = @times [ t ] . size end @analysis = nil self end
Truncate the measurements stored in this clock starting from the integer + offset + .
20,408
def find_truncation_offset truncation = self . case . truncate_data slope_angle = self . case . truncate_data . slope_angle . abs time = self . case . compare_time . to_sym ms = analysis [ time ] . elements . reverse offset = ms . size - 1 @slopes = [ ] ModuleFunctions . array_window ( ms , truncation . window_size ) do | data | lr = LinearRegression . new ( data ) a = lr . a @slopes << [ offset , a ] a . abs > slope_angle and break offset -= 1 end offset < 0 ? 0 : offset end
Find an offset from the start of the measurements in this clock to truncate the initial data until a stable state has been reached and return it as an integer .
20,409
def load ( fp = file_path ) self . clock = self . case . class . clock . new self $DEBUG and warn "Loading '#{fp}' into clock." File . open ( fp , 'r' ) do | f | f . each do | line | line . chomp! line =~ / \s / and next clock << line . split ( / \t / ) end end self rescue Errno :: ENOENT end
Load the data of file + fp + into this clock .
20,410
def longest_name bmethods . empty? and return 0 bmethods . map { | x | x . short_name . size } . max end
Return the length of the longest_name of all these methods names .
20,411
def pre_run ( bc_method ) setup_name = bc_method . setup_name if respond_to? setup_name $DEBUG and warn "Calling #{setup_name}." __send__ ( setup_name ) end self . class . output . puts "#{bc_method.long_name}:" end
Output before + bc_method + is run .
20,412
def run_method ( bc_method ) pre_run bc_method clock = self . class . clock . __send__ ( self . class . clock_method , bc_method ) do __send__ ( bc_method . name ) end bc_method . clock = clock post_run bc_method clock end
Run only pre_run and post_run methods . Yield to the block if one was given .
20,413
def post_run ( bc_method ) teardown_name = bc_method . teardown_name if respond_to? teardown_name $DEBUG and warn "Calling #{teardown_name}." __send__ ( bc_method . teardown_name ) end end
Output after + bc_method + is run .
20,414
def output_filename ( name ) path = File . expand_path ( name , output_dir ) output File . new ( path , 'a+' ) end
Output results to the file named + name + .
20,415
def validate errors = [ ] schema_path = File . expand_path ( "../../../vendor/AppleDictionarySchema.rng" , __FILE__ ) schema = Nokogiri :: XML :: RelaxNG ( File . open ( schema_path ) ) schema . validate ( Nokogiri :: XML ( self . to_xml ) ) . each do | error | errors << error end if errors . size > 0 return errors else return true end end
Validate Dictionary xml with Apple s RelaxNG schema .
20,416
def to_xml xml = "" xml << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" xml << "<d:dictionary xmlns=\"http://www.w3.org/1999/xhtml\" " xml << "xmlns:d=\"http://www.apple.com/DTDs/DictionaryService-1.0.rng\">\n" @entries . each do | entry | next if entry . to_xml . nil? xml << entry . to_xml end xml << "</d:dictionary>" return xml end
Generates xml for Dictionary and Entry objects .
20,417
def return_hash ( final_vector ) case digest_length when 512 create_digest ( final_vector ) when 256 create_digest ( vector_from_array ( final_vector [ 0 .. 31 ] ) ) else raise ArgumentError , "digest length must be equal to 256 or 512, not #{digest_length}" end end
Method which return digest dependent on them length
20,418
def parse_options ( parser_configuration = { } ) raise_on_invalid_option = parser_configuration . has_key? ( :raise_on_invalid_option ) ? parser_configuration [ :raise_on_invalid_option ] : true parse_base_options = parser_configuration . has_key? ( :parse_base_options ) ? parser_configuration [ :parse_base_options ] : true logger . debug "parsing args: #{@args.inspect}, raise_on_invalid_option: #{raise_on_invalid_option}, parse_base_options: #{parse_base_options}" @option_parser ||= OptionParser . new option_parser . banner = help + "\n\nOptions:" if parse_base_options option_parser . on ( "--template [NAME]" , "Use a template to render output. (default=default.slim)" ) do | t | options [ :template ] = t . nil? ? "default.slim" : t @template = options [ :template ] end option_parser . on ( "--output FILENAME" , "Render output directly to a file" ) do | f | options [ :output ] = f @output = options [ :output ] end option_parser . on ( "--force" , "Overwrite file output without prompting" ) do | f | options [ :force ] = f end option_parser . on ( "-r" , "--repos a1,a2,a3" , "--asset a1,a2,a3" , "--filter a1,a2,a3" , Array , "List of regex asset name filters" ) do | list | options [ :filter ] = list end option_parser . on ( "--match [MODE]" , "Asset filter match mode. MODE=ALL (default), FIRST, EXACT, or ONE (fails if more than 1 match)" ) do | m | options [ :match ] = m || "ALL" options [ :match ] . upcase! unless [ "ALL" , "FIRST" , "EXACT" , "ONE" ] . include? ( options [ :match ] ) puts "invalid match mode option: #{options[:match]}" exit 1 end end end yield option_parser if block_given? logger . debug "args before reprocessing: #{@args.inspect}" begin option_parser . order! ( @args ) rescue OptionParser :: InvalidOption => e if raise_on_invalid_option puts "option error: #{e}" puts option_parser exit 1 else e . recover ( @args ) end end logger . debug "args before unknown collection: #{@args.inspect}" unknown_args = [ ] while unknown_arg = @args . shift logger . debug "unknown_arg: #{unknown_arg.inspect}" unknown_args << unknown_arg begin option_parser . order! ( @args ) rescue OptionParser :: InvalidOption => e if raise_on_invalid_option puts "option error: #{e}" puts option_parser exit 1 else e . recover ( @args ) end end end logger . debug "args after unknown collection: #{@args.inspect}" @args = unknown_args . dup logger . debug "args after reprocessing: #{@args.inspect}" logger . debug "configuration after reprocessing: #{@configuration.inspect}" logger . debug "options after reprocessing: #{@options.inspect}" option_parser end
Parse generic action options for all decendant actions
20,419
def asset_options result = options . deep_clone filters = args . dup filters += result [ :filter ] if result [ :filter ] result = result . merge ( :filter => filters ) unless filters . empty? type = result [ :type ] || asset_type result = result . merge ( :type => type ) result = result . merge ( :assets_folder => configuration [ :folders ] [ :assets ] ) if configuration [ :folders ] result = result . merge ( :base_folder => File . dirname ( configuration [ :configuration_filename ] ) ) if configuration [ :configuration_filename ] result end
asset options separated from assets to make it easier to override assets
20,420
def render ( view_options = configuration ) logger . debug "rendering" result = "" if template logger . debug "rendering with template : #{template}" view = AppView . new ( items , view_options ) view . template = template result = view . render else items . each_with_index do | item , index | result += "\n" unless index == 0 result += item . name . green + ":\n" if item . respond_to? ( :attributes ) attributes = item . attributes . deep_clone result += attributes . recursively_stringify_keys! . to_conf . gsub ( / \s / , '' ) result += "\n" end end end result end
Render items result to a string
20,421
def call ( env ) Rails . application . send :define_singleton_method , 'domain_name' do env [ 'SERVER_NAME' ] end unless Rails . application . respond_to? :fetch_domain Rails . application . send :define_singleton_method , 'fetch_domain' do if defined? ActiveRecord Domain . find_by ( nam : Rails . application . domain_name ) elsif defined? Mongoid Site . where ( 'domains.name' => Rails . application . domain_name ) . domains . first end end end Rails . application . send :define_singleton_method , 'site' do site = nil unless Rails . application . domain . nil? site = Rails . application . domain . site end site end Rails . application @app . call ( env ) end
Middleware initializer method which gets the app from previous middleware
20,422
def loop_eval ( input ) if input == '' @command_mode = :system and return end case @command_mode when :system if ! @result_storage ruby_command_code = "_ = system '#{ input }'\n" else temp_file = "/tmp/ripl-fresh_#{ rand 12345678901234567890 }" ruby_command_code = "_ = system '#{ input } 2>&1', :out => '#{ temp_file }'\n" case @result_operator when '=>' , '=>>' result_literal = "[]" formatted_result = "File.read('#{ temp_file }').split($/)" operator = @result_operator == '=>>' ? '+=' : '=' when '~>' , '~>>' result_literal = "''" formatted_result = "File.read('#{ temp_file }')" operator = @result_operator == '~>>' ? '<<' : '=' end ruby_command_code << %Q% #{ @result_storage } ||= #{ result_literal } #{ @result_storage } #{ operator } #{ formatted_result } FileUtils.rm '#{ temp_file }' % end ruby_command_code << "if !_ raise( SystemCallError.new $?.exitstatus ) end;" super @input = ruby_command_code when :mixed method_name , * args = * input . split super @input = "#{ method_name }(*#{ args })" else super end end
get result ( depending on
20,423
def to_s ptr = CF . CFDataGetBytePtr ( self ) if CF :: String :: HAS_ENCODING ptr . read_string ( CF . CFDataGetLength ( self ) ) . force_encoding ( Encoding :: ASCII_8BIT ) else ptr . read_string ( CF . CFDataGetLength ( self ) ) end end
Creates a ruby string from the wrapped data . The encoding will always be ASCII_8BIT
20,424
def set_build_vars warning_flags = ' -W -Wall' if 'release' == @config . release optimization_flags = " #{@config.optimization_release} -DRELEASE" else optimization_flags = " #{@config.optimization_dbg} -g" end @settings [ 'APP_SRC_DIR' ] = 'src/app' @settings [ 'LIB_SRC_DIR' ] = 'src/lib' @settings [ 'BUILD_DIR' ] = "#{build_dir}" @settings [ 'LIB_OUT' ] = "#{@settings['BUILD_DIR']}/libs" @settings [ 'APP_OUT' ] = "#{@settings['BUILD_DIR']}/apps" unless @settings [ 'OECORE_TARGET_SYSROOT' ] . nil? || @settings [ 'OECORE_TARGET_SYSROOT' ] . empty? @settings [ 'SYS_LFLAGS' ] = "-L#{@settings['OECORE_TARGET_SYSROOT']}/lib -L#{@settings['OECORE_TARGET_SYSROOT']}/usr/lib" end @settings [ 'LD_LIBRARY_PATH' ] = @settings [ 'LIB_OUT' ] @settings [ 'CXXFLAGS' ] += warning_flags + optimization_flags + " #{@config.language_std_cpp}" @settings [ 'CFLAGS' ] += warning_flags + optimization_flags + " #{@config.language_std_c}" if @settings [ 'PRJ_TYPE' ] == 'SOLIB' @settings [ 'CXXFLAGS' ] += ' -fPIC' @settings [ 'CFLAGS' ] += ' -fPIC' end @settings [ 'LDFLAGS' ] = @settings [ 'LDFLAGS' ] + " -L #{@settings['LIB_OUT']} #{@settings['SYS_LFLAGS']} -Wl,--no-as-needed -Wl,--start-group" end
Set common build variables
20,425
def reduce_libs_to_bare_minimum ( libs ) rv = libs . clone lib_entries = RakeOE :: PrjFileCache . get_lib_entries ( libs ) lib_entries . each_pair do | lib , entry | rv . delete ( lib ) unless RakeOE :: PrjFileCache . project_entry_buildable? ( entry , @target ) end rv end
Reduces the given list of libraries to bare minimum i . e . the minimum needed for actual platform
20,426
def libs_for_binary ( a_binary , visited = [ ] ) return [ ] if visited . include? ( a_binary ) visited << a_binary pre = Rake :: Task [ a_binary ] . prerequisites rv = [ ] pre . each do | p | next if ( File . extname ( p ) != '.a' ) && ( File . extname ( p ) != '.so' ) next if p =~ / \- \. / rv << File . basename ( p ) . gsub ( / \. \. / , '' ) rv += libs_for_binary ( p , visited ) end reduce_libs_to_bare_minimum ( rv . uniq ) end
Return array of library prerequisites for given file
20,427
def obj ( params = { } ) extension = File . extname ( params [ :source ] ) object = params [ :object ] source = params [ :source ] incs = compiler_incs_for ( params [ :includes ] ) + " #{@settings['LIB_INC']}" case when cpp_source_extensions . include? ( extension ) flags = @settings [ 'CXXFLAGS' ] + ' ' + params [ :settings ] [ 'ADD_CXXFLAGS' ] compiler = "#{@settings['CXX']} -x c++ " when c_source_extensions . include? ( extension ) flags = @settings [ 'CFLAGS' ] + ' ' + params [ :settings ] [ 'ADD_CFLAGS' ] compiler = "#{@settings['CC']} -x c " when as_source_extensions . include? ( extension ) flags = '' compiler = "#{@settings['AS']}" else raise "unsupported source file extension (#{extension}) for creating object!" end sh "#{compiler} #{flags} #{incs} -c #{source} -o #{object}" end
Creates compilation object
20,428
def solve_equivalent_fractions last = 0 array = Array . new @reduced_row_echelon_form . each do | x | array = last . gcdlcm ( x . last . denominator ) last = x . last . denominator end array . max end
from the reduced row echelon form we are left with a set of equivalent fractions to transform into a whole number we do this by using the gcdlcm method
20,429
def apply_solved_equivalent_fractions_to_fraction int = self . solve_equivalent_fractions answer = [ ] @reduced_row_echelon_form . each do | row | answer << row . last * int end answer << int count = 0 @balanced = Hash . new @left_system_of_equations . each do | x , v | answer [ count ] @left_system_of_equations [ x ] = answer [ count ] . to_i . abs unless answer [ count ] . nil? count += 1 end @right_system_of_equations . each do | x , v | answer [ count ] @right_system_of_equations [ x ] = answer [ count ] . to_i . abs unless answer [ count ] . nil? count += 1 end answer @balanced = { left : @left_system_of_equations , right : @right_system_of_equations } self . balanced_string . gsub ( / \D \D / , '\1\2' ) end
Now that we have the whole number from solve_equivalent_fractions we must apply that to each of the fractions to solve for the balanced equation
20,430
def reduced_row_echelon_form ( ary ) lead = 0 rows = ary . size cols = ary [ 0 ] . size rary = convert_to_rational ( ary ) catch :done do rows . times do | r | throw :done if cols <= lead i = r while rary [ i ] [ lead ] == 0 i += 1 if rows == i i = r lead += 1 throw :done if cols == lead end end rary [ i ] , rary [ r ] = rary [ r ] , rary [ i ] v = rary [ r ] [ lead ] rary [ r ] . collect! { | x | x /= v } rows . times do | i | next if i == r v = rary [ i ] [ lead ] rary [ i ] . each_index { | j | rary [ i ] [ j ] -= v * rary [ r ] [ j ] } end lead += 1 end end rary end
returns an 2 - D array where each element is a Rational
20,431
def http_status_exception ( exception ) @exception = exception render_options = { :template => exception . template , :status => exception . status } render_options [ :layout ] = exception . template_layout if exception . template_layout render ( render_options ) rescue ActionView :: MissingTemplate head ( exception . status ) end
The default handler for raised HTTP status exceptions . It will render a template if available or respond with an empty response with the HTTP status corresponding to the exception .
20,432
def append ( event , frame , arg ) item = EventStruct . new ( event , arg , frame ) @pos = self . succ_pos @marks . shift if @marks [ 0 ] == @pos @buf [ @pos ] = item @size += 1 unless @maxsize && @size == @maxsize end
Add a new event dropping off old events if that was declared marks are also dropped if buffer has a limit .
20,433
def check_code_name ( cname ) [ cname . pluralize , cname . singularize ] . each { | name | return false if root . descendants . map { | t | t . code_name unless t . code_name == cname } . include? ( name ) } true end
Check if there is code_name in same branch
20,434
def render context = nil , template_or_src = nil , & block compiled_template = compile ( template_or_src , & block ) context . instance_eval compiled_template end
render accepts source or block evaluates the resulting string of ruby in the context provided
20,435
def configure ( options ) configuration = { :options => { :verbose => false , :color => 'AUTO' , :short => false , :unmodified => 'HIDE' , :match => 'ALL' , :list => 'ALL' } , :commands => [ 'diff' , 'grep' , 'log' , 'ls-files' , 'show' , 'status' ] } config = options [ :config ] if config . nil? config = [ File . join ( @working_dir , "repo.conf" ) , File . join ( @working_dir , ".repo.conf" ) , File . join ( @working_dir , "repo_manager" , "repo.conf" ) , File . join ( @working_dir , ".repo_manager" , "repo.conf" ) , File . join ( @working_dir , "config" , "repo.conf" ) , File . expand_path ( File . join ( "~" , ".repo.conf" ) ) , File . expand_path ( File . join ( "~" , "repo.conf" ) ) , File . expand_path ( File . join ( "~" , "repo_manager" , "repo.conf" ) ) , File . expand_path ( File . join ( "~" , ".repo_manager" , "repo.conf" ) ) ] . detect { | filename | File . exists? ( filename ) } end if config && File . exists? ( config ) logger . debug "reading configuration file: #{config}" config_contents = YAML . load ( ERB . new ( File . open ( config , "rb" ) . read ) . result ) configuration . merge! ( config_contents . symbolize_keys! ) if config_contents && config_contents . is_a? ( Hash ) else raise "config file not found" if options [ :config ] end configuration [ :configuration_filename ] = config configuration . recursively_symbolize_keys! configuration [ :options ] . merge! ( options ) configuration end
read options from YAML config
20,436
def fetch_in_batches ( opts = { } ) opts [ :batch_size ] ||= 1000 paged_query = opts . delete ( :_paged_query ) || self . clone return to_enum ( :fetch_in_batches , opts . merge ( _paged_query : paged_query ) ) unless block_given? paged_query . stateless_page_size = opts [ :batch_size ] paged_query . paging_state = nil loop do break if paged_query . result && paged_query . result . last_page? raise page_size_changed_error ( opts [ :batch_size ] ) if opts [ :batch_size ] != paged_query . stateless_page_size batch = paged_query . fetch paged_query . paging_state = paged_query . result . paging_state yield batch end end
Yields each batch of records that was found by the options as an array .
20,437
def search_for ( name ) url = build_query ( name ) url += '/fuzzy/web' data = @client . query ( url ) sleep ( 1 ) data [ "results" ] end
Search for show
20,438
def valid_input? ( input ) case @attributes [ :type ] when :boolean [ true , false ] . include? ( input ) when :enum raise MissingValuesError unless @attributes [ :values ] raise InvalidValuesError unless @attributes [ :values ] . class == Array @attributes [ :values ] . include? ( input ) when :string format = @attributes [ :format ] || :anything Validator . valid_input? ( format , input ) when :number [ Integer , Fixnum ] . include? ( input . class ) when :timestamp true else false end end
Check if a value provided will suffice for the way this argument is defined .
20,439
def fetch ( args = { } ) args . each do | k , v | setter = "#{k}=" send ( setter , v ) if respond_to? setter end execute result end
Returns array of rows or empty array
20,440
def inspect cf = CF :: String . new ( CF . CFCopyDescription ( self ) ) cf . to_s . tap { cf . release } end
Returns a ruby string containing the output of CFCopyDescription for the wrapped object
20,441
def equals? ( other ) if other . is_a? ( CF :: Base ) @ptr . address == other . to_ptr . address else false end end
Uses CFHash to return a hash code
20,442
def color_chart [ 0 , 1 , 4 , 5 , 7 ] . each do | attr | puts '----------------------------------------------------------------' puts "ESC[#{attr};Foreground;Background" 30 . upto ( 37 ) do | fg | 40 . upto ( 47 ) do | bg | print "\033[#{attr};#{fg};#{bg}m #{fg};#{bg} " end puts "\033[0m" end end end
Displays a chart of all the possible ANSI foreground and background color combinations .
20,443
def validate_paramified_params self . class . paramify_methods . each do | method | params = send ( method ) transfer_errors_from ( params , TermMapper . scope ( params . group ) ) if ! params . valid? end end
Helper method to validate paramified params and to transfer any errors into the handler .
20,444
def perform_after ( time , block = nil ) task = Concurrent :: ScheduledTask . new ( time ) do block = -> ( ) { yield } unless block self . async . perform_now block end task . execute task end
Perform block after given period
20,445
def set_by_path ( path , value , target = @ini ) keys = path . split ( '/' ) until keys . one? target [ keys . first ] = { } unless target [ keys . first ] . is_a? ( Hash ) target = target [ keys . shift ] end target [ keys . shift ] = value end
Sets the value of a key in a hash - of - hashes via a unix - style path .
20,446
def get_by_path ( path , target = @ini ) keys = path . split ( '/' ) target = target [ keys . shift ] until keys . empty? target end
Gets the value of a key in a hash - of - hashes via a unix - style path .
20,447
def process_property ( property , value ) value . chomp! return if property . empty? and value . empty? return if value . sub! ( %r/ \\ \s \z / , '' ) property . strip! value . strip! parse_error if property . empty? set_by_path ( CGI :: unescape ( property ) , unescape_value ( value . dup ) , current_section ) property . slice! ( 0 , property . length ) value . slice! ( 0 , value . length ) nil end
Processes a given name - value pair adding them to the current INI database .
20,448
def init? ( path = Dir . pwd ) begin MiniGit . new ( path ) rescue Exception return false end true end
Check if a git directory has been initialized
20,449
def commits? ( path ) res = false Dir . chdir ( path ) do _stdout , _stderr , exit_status = Open3 . capture3 ( "git rev-parse HEAD" ) res = ( exit_status . to_i . zero? ) end res end
Check if the repositories already holds some commits
20,450
def command? ( cmd ) cg = MiniGit :: Capturing . new cmd_list = cg . help :a => true l = cmd_list . split ( "\n\n" ) l . shift subl = l . each_index . select { | i | l [ i ] =~ / \s \s / } return false if subl . empty? subl . any? { | i | l [ i ] . split . include? ( cmd ) } end
Check the availability of a given git command
20,451
def init ( path = Dir . pwd , _options = { } ) [ 'user.name' , 'user.email' ] . each do | userconf | next unless MiniGit [ userconf ] . nil? warn "The Git global configuration '#{userconf}' is not set so" warn "you should *seriously* consider setting them by running\n\t git config --global #{userconf} 'your_#{userconf.sub(/\./, '_')}'" default_val = ENV [ 'USER' ] default_val += '@domain.org' if userconf =~ / / warn "Now putting a default value '#{default_val}' you could change later on" run %( git config --global #{userconf} "#{default_val}" ) end exit_status = 1 Dir . mkdir ( path ) unless Dir . exist? ( path ) Dir . chdir ( path ) do execute "git init" unless FalkorLib . config . debug exit_status = $? . to_i end exit_status end
Initialize a git repository
20,452
def create_branch ( branch , path = Dir . pwd ) g = MiniGit . new ( path ) error "not yet any commit performed -- You shall do one" unless commits? ( path ) g . branch branch . to_s end
Create a new branch
20,453
def delete_branch ( branch , path = Dir . pwd , opts = { :force => false } ) g = MiniGit . new ( path ) error "'#{branch}' is not a valid existing branch" unless list_branch ( path ) . include? ( branch ) g . branch ( ( opts [ :force ] ) ? :D : :d ) => branch . to_s end
Delete a branch .
20,454
def grab ( branch , path = Dir . pwd , remote = 'origin' ) exit_status = 1 error "no branch provided" if branch . nil? branches = FalkorLib :: Git . list_branch ( path ) if branches . include? "remotes/#{remote}/#{branch}" info "Grab the branch '#{remote}/#{branch}'" exit_status = execute_in_dir ( FalkorLib :: Git . rootdir ( path ) , "git branch --track #{branch} #{remote}/#{branch}" ) else warning "the remote branch '#{remote}/#{branch}' cannot be found" end exit_status end
Grab a remote branch
20,455
def publish ( branch , path = Dir . pwd , remote = 'origin' ) exit_status = 1 error "no branch provided" if branch . nil? branches = FalkorLib :: Git . list_branch ( path ) Dir . chdir ( FalkorLib :: Git . rootdir ( path ) ) do if branches . include? "remotes/#{remote}/#{branch}" warning "the remote branch '#{remote}/#{branch}' already exists" else info "Publish the branch '#{branch}' on the remote '#{remote}'" exit_status = run %( git push #{remote} #{branch}:refs/heads/#{branch} git fetch #{remote} git branch -u #{remote}/#{branch} #{branch} ) end end exit_status end
Publish a branch on the remote
20,456
def list_files ( path = Dir . pwd ) g = MiniGit . new ( path ) g . capturing . ls_files . split end
List the files currently under version
20,457
def last_tag_commit ( path = Dir . pwd ) res = "" g = MiniGit . new ( path ) unless ( g . capturing . tag :list => true ) . empty? res = ( g . capturing . rev_list :tags => true , :max_count => 1 ) . chomp end res end
list_tag Get the last tag commit or nil if no tag can be found
20,458
def remotes ( path = Dir . pwd ) g = MiniGit . new ( path ) g . capturing . remote . split end
tag List of Git remotes
20,459
def subtree_init? ( path = Dir . pwd ) res = true FalkorLib . config . git [ :subtrees ] . keys . each do | dir | res &&= File . directory? ( File . join ( path , dir ) ) end res end
Check if the subtrees have been initialized . Actually based on a naive check of sub - directory existence
20,460
def subtree_up ( path = Dir . pwd ) error "Unable to pull subtree(s): Dirty Git repository" if FalkorLib :: Git . dirty? ( path ) exit_status = 0 git_root_dir = rootdir ( path ) Dir . chdir ( git_root_dir ) do FalkorLib . config . git [ :subtrees ] . each do | dir , conf | next if conf [ :url ] . nil? remote = dir . gsub ( / \/ / , '-' ) branch = ( conf [ :branch ] . nil? ) ? 'master' : conf [ :branch ] remotes = FalkorLib :: Git . remotes info "Pulling changes into subtree '#{dir}' using remote '#{remote}/#{branch}'" raise IOError , "The git remote '#{remote}' is not configured" unless remotes . include? ( remote ) info "\t\\__ fetching remote '#{remotes.join(',')}'" FalkorLib :: Git . fetch ( git_root_dir ) raise IOError , "The git subtree directory '#{dir}' does not exists" unless File . directory? ( File . join ( git_root_dir , dir ) ) info "\t\\__ pulling changes" exit_status = execute "git subtree pull --prefix #{dir} --squash #{remote} #{branch}" end end exit_status end
Pull the latest changes assuming the git repository is not dirty
20,461
def local_init ( bucket_count , bucket_width , start_priority ) @width = bucket_width old = @buckets @buckets = if @cached_buckets == nil Array . new ( bucket_count ) { [ ] } else n = @cached_buckets . size if bucket_count < n @cached_buckets . slice! ( bucket_count , n ) else @cached_buckets . fill ( n , bucket_count - n ) { [ ] } end @cached_buckets end @cached_buckets = old @last_priority = start_priority i = start_priority / bucket_width @last_bucket = ( i % bucket_count ) . to_i @bucket_top = ( i + 1 ) * bucket_width + 0.5 * bucket_width @shrink_threshold = bucket_count / 2 - 2 @expand_threshold = 2 * bucket_count end
Initializes a bucket array within
20,462
def resize ( new_size ) return unless @resize_enabled bucket_width = new_width local_init ( new_size , bucket_width , @last_priority ) i = 0 while i < @cached_buckets . size bucket = @cached_buckets [ i ] @size -= bucket . size while obj = bucket . pop self << obj end i += 1 end end
Resize buckets to new_size .
20,463
def new_width return 1.0 if @size < 2 n = if @size <= 5 @size else 5 + ( @size / 10 ) . to_i end n = 25 if n > 25 tmp_last_bucket = @last_bucket tmp_last_priority = @last_priority tmp_bucket_top = @bucket_top @resize_enabled = false tmp = Array . new ( n ) average = 0.0 i = 0 while i < n tmp [ i ] = self . pop average += tmp [ i ] . time_next - tmp [ i - 1 ] . time_next if i > 0 i += 1 end average = average / ( n - 1 ) . to_f self << tmp [ 0 ] new_average = 0.0 j = 0 i = 1 while i < n sub = tmp [ i ] . time_next - tmp [ i - 1 ] . time_next if sub < average * 2.0 new_average += sub j += 1 end self << tmp [ i ] i += 1 end new_average = new_average / j . to_f @resize_enabled = true @last_bucket = tmp_last_bucket @last_priority = tmp_last_priority @bucket_top = tmp_bucket_top if new_average > 0.0 new_average * 3.0 elsif average > 0.0 average * 2.0 else 1.0 end end
Calculates the width to use for buckets
20,464
def transition_stats if done? @transition_stats ||= ( stats = { } hierarchy = @processor . children . dup i = 0 while i < hierarchy . size child = hierarchy [ i ] if child . model . coupled? hierarchy . concat ( child . children ) else stats [ child . model . name ] = child . transition_stats end i += 1 end total = Hash . new ( 0 ) stats . values . each { | h | h . each { | k , v | total [ k ] += v } } stats [ :TOTAL ] = total stats ) end end
Returns the number of transitions per model along with the total
20,465
def partial ( filename ) filename = partial_path ( filename ) raise "unable to find partial file: #{filename}" unless File . exists? ( filename ) contents = File . open ( filename , "rb" ) { | f | f . read } contents . gsub! ( / \r \n / , "\n" ) if contents . match ( "\r\n" ) contents end
render a partial
20,466
def partial_path ( filename ) return filename if filename . nil? || Pathname . new ( filename ) . absolute? if template base_folder = File . dirname ( template ) filename = File . expand_path ( File . join ( base_folder , filename ) ) return filename if File . exists? ( filename ) end filename = File . expand_path ( File . join ( FileUtils . pwd , filename ) ) return filename if File . exists? ( filename ) filename = File . expand_path ( File . join ( '../templates' , filename ) , __FILE__ ) end
full expanded path to the given partial
20,467
def set_logger @logger = if block_given? yield elsif defined? ( Rails ) Rails . logger else logger = Logger . new ( STDOUT ) logger . level = Logger :: DEBUG logger end end
Sets the client logger object . Execution is yielded to passed + block + to set customize and returning a logger instance .
20,468
def valid_input? ( key , string ) raise InvalidFormatError unless valid_regex_format? ( key ) boolarray = validation_regex [ key ] . map do | regxp | ( string =~ regxp ) == 0 ? true : false end return true if boolarray . include? ( true ) false end
Core method of the module which attempts to check if a provided string matches any of the regex s as identified by the key
20,469
def validation_regex { :address => [ HOSTNAME_REGEX , DOMAIN_REGEX , IP_V4_REGEX , IP_V6_REGEX ] , :anything => [ / / ] , :bool => [ TRUEFALSE_REGEX ] , :command => [ SIMPLE_COMMAND_REGEX ] , :gsm_adapter => [ ADAPTER_REGEX ] , :hostname => [ HOSTNAME_REGEX ] , :interface => [ INTERFACE_REGEX ] , :ip => [ IP_V4_REGEX , IP_V6_REGEX ] , :ipv6 => [ IP_V6_REGEX ] , :ipv4 => [ IP_V4_REGEX ] , :json => [ JsonValidator ] , :mac => [ MAC_REGEX ] , :snapi_function_name => [ SNAPI_FUNCTION_NAME ] , :on_off => [ ON_OFF_REGEX ] , :port => [ PORT_REGEX ] , :uri => [ URI_REGEX ] , } end
A helper dictionary which returns and array of valid Regexp patterns in exchange for a valid key
20,470
def load_tasks return if @loaded Dir . glob ( File . join ( File . dirname ( __FILE__ ) , '**' , '*.rb' ) ) . each do | task | if task . match ( / \. / ) :: Thor :: Util . load_thorfile task end end Dir . glob ( File . join ( File . dirname ( __FILE__ ) , '**' , '*.rb' ) ) . each do | task | unless task . match ( / \. / ) :: Thor :: Util . load_thorfile task end end if user_tasks_folder Dir . glob ( File . join ( [ user_tasks_folder , '**' , '*.{rb,thor}' ] ) ) . each { | task | :: Thor :: Util . load_thorfile task if task . match ( / \. / ) } Dir . glob ( File . join ( [ user_tasks_folder , '**' , '*.{rb,thor}' ] ) ) . each { | task | :: Thor :: Util . load_thorfile task unless task . match ( / \. / ) } end @loaded = true end
load all the tasks in this gem plus the user s own repo_manager task folder
20,471
def task_help ( name ) load_tasks klass , task = find_by_namespace ( name ) $thor_runner = true klass . task_help ( shell , task ) end
display help for the given task
20,472
def list_tasks load_tasks $thor_runner = true list = [ ] Thor :: Base . subclasses . each do | klass | list += klass . printable_tasks ( false ) unless klass == Thor end list . sort! { | a , b | a [ 0 ] <=> b [ 0 ] } title = "repo_manager tasks" shell . say shell . set_color ( title , :blue , bold = true ) shell . say "-" * title . size shell . print_table ( list , :ident => 2 , :truncate => true ) end
display a list of tasks for user display
20,473
def list_bare_tasks load_tasks Thor :: Base . subclasses . each do | klass | unless klass == Thor klass . tasks . each do | t | puts "#{klass.namespace}:#{t[0]}" end end end end
display a list of tasks for CLI completion
20,474
def search_for_by_provider ( name , provider ) url = build_query ( name ) url += '/fuzzy/' + provider + "/web" data = @client . query ( url ) data [ "results" ] end
Search by provider
20,475
def search_by_db_id ( id , type ) url = @base_url url += "/search/id/" case type when "tvdb" url += "tvdb/" url += id . to_s when "themoviedb" url += "themoviedb/" url += id . to_s when "imdb" url += "imdb/" url += id else puts "That id type does not exist" return end @client . query ( url ) end
Search for show by external db id
20,476
def show_information ( name ) id = self . search_for ( name ) . first [ "id" ] url = @base_url url += "/show/" + id . to_s @client . query ( url ) end
Get all tv show info
20,477
def min_time_next tn = DEVS :: INFINITY if ( obj = @scheduler . peek ) tn = obj . time_next end tn end
Returns the minimum time next in all children
20,478
def max_time_last max = 0 i = 0 while i < @children . size tl = @children [ i ] . time_last max = tl if tl > max i += 1 end max end
Returns the maximum time last in all children
20,479
def order ( types ) types . map { | type | AcceptMediaType . new ( type ) } . reverse . sort . reverse . select { | type | type . valid? } . map { | type | type . range } end
Order media types by quality values remove invalid types and return media ranges .
20,480
def set ( key , value ) types [ key . to_sym ] = ( value == [ ] ? [ ] : ( value . is_a? ( Symbol ) ? value : nil ) ) messages [ key . to_sym ] = value end
Set messages for + key + to + value +
20,481
def delete ( key ) key = key . to_sym types . delete ( key ) messages . delete ( key ) end
Delete messages for + key +
20,482
def empty? all? { | k , v | v && v . empty? && ! v . is_a? ( String ) } end
Returns true if no errors are found false otherwise . If the error message is a string it can be empty .
20,483
def add_on_empty ( attributes , options = { } ) [ attributes ] . flatten . each do | attribute | value = @base . send ( :read_attribute_for_validation , attribute ) is_empty = value . respond_to? ( :empty? ) ? value . empty? : false add ( attribute , :empty , options ) if value . nil? || is_empty end end
Will add an error message to each of the attributes in + attributes + that is empty .
20,484
def start message = 'Guard::Inch is running' message << ' in pedantic mode' if options [ :pedantic ] message << ' and inspecting private fields' if options [ :private ] :: Guard :: UI . info message run_all if options [ :all_on_start ] end
configure a new instance of the plugin
20,485
def update_fields_values ( params ) params || return fields . each { | f | f . find_or_create_type_object ( self ) . tap { | t | t || next params [ f . code_name . to_sym ] . tap { | v | v && t . value = v } t . save } } end
Update all fields values with given params .
20,486
def find_page_in_branch ( cname ) Template . find_by ( code_name : cname . singularize ) . tap { | t | t || return ( descendants . where ( template_id : t . id ) if cname == cname . pluralize ) . tap { | r | r ||= [ ] return r . empty? ? ancestors . find_by ( template_id : t . id ) : r } } end
Search page by template code_name in same branch of pages and templates . It allows to call page . category . brand . series . model etc .
20,487
def as_json ( options = { } ) { name : self . name , title : self . title } . merge ( options ) . tap do | options | fields . each { | f | options . merge! ( { f . code_name . to_sym => f . get_value_for ( self ) } ) } end end
Returns page hash attributes with fields .
20,488
def meta_tag ( options , open = false , escape = true ) tag ( :meta , options , open , escape ) end
Meta Tag helper
20,489
def bit_mask ( name , flags , type = :uint ) bit_mask = BitMask . new ( flags , type ) typedef ( bit_mask , name ) return bit_mask end
Defines a new bitmask .
20,490
def build_up_commands local_versions . select { | v | v > current_version && v <= target_version } . map { | v | ApplyCommand . new ( v ) } end
install all local versions since current
20,491
def build_down_commands rollbacks = rollback_versions . map { | v | RollbackCommand . new ( v ) } missing = missing_versions_before ( rollbacks . last . version ) . map { | v | ApplyCommand . new ( v ) } rollbacks + missing end
rollback all versions applied past the target and apply missing versions to get to target
20,492
def missing_versions_before ( last_rollback ) return [ ] unless last_rollback rollback_index = applied_versions . index ( last_rollback ) stop = if rollback_index == applied_versions . length - 1 Version . new ( '0' ) else applied_versions [ rollback_index + 1 ] end return [ ] if stop == target_version local_versions . select { | v | v > stop && v <= target_version } end
versions that are not applied yet but need to get applied to get up the target version
20,493
def field ( name , ** options ) name = name . to_sym definitions [ name ] = options proxy . instance_eval do define_method ( name ) { fields [ name ] } define_method ( "#{name}=" ) { | value | fields [ name ] = value } end end
Declare new form field
20,494
def changes ( of_type : nil , in_range : nil ) resources . select do | r | is_of_type = of_type ? r . change == of_type : true is_in_range = in_range ? in_range . cover? ( r . modified_time ) : true is_of_type && is_in_range end end
Filters the list of changes by change type modification time or both .
20,495
def on_idle ( op , * args ) @idle_mutex . synchronize { @idle . insert ( 0 , Act . new ( op , args ) ) } @loop . wakeup ( ) if RUNNING == @state end
Queues an operation and arguments to be called when the Actor is has no other requests to process .
20,496
def method_missing ( m , * args , & blk ) raise NoMethodError . new ( "undefined method '#{m}' for #{self.class}" , m , args ) unless respond_to? ( m , true ) ask ( m , * args ) end
When an attempt is made to call a private method of the Actor it is places on the processing queue . Other methods cause a NoMethodError to be raised as it normally would .
20,497
def findings = ( findings ) raise TypeException unless findings . is_a? ( Array ) findings . each { | item | raise TypeException unless item . is_a? ( StatModule :: Finding ) raise DuplicateElementException if @findings . include? ( item ) @findings . push ( item ) } end
Initialize new Stat object
20,498
def print_header @finding_print_index = 0 hash = { } hash [ 'statVersion' ] = @statVersion hash [ 'process' ] = @process hash [ 'findings' ] = [ ] result = hash . to_json result = result [ 0 .. result . length - 3 ] puts ( result ) puts $stdout . flush end
Prints header of STAT object in json format Header contains statVersion process and optional array of findings
20,499
def print_finding if @finding_print_index < @findings . length result = @findings [ @finding_print_index ] . to_json result += ',' unless @finding_print_index >= @findings . length - 1 puts result puts $stdout . flush @finding_print_index += 1 else raise IndexOutOfBoundException end end
Prints one finding in json format .