format snippets

How to format number of seconds as duration with PHP

Tagged php, duration, format, time, seconds  Languages php

A very sophisticated algorithm that will display the length of, for example, a video as 12:01:30.

function duration($seconds_count)
    {
        $delimiter  = ':';
        $seconds = $seconds_count % 60;
        $minutes = floor($seconds_count/60);
        $hours   = floor($seconds_count/3600);

        $seconds = str_pad($seconds, 2, "0", STR_PAD_LEFT);
        $minutes = str_pad($minutes, 2, "0", STR_PAD_LEFT).$delimiter;

        if($hours > 0)
        {
            $hours = str_pad($hours, 2, "0", STR_PAD_LEFT).$delimiter;
        }
        else
        {
            $hours = '';
        }

        return "$hours$minutes$seconds";
    }

How to parse Apache logs with Ruby

Tagged apache, statistics, logs, ruby, combined, format  Languages ruby

Only supports the combined format at the moment...

class ApacheLog
  FORMATS = {
    :combined => %r{^(\S+) - - \[(\S+ \+\d{4})\] "(\S+ \S+ [^"]+)" (\d{3}) (\d+|-) "(.*?)" "([^"]+)"$}
  }
  
  class << self
    def each_line(log_file, log_format = FORMATS[:combined])

      f = File.open(log_file, "r")

      f.each_line do|line|
        data = line.scan(log_format).flatten

        if data.empty?
          p "Line didn't match pattern: #{line}"

          next
        end

        yield data
      end
    end
  end
end


log_file   = ARGV[0]

ApacheLog.each_line(log_file) do |data|
  host, date, url_with_method, status, size, referrer, agent = data
end