module Pbw
	class Container
		include ::Mongoid::Document
    	include ::Mongoid::Timestamps

    	field :name, type: String
    	validates :name, presence: true

    	embeds_many :item_containers, class_name: '::Pbw::ItemContainer'
    	embeds_many :attached_processes, class_name: '::Pbw::AttachedProcess'
    	embeds_many :tokens, class_name: '::Pbw::Token'
    	embeds_many :constraints, class_name: '::Pbw::Constraint'
    	embeds_many :capabilities, class_name: '::Pbw::Capability'
    	embeds_many :triggers, class_name: '::Pbw::Trigger'

    	attr_accessible :name

    	# STUB METHODS

    	def before_token_enters(token)
	        # stub method
	        true
	    end

	    def after_token_enters(token)
	        # stub method
	    end

	    def before_add_item(item, quantity)
	        # stub method
	        true
	    end

	    def after_add_item(item, quantity)
	        # stub method
	    end

	    def before_remove_item(item, quantity)
	        # stub method
	        true
	    end

	    def after_remove_item(item, quantity)
	        # stub method
	    end

	    # ATTACHED PROCESSES

	    def attach_tick_process(process, ticks_to_wait=0)
	        self.attached_processes << AttachedProcess.build(process: process, tickable: true, ticks_waiting: ticks_to_wait)
	        save!
	    end

	    def attach_update_process(process, updates_to_wait=0)
	        self.attached_processes << AttachedProces.build(process: process, updatable: true, updates_waiting: updates_to_wait)
	        save!
	    end

	    # ITEM CONTAINERS

	    def item_container(item)
	    	self.item_containers.where(item: item).first
	    end

	    def count_item(item)
	        container = item_container(item)
	        container ? container.quantity : 0
	    end

	    def add_item!(item, quantity)
	        raise PbwArgumentError('Invalid quantity') unless quantity && quantity.responds_to?(:abs)
	        raise PbwArgumentError('Invalid item') unless item
	        return remove_item!(item, quantity.abs) if quantity < 0
	        return false unless before_add_item(item,quantity)
	        container = item_container(item)
	        unless container
	        	container = ItemContainer.build(item: item, quantity: 0)
	        	self.item_containers << container
	        	save!
	    	end
	    	container.add_item(quantity_to_add)
	    end

	    def remove_item!(item, quantity)
	        raise PbwArgumentError('Invalid quantity') unless quantity && quantity.responds_to?(:abs)
	        raise PbwArgumentError('Invalid item') unless item
	        return add_item!(item, quantity.abs) if quantity < 0
	        container = item_container(item)
	        return false unless container
	        return false unless before_remove_item(item,quantity)
	        container.remove_item(quantity)
	    end

	    # TOKENS

	    def has_token?(token)
	    	token && token._id && self.tokens.where(_id: token._id).first
	    end

	    def add_token!(token)
	    	raise PbwArgumentError('Invalid token') unless token
	    	return false if has_token?(token)
	    	self.tokens << token
	    	save!
	    	self
	    end

	    def remove_token!(token)
	    	ct = has_token?(token)
	    	return false unless ct
	    	ct.destroy
	    	self
	    end

	    # CONSTRAINTS

	    def add_constraint!(constraint)
	        raise PbwArgumentError('Invalid constraint') unless constraint
	        return false if has_constraint?(constraint)
	        return false unless constraint.before_add(self)
	        self.constraints << constraint
	        save!
	        constraint.after_add(self)
	        self
	    end

	    def has_constraint?(constraint)
	        constraint && constraint._id && self.constraints.where(_id: constraint._id).first
	    end

	    def remove_constraint!(constraint)
	        cc = has_constraint?(constraint)
	        return false unless cc && cc.before_remove(self)
	        if cc
	            cc.destroy
	            constraint.after_remove(self)
	        end
	        self
	    end

	    # CAPABILITIES

	    def add_capability!(capability)
	        raise PbwArgumentError('Invalid capability') unless capability
	        return false if has_capability?(capability)
	        return false unless capability.before_add(self)
	        self.capabilities << capability
	        save!
	        capability.after_add(self)
	        self
	    end

	    def has_capability?(capability)
	        capability && capability._id && self.container_capabilities.where(_id: capability._id).first
	    end

	    def remove_capability!(capability)
	        cc = has_capability?(capability)
	        return false unless cc && cc.before_remove(self)
	        if cc
	            cc.destroy
	            capability.after_remove(self)
	        end
	        self
	    end

	    # TRIGGERS

	    def add_trigger!(trigger)
	        raise PbwArgumentError('Invalid trigger') unless trigger
	        return false if has_trigger?(trigger)
	        self.triggers << trigger
	        save!
	        trigger.after_add(self)
	        self
	    end

	    def has_trigger?(trigger)
	        trigger && trigger._id && self.triggers.where(_id: trigger._id).first
	    end

	    def remove_trigger!(trigger)
	        ct = has_trigger?(trigger)
	        if ct
	            ct.destroy
	        end
	        self
	    end

	    def check_triggers!
	        self.triggers.each{|ct| ct.trigger.check! }
	    end

	    def check_constraints_and_capabilities(&changeset)
	        self.constraints.any?{|cc| !cc.before_process(self, changeset)}
	        self.constraints.any?{|cc| !cc.before_process(self, changeset)}
	    end
	end
end


require 'net/http'
require 'json'
require 'uri'

module Ropenstack
=begin
	* Name: Rest
	* Description: A generic wrapper for basic rest functions with JSON data which return ruby hashes.
	* Author: Sam "Tehsmash" Betts
	* Date: 12/18/2012
=end
  class Rest
    ##
    # Build a HTTP object having been given a timeout and a URI object
    # Returns Net::HTTP object.
    ##
    def build_http(uri, timeout)
      http = Net::HTTP.new(uri.host, uri.port)
      if(timeout > 0)
              http.open_timeout = timeout
              http.read_timeout = timeout
      end
      return http
    end

    ##
    # All responses from openstack where any errors need to be caught are passed through
    # this function. Unless a successful response is passed it will throw a Ropenstack
    # error.
    # If successful returns a hash of response body, unless response body is nil then it
    # returns an empty hash.
    ##
    def error_manager(uri, response)
      case response
      when Net::HTTPSuccess then
        # This covers cases where the response may not validate as JSON.
        begin
          data = JSON.parse(response.body)
        rescue
          data = {}
        end
        ## Get the Headers out of the response object
        data['headers'] = response.to_hash()
        return data
      when Net::HTTPBadRequest
        raise Ropenstack::MalformedRequestError, response.body
      when Net::HTTPNotFound
        raise Ropenstack::NotFoundError, "URI: #{uri} \n" + response.body
      when Net::HTTPUnauthorized
        raise Ropenstack::UnauthorisedError, response.body
      else
        raise Ropenstack::RopenstackError, response.body
      end
    end

    ##
    # Builds headers for requests which send JSON data, if a keystone token is supplied
    # it adds the X-Auth-Token field with the keystone token.
    # Returns a hash which represents the http headers in a format accepted by Net::HTTP.
    ##
    def build_headers(token)
      headers = {'Content-Type' =>'application/json'}
      unless token.nil?
        headers['X-Auth-Token'] = token
      end
      return headers
    end

    ##
    # The function which you call to perform a http request
    # using the request object given in the parameters. By
    # default manage errors is true, so all responses are passed
    # through the error manager which converts the into Ropenstack errors.
    ##
    def do_request(uri, request, manage_errors = true, timeout = 10)
      begin
        http = build_http(uri, timeout)
        if(manage_errors)
          return error_manager(uri, http.request(request))
        else
          http.request(request)
          return { "Success" => true }
        end
      rescue Timeout::Error
        raise Ropenstack::TimeoutError, "It took longer than #{timeout} to connect to #{uri.to_s}"
      rescue Errno::ECONNREFUSED
        raise Ropenstack::TimeoutError, "It took longer than #{timeout} to connect to #{uri.to_s}"
      end
    end

    ##
    # Wrapper function for a get request, just provide a uri
    # and it will return you a hash with the result data.
    # For authenticated transactions a token can be provided.
    # Implemented using the do_request method.
    ##
    def get_request(uri, token = nil, manage_errors = true)
      request = Net::HTTP::Get.new(uri.request_uri, initheader = build_headers(token))
      return do_request(uri, request, manage_errors)
    end

    ##
    # Wrapper function for delete requests, just provide a uri
    # and it will return you a hash with the result data.
    # For authenticated transactions a token can be provided.
    # Implemented using the do_request method.
    ##
    def delete_request(uri, token = nil, manage_errors = true)
      request = Net::HTTP::Delete.new(uri.request_uri, initheader = build_headers(token))
      return do_request(uri, request, manage_errors)
    end

    ##
    # Wrapper function for a put request, just provide a uri
    # and a hash of the data to send, then it will return you a hash
    # with the result data.
    # For authenticated transactions a token can be provided.
    # Implemented using the do_request method
    ##
    def put_request(uri, body, token = nil, manage_errors = true)
      request = Net::HTTP::Put.new(uri.request_uri, initheader = build_headers(token))
      request.body = body.to_json
      return do_request(uri, request, manage_errors)
    end

    ##
    # Wrapper function for a put request, just provide a uri
    # and a hash of the data to send, then it will return you a hash
    # with the result data.
    # For authenticated transactions a token can be provided.
    ##
    def post_request(uri, body, token = nil, manage_errors = true)
      request = Net::HTTP::Post.new(uri.request_uri, initheader = build_headers(token))
      request.body = body.to_json
      return do_request(uri, request, manage_errors)
    end
  end
end


# coding: utf-8
require "fn/version"

module Fn
  module_function

  # coding: utf-8
  module Callable
    def to_proc
      method(:call).to_proc
    end
  end

  module Composable
    # Functional composition, f · g
    def comp(g)
      Fn { |*a, &b|
        call(g.call(*a, &b))
      }
    end
    alias * comp
    alias + comp

    def pipe(g)
      Fn { |*a, &b|
        g.call(call(*a, &b))
      }
    end
    alias | pipe

    # Bind (partially apply) parameters from the left
    def lapply(*l)
      Fn { |r, &b|
        call(*l, *r, &b)
      }
    end
    alias << lapply

    # Bind (partially apply) parameters from the right
    def rapply(*r)
      Fn { |*l, &b|
        call(*l, *r, &b)
      }
    end
    alias >> rapply
  end

  class Fn
    include Callable
    include Composable

    def initialize(&body)
      @body = body
    end

    def call(*args, &blk)
      @body.call(*args, &blk)
    end
  end

  # class Maybe
  #   def initialize(val)
  #     @val = val
  #   end

  #   def bind(g)
  #     if @val
  #       Fn { |*args, &blk|  }
  #     end
  #   end

  #   def then(resolve, _reject = nil)
  #     resolve.call(@val)
  #   end
  # end

  # class Nothing
  #   def self.then(_resolve, reject = nil)
  #     reject.call
  #   end
  # end

  # Function pseudo-constructor
  #
  # Like Symbol#to_proc
  #
  #     Fn(:upcase).call('xxx') #=> 'XXX'
  #
  # But the resulting Fn can take extra args besides `self`
  #
  #     Fn(:ljust).call('xxx', 5) #=> '  XXX'
  #
  # Can be used to coerce/convert an existing Proc (compare Integer(), Array())
  #
  #    Fn(->{ |x| x.length }).call('xxx') #=> 3
  #
  # Or called with a block directly
  #
  #    Fn { |x| x.length }.call('xxx') #=> 3
  #
  def Fn(prc = nil, *rargs, &blk)
    if Symbol === prc
      Fn { |*args| args.first.send(prc, *rargs, *args.drop(1)) }
    else
      Fn.new(&(prc || blk))
    end
  end
  alias fn Fn

  # I = fn { |x| x }

  # def maybe(*fns)
  #   if fns.empty?
  #     I
  #   else
  #     fn { |arg, &blk|
  #       if arg.nil?
  #         nil
  #       else
  #         maybe(*fns.drop(1)).call(fns.first.(arg, &blk))
  #       end
  #     }
  #   end
  # end

  # # Juxtapose, put function applications side by side
  # juxt = fn { |*fns|
  #   fn { |*args|
  #     fns.map(&fn(:call).rapply(*args))
  #   }
  # }

  # map_hsh = fn { |hsh, blk| hsh.map(&blk).to_h }

  # map_values = fn { |hsh, blk|
  #   map_hsh.(
  #     hsh,
  #     juxt.(
  #       fn(:first),
  #       blk * fn(:last)
  #     )
  #   )
  # }

  # map_keys = fn { |hsh, blk|
  #   map_hsh.(
  #     hsh,
  #     juxt.(
  #       blk * fn(:first),
  #       fn(:last)
  #     )
  #   )
  # }

  # symbolize_keys = map_keys >> fn(:to_sym) # bind the right arg, i.e. the function to map with
  # stringize_keys = map_keys >> fn(:to_s)

end


require 'sfkb/rest'
require 'sfkb/settings'
require 'sfkb/decoration'

module SFKB
  module Knowledge
    include REST
    include Settings
    include Decoration

    # Queries for all (undeleted) article IDs, returning an array.
    def article_ids
      query('SELECT Id FROM KnowledgeArticle').map(&:Id)
    end

    # Enumerates articles
    def articles
      Enumerator.new do |y|
        article_ids.each do |id|
          y << article(id)
        end
      end
    end

    # Gets an article by ID
    def article(id)
      url = index.knowledgeManagement.articles.article
      url = url(url, ArticleID: id)
      decorate(get(url).body) { |o| autodefine(o) }
    end
  end
end


module Ropenstack
  ##
  # * Name: ImageVersion2
  # * Description: Implementation of the Glance V2.0 API Client in Ruby
  # * Author: Sam 'Tehsmash' Betts, John Davidge
  # * Date: 30/06/2014
  ##
  module Image::Version2
    ##
    # Returns a list of images with all associated meta-data in
    # hash format.
    ##
    def images(id)
      if id.nil?
        return get_request(address("images"), @token)["images"]
      else
        return get_request(address("images/" + id), @token)
      end
    end

    def image_create(name, id, visibilty, tags)
      data = {
        :name => name
      }
      unless id.nil?
        data[:id] = id
      end
      unless visibility.nil?
        data[:visibility] = visibility
      end
      unless tags.nil?
        data[:tags] = tags
      end

      post_request(address("images"), data, @token)
    end

    def image_delete(id)
      delete_request(address("images/" + id), @token)
    end

    # TODO Ruby HTTP Binary Download to FILE
    def image_download(id)
    end

    def image_add_tag(id, tag)
      put_request(address("images/"+id+"/tags/"+tag), @token)
    end

    def image_delete_tag(id)
      delete_request(address("images/"+id+"/tags/"+tag), @token)
    end

    ## Members
    def members(id)
    end

    def member_add()
    end

    def member_delete()
    end

    def member_update()
    end

    ## Schemas
    def schemas(type)
      return get_request(address("schemas/" + type), @token)
    end

    ## BELOW HERE IS OLD CODE THAT MAY OR MAYNOT WORK, THAR BE DRAGONS

    ##
    # Upload an image to the Image Service from a file, takes in a ruby file object.
    # More convoluted than it should be because for a bug in Quantum
    # which just returns an error no matter the outcome.
    ##
    def upload_image_from_file(name, disk_format, container_format, minDisk, minRam, is_public, file)
      data = {
        "name" => name,
        "disk_format" => disk_format,
        "container_format" => container_format,
        "minDisk" => minDisk,
        "minRam" => minRam,
        "public" => is_public
      }
      imagesBefore = images()
      post_request(address("images"), data, @token, false)
      imagesAfter = images()
      foundNewImage = true
      image = nil
      imagesAfter.each do |imageA|
        imagesBefore.each do |imageB|
          if(imageA == imageB)
            foundNewImage = false
          end
        end
        if(foundNewImage)
          image = imageA
          break
        end
      end
      return put_octect(address(image["file"]), file.read, false)
    end

    ##
    # Special rest call for sending a file stream using an octet-stream
    # main change is just custom headers.
    # Still implemented using do_request function.
    ##
    def put_octect(uri, data, manage_errors)
      headers = build_headers(@token)
      headers["Content-Type"] = 'application/octet-stream'
      req = Net::HTTP::Put.new(uri.request_uri, initheader = headers)
      req.body = data
      return do_request(uri, req, manage_errors, 0)
    end

    private

    ##
    # Function to get the v2 address location of an endpoint.
    ##
    def address(endpoint)
      address("/v2/#{endpoint}")
    end

    def version
      "V2"
    end
  end
end


module GameOfLife
  module Rules

    # The rules followed are:
    # 1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
    # 2. Any live cell with two or three live neighbours lives on to the next generation.
    # 3. Any live cell with more than three live neighbours dies, as if by overcrowding.
    # 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.
    # 5. Any live cell that is over 3 generations dies
    def should_cell_live?(board, cell, x, y)
      live_neighbors_count = board.neighbors_of_cell_at(x, y).select { |n| n.alive? }.size
      case cell.state
      when :live
        ((2..3).include? live_neighbors_count) && (! cell.old?)
      when :dead
        live_neighbors_count == 3
      end
    end

    module_function :should_cell_live?
  end
end


require "rails_sprite/stylesheet_generator"

module RailsSprite
  class SpriteUtil
    attr_reader :root_path, :scope_name, :recipe_path, :file_extend,
      :spacing, :image_to_folder, :image_source_folder,
      :stylesheet_to, :image_to_file_path, :css_class_prefix, :css_class_shared,
      :image_scope_name, :stylesheet_scope_name,
      :css_extend, :file_extend_name, :zoom

    #
    #  :css_extend => "",
    #  :root_path => '.',
    #  :scope_name => "rails_xxx",
    #  :recipe_path => "icons/16x16",
    #  :file_extend => '.png',
    #  :spacing => 10,
    #  :image_to_folder => "app/assets/images",
    #  :image_source_folder => 'app/assets/images/rails_xxx/sprite_sources',
    #  :stylesheet_to => "app/assets/stylesheets/rails_xxx/sprite/icons/16x16.css.scss.erb",
    #  :image_to_file_path => "rails_xxx/sprite/icons/16x16.png"
    #
    def initialize options={}
      @root_path                = options.fetch(:root_path, ::Rails.root)

      @scope_name               = options.fetch(:scope_name, '')
      @scope_name               = "#{scope_name}/" unless scope_name.end_with?('/')

      @recipe_path              = options.fetch(:recipe_path, '')
      @recipe_path              = recipe_path.chomp('/') if recipe_path.end_with?('/')

      @file_extend              = options.fetch(:file_extend, '.png').downcase
      @css_extend               = options.fetch(:css_extend, ".css.scss.erb")

      @file_extend_name = file_extend.gsub('.', '')

      @spacing                  = options.fetch(:spacing, 10)
      @stylesheet_scope_name    = "#{scope_name}sprite/#{recipe_path}#{css_extend}"
      @stylesheet_to            = options.fetch(:stylesheet_to, "#{root_path}/app/assets/stylesheets/#{stylesheet_scope_name}")

      @image_source_folder      = options.fetch(
        :image_source_folder, "#{root_path}/app/assets/images/#{scope_name}sprite_sources/#{recipe_path}"
      )

      @image_to_folder          = options.fetch(:image_to_folder, "#{root_path}/app/assets/images")
      @image_scope_name         = "#{scope_name}sprite/#{recipe_path}#{file_extend}"
      @image_to_file_path       = options.fetch(:image_to_file_path, "#{image_to_folder}/#{image_scope_name}")

      @scope_str                = scope_name.chomp('/').gsub('/', '-')
      @recipe_str               = recipe_path.chomp('/').gsub('/', '-')

      @css_class_shared         = options.fetch(:css_class_shared, "rs-#{@scope_str}")
      @css_class_prefix         = options.fetch(:css_class_prefix, "rs-#{@scope_str}-#{@recipe_str}-")

      @zoom                     = options.fetch(:zoom, 1).to_i
    end

    def perform
      file_infos = []

      #  puts "image_source_folder: #{image_source_folder}"
      #  puts "image_to_file_path: #{image_to_file_path}"
      #  puts "stylesheet_to: #{stylesheet_to}"

      counter = 0

      x = 0
      y = 0
      max_w = 0
      max_h = 0

      Dir.entries( image_source_folder ).each do |file_name|
        if file_name != '.' && file_name != '..' && file_name.end_with?(file_extend)
          file_path = "#{image_source_folder}/#{file_name}"

          if ::File.file?(file_path)
            file_name_split = file_name.split('.')
            file_name_split.pop
            file_purename = file_name_split.join('.')

            file_info = {
              :filepath => file_path,
              :filename => file_name,
              :file_purename => file_purename,
              :idx => counter
            }.merge(
              _library.load( file_path )
            )

            file_info[:x] = x
            file_info[:y] = y

            y += (spacing + file_info[:height])

            max_w = [max_w, file_info[:width]].max
            max_h = y

            file_infos << file_info

            counter += 1
          end
        end
      end

      _composite_images(:file_infos => file_infos, :max_w => max_w, :max_h => max_h)
      _composite_css(file_infos, :max_w => max_w, :max_h => max_h)
    end

    private

    def stylesheet_generator
      RailsSprite::StylesheetGenerator
    end

    def _library
      RailsSprite::Library::RMagick
    end

    def _composite_css file_infos, options
      stylesheet_generator.generate(
        :zoom => zoom,
        :css_class_shared => css_class_shared,
        :css_class_prefix => css_class_prefix,
        :file_infos => file_infos,
        :max_w => options[:max_w],
        :max_h => options[:max_h],
        :image_scope_name => image_scope_name,
        :css_extend => css_extend,
        :stylesheet_to => stylesheet_to
      )
    end

    def _composite_images options={}
      target = Magick::Image.new(options[:max_w], options[:max_h])
      target.opacity = Magick::QuantumRange

      options[:file_infos].each do |file_info|
        target.composite!(file_info[:image], file_info[:x], file_info[:y], Magick::SrcOverCompositeOp)
      end

      system "mkdir -p #{::File.dirname(image_to_file_path)}"

      target.write(image_to_file_path)
    end

  end
end


# encoding: utf-8

require 'tabledata/parser'
require 'tabledata/row'
require 'tabledata/column'
require 'tabledata/detection'
require 'tabledata/exceptions'
require 'tabledata/presenter'

module Tabledata

  # Table represents tabular data and provides various ways to create one,
  # read from it and represent it in a different format.
  class Table

    include Enumerable

    # A list of options which are valid to be passed to some of the constructors.
    ValidOptions           = [:has_headers, :has_footer, :file_type, :name, :table_class, :table_classes, :accessors, :data, :header, :body, :footer]

    # Options which are invalid to be passed to Tabledata::Table.from_file.
    InvalidFromFileOptions = [:data, :header, :body, :footer]

    # The default name for unnamed tables.
    DefaultTableName       = 'Unnamed Table'

    # The default accessor list.
    DefaultAccessors       = []

    # Create a table from a file.
    # See {Tabledata} docs for a list of supported file types.
    #
    # @param [String] path
    #   The path to a file in one of the supported formats.
    #
    # @param [Hash] options
    #   A list of options. Many are identical to {Table#initialize}'s options
    #   hash, but with the additional options :file_type and :table_class.
    #   The :data option is used by from_file and thus overridden and can't be
    #   used. For the same reason, :header, :footer and :body can't be used.
    #
    # @option options [Symbol] :file_type
    #   The file type. Nil for auto-detection (which uses the extension of the
    #   filename), or one of :csv, :xls or :xlsx
    # @option options [String] :name
    #   The name of the table. Defaults to the basename of the file without the suffix.
    # @option options [Array<Symbol>, Hash<Symbol => Integer>, nil] :accessors
    #   A list of accessors for the columns. Allows accessing columns by that accessor.
    # @option options [true, false] :has_headers
    #   Whether the table has a header, defaults to true
    # @option options [true, false] :has_footer
    #   Whether the table has a footer, defaults to false
    #
    # @return [Tabledata::Table]
    #
    def self.from_file(path, options=nil)
      options ||= {}

      unless (options.keys & InvalidFromFileOptions).empty?
        raise ArgumentError, "Must not pass #{(options.keys & InvalidFromFileOptions).inspect[1..-2]}"
      end

      options[:table_class] ||= self
      options[:file_type]   ||= Detection.file_type_from_path(path)
      options[:name]        ||= File.basename(path).sub(/\.(?:csv|xlsx?)\z/, '')

      case options[:file_type]
        when :csv then Parser.parse_csv(path, options)
        when :xls then Parser.table_from_xls(path, options)
        when :xlsx then Parser.table_from_xlsx(path, options)
        else raise InvalidFileType, "Unknown file format #{options[:file_type].inspect}"
      end
    end

    # Create a table from a datastructure.
    #
    # @param [Array<Array>] data
    #   An array of arrays, representing rows -> cells.
    #
    # @param [Hash] options
    #   A list of options. Many are identical to {Table#initialize}'s options
    #   hash, but with the additional options :file_type and :table_class.
    #   The :data option is used by from_file and thus overridden and can't be
    #   used. For the same reason, :header, :footer and :body can't be used.
    #
    # @option options [Symbol] :file_type
    #   The file type. Nil for auto-detection (which uses the extension of the
    #   filename), or one of :csv, :xls or :xlsx
    # @option options [Symbol] :table_class
    #   The class to use for this table. Defaults to self (Tabledata::Table)
    # @option options [String] :name
    #   The name of the table
    # @option options [Array<Symbol>, Hash<Symbol => Integer>, nil] :accessors
    #   A list of accessors for the columns. Allows accessing columns by that accessor.
    # @option options [true, false] :has_headers
    #   Whether the table has a header, defaults to true
    # @option options [true, false] :has_footer
    #   Whether the table has a footer, defaults to false
    #
    #
    def self.from_data(data, options=nil)
      new(options ? options.merge(data: data) : {data: data})
    end

    # @return [Array<Symbol>] An array of all named accessors
    attr_reader :accessors

    # @return [Hash<Symbol => Integer>] A hash mapping column accessor names to the column index
    attr_reader :accessor_columns

    # @return [Hash<Integer => Symbol>] A hash mapping column index to the column accessor names
    attr_reader :column_accessors

    # @private
    # The internal data structure. Do not modify.
    attr_reader :data

    # @return [String, nil] The name of the table
    attr_reader :name

    # Create a new table.
    #
    # @param [Hash] options
    #   A list of options. Mostly identical to {Table#initialize}'s options
    #   hash, but with the additional options :file_type and :table_class.
    #
    # @option options [String] :name
    #   The name of the table
    # @option options [Array<Symbol>, Hash<Symbol => Integer>, nil] :accessors
    #   A list of accessors for the columns. Allows accessing columns by that accessor.
    # @option options [Symbol] :data
    #   An array of arrays with the table data. Mutually exclusive with
    #   :header, :body and :footer.
    # @option options [Symbol] :header
    #   An array with the header values. To be used together with :body and :footer.
    #   Mutually exclusive with :data.
    #   Automatically sets :has_headers to true.
    # @option options [Symbol] :body
    #   An array with the header values. To be used together with :header and :footer.
    #   Mutually exclusive with :data.
    #   Automatically sets :has_headers to false if :header is not also present.
    #   Automatically sets :has_footer to false if :footer is not also present.
    # @option options [Symbol] :footer
    #   An array with the header values. To be used together with :header and :body.
    #   Mutually exclusive with :data.
    #   Automatically sets :has_footer to true.
    # @option options [true, false] :has_headers
    #   Whether the table has a header, defaults to true
    # @option options [true, false] :has_footer
    #   Whether the table has a footer, defaults to false
    #
    def initialize(options=nil)
      options           = options ? options.dup : {}
      raise ArgumentError, "Invalid options: #{(options.keys-ValidOptions).inspect[1..-2]}" unless (options.keys-ValidOptions).empty?

      if options.has_key?(:data)
        raise "Must not mix :data with :header, :body or :footer" if options.has_key?(:header) || options.has_key?(:body) || options.has_key?(:footer)
        data = options.delete(:data)
      else
        data = []
        if options.has_key?(:header)
          data << options.delete(:header)
          options[:has_headers] = true
        elsif !options.has_key?(:has_headers)
          options[:has_headers] = !options.has_key?(:body)
        end
        data.concat(options.delete(:body)) if options.has_key?(:body)
        if options.has_key?(:footer)
          data << options.delete(:footer)
          options[:has_footer] = true
        end
      end

      column_count      = data.first ? data.first.size : 0
      @name             = options.delete(:name) || DefaultTableName
      @has_headers      = options.fetch(:has_headers, true) ? true : false
      @has_footer       = options.fetch(:has_footer, false) ? true : false
      @data             = data
      @header_columns   = nil                        # used for cell access by header name, e.g. table[0]["Some Cellname"]
      self.accessors    = options.delete(:accessors) # used for cell access by accessor, e.g. table[0][:some_cell_accessor]
      @rows             = data.map.with_index { |row, index|
        raise InvalidColumnCount.new(index, row.size, column_count) if index > 0 && row.size != column_count
        raise ArgumentError, "Row must be provided as Array, but got #{row.class} in row #{index}" unless row.is_a?(Array)

        Row.new(self, index, row)
      }
    end

    # Automatically create accessors from the headers of the table.
    # It does that by downcasing the headers, replace everything which is not in [a-z0-9_] with an _,
    # replace all repeated occurrences of _ with a single _.
    #
    # @note
    #   The actual transformation algorithm might change in the future.
    def accessors_from_headers!
      raise "Can't define accessors from headers in a table without headers" unless @has_headers

      self.accessors = headers.map { |val| (val && !val.empty?) ? val.to_s.downcase.tr('^a-z0-9_', '_').squeeze('_').gsub(/\A_|_\z/, '').to_sym : nil }
    end

    # @param [Array<Symbol>, Hash<Symbol => Integer>, nil] accessors
    #
    # Define the name of the accessors used in Tabledata::Row.
    # If you pass in a Hash, it's supposed to be in the form of
    # {accessor_name: column_index}.
    def accessors=(accessors)
      @accessor_columns = {}
      case accessors
        when nil
          # nothing to do
        when Array
          accessors.each_with_index do |name, idx|
            @accessor_columns[name.to_sym] = idx if name
          end
        when Hash
          @accessor_columns = Hash[accessors.map { |name, index| [name.to_sym, index] }]
        else
          raise ArgumentError, "Expected nil, an Array or a Hash, but got #{accessors.class}"
      end
      @accessor_columns.freeze
      @column_accessors  = @accessor_columns.invert.freeze
      @accessors         = @column_accessors.values_at(*0..(@column_accessors.keys.max || -1)).freeze
    end

    # @return [Integer] The number of rows, excluding headers and footer
    def size
      result = @data.size - (@has_headers ? 1 : 0) - (@has_footer ? 1 : 0)

      result < 0 ? 0 : result
    end
    alias length size

    # @return [Integer, nil] The number of columns. Nil if no rows are present.
    def column_count
      @data.first ? @data.first.size : nil
    end

    # Array#[] like access to the rows in the body (excluding headers and
    # footer) of the table.
    #
    # @return [Array<Tabledata::Row>]
    def [](*args)
      body[*args]
    end

    # @return [Tabledata::Row]
    #   The row at the given row number (zero based). Includes headers and footer.
    #   Returns the given default value or invokes the default block if the desired row does not
    #   exist.
    #
    # @raise [KeyError]
    #   If the row was not found and neither a default value nor a default block were given.
    def fetch_row(row, *default)
      raise ArgumentError, "Must only provide at max one default value or one default block" if default.size > (block_given? ? 0 : 1)

      row_data = row(row)

      if row_data
        row_data
      elsif block_given?
        yield(self, row)
      elsif default.empty?
        raise KeyError, "Row not found: #{row.inspect}"
      else
        default.first
      end
    end

    # @return [Tabledata::Row]
    #   The row at the given row number (zero based). Includes headers and footer.
    def row(row)
      @rows[row]
    end

    # @return [Object]
    #   The cell value at the given row and column number (zero based). Includes headers and footer.
    #   Returns the given default value or invokes the default block if the desired cell does not
    #   exist.
    #
    # @raise [KeyError]
    #   If the cell was not found and neither a default value nor a default block were given.
    def fetch_cell(row, column, *default_value, &default_block)
      raise ArgumentError, "Must only provide at max one default value or one default block" if default_value.size > (block_given? ? 0 : 1)

      row_data = row(row)

      if row_data
        row_data.fetch(column, *default_value, &default_block)
      elsif block_given?
        yield(self, row, column)
      elsif default_value.empty?
        raise IndexError, "Row not found: #{row.inspect}, #{column.inspect}"
      else
        default_value.first
      end
    end

    # @return [Symbol, nil]
    #   The accessor defined for the given column index.
    def column_accessor(index)
      @column_accessors[index]
    end

    # @return [String, nil]
    #   The name defined for the given column index.
    #   The name is determined by the column's header.
    #   Returns nil if the table has no headers.
    def column_name(index)
      h = headers

      h && h.at(index)
    end
    alias column_header column_name

    # @return [Array<Tabledata::Column>]
    #   An array with the columns of this table
    def columns
      Array.new(column_count) { |col| column(col) }
    end

    # @return [Tabledata::Column]
    #   The column at the given index, accessor or name.
    def column(index)
      Column.new(self, index_for_column(index))
    end

    # @return [Integer, nil]
    #   The index for the given column-index, -accessor or -name.
    def index_for_column(column)
      case column
        when Integer then column
        when Symbol  then index_for_accessor(column)
        when String  then index_for_header(column)
        else raise InvalidColumnSpecifier, "Invalid index type, expected Symbol, String or Integer, but got #{column.class}"
      end
    end

    # @return [Integer, nil]
    #   The index for the given column-accessor.
    def index_for_accessor(name)
      @accessor_columns[name.to_sym]
    end

    # @return [Integer, nil]
    #   The index for the given column-name.
    def index_for_header(name)
      if @has_headers && @data.first then
        @header_columns ||= Hash[@data.first.each_with_index.to_a]
        @header_columns[name]
      else
        nil
      end
    end

    # @return [true, false]
    #   Whether accessors have been defined for this table
    def accessors?
      !@accessors.empty?
    end

    # @return [true, false]
    #   Whether this table has headers
    def headers?
      @has_headers
    end

    # @return [Tabledata::Row, nil]
    #   The header row, if the table has headers and the header row is present.
    #   Nil otherwise.
    def headers
      headers? ? @rows.first : nil
    end

    # @return [true, false]
    #   Whether this table has a footer
    def footer?
      @has_footer
    end

    # @return [Tabledata::Row, nil]
    #   The header row, if the table has a footer and the footer row is present.
    #   Nil otherwise.
    def footer
      !footer? || (headers? && @rows.size < 2) ? nil : @rows.last
    end

    # @return [Array<Tabledata::Row>]
    #   All rows except header and footer.
    def body
      end_offset = footer? ? -2 : -1

      if headers?
        @rows.empty? ? [] : @rows[1..end_offset]
      else
        @rows[0..end_offset]
      end
    end

    # Append a row to the table.
    #
    # @param [Array, #to_ary] row
    #   The row to append to the table
    #
    # @return [self]
    def <<(row)
      index  = @data.size
      begin
        row = row.to_ary
      rescue NoMethodError
        raise ArgumentError, "Row must be provided as Array or respond to `to_ary`, but got #{row.class} in row #{index}" unless row.respond_to?(:to_ary)
        raise
      end
      raise InvalidColumnCount.new(index, row.size, column_count) if @data.first && row.size != @data.first.size

      @data << row
      @rows << Row.new(self, index, row)

      self
    end

    # Iterate over all rows in the body
    #
    # @see Tabledata::Table#each_row A method which iterates over all rows, including headers
    #
    # @yield [row]
    # @yieldparam [Tabledata::Row]
    #
    # @return [self]
    def each(&block)
      return enum_for(__method__) unless block

      body.each(&block)

      self
    end

    # Iterate over all rows, header and body
    #
    # @see Tabledata::Table#each A method which iterates only over body-rows
    #
    # @yield [row]
    # @yieldparam [Tabledata::Row]
    #
    # @return [self]
    def each_row(&block)
      return enum_for(__method__) unless block

      @data.each(&block)

      self
    end

    # Iterate over all columns
    #
    # @yield [column]
    # @yieldparam [Tabledata::Column]
    #
    # @return [self]
    def each_column
      return enum_for(__method__) unless block_given?

      column_count.times do |i|
        yield column(i)
      end

      self
    end

    # Returns a deep copy of the tables internal datastructure.
    #
    # @note
    #   Only rows and columns are copied, the individual values are not.
    #   Example:
    #
    # @see Table#data Table#data returns the actual, uncopied, internal datastructure
    #
    # @return [Array<Array>]
    #   A deep copy of the tables internal datastructure, an Array of row array.
    def to_a
      @data.map(&:dup)
    end

    # @return [true, false]
    #   Whether this table has the same content as `other`.
    #   Uses the #data method to get the contents.
    #   If other has no #data method, the comparison is false.
    def ==(other)
      @data == other.data
    rescue NoMethodError
      false
    end

    # @return [true, false]
    #   Whether this table has the same content and properties (name, has_headers, has_footer,
    #   accessors) as another table
    def eql?(other)
      (
        other.is_a?(Tabledata::Table) &&
        other.name      == @name &&
        other.headers?  == @has_headers &&
        other.footer?   == @has_footer &&
        other.accessors == @accessors &&
        other.data      == @data
      )
    end

    # See Object#hash
    def hash(other)
      [Tabledata::Table, @name, @has_headers, @has_footer, @accessors, @data].hash
    end

    # @return [Tabledata::Presenter]
    def format(format_id, options=nil)
      Presenter.present(self, format_id, options)
    end

    # See Object#inspect
    def inspect
      sprintf "#<%s headers: %p, footer: %p, cols: %s, rows: %d>",
        self.class,
        headers?,
        footer?,
        column_count || '-',
        size
    end
  end
end


module Hemingway
  module FootnoteNode
    # This is the method that will place the anchor tag and id of the
    # footnote within the paragraph body itself.
    #
    # I'm passing in a time variable here to make links unique. You see,
    # if you parse many of these entries on a single HTML page you'll end up
    # with multiple #footnote1 divs. To make them unique, we'll pass down
    # a time variable from above to seed them.
    def html(id, time)
      inline_footnote_label = Build.tag("span", Build.tag("sup", id.to_s), :class => "inline-footnote-number")
      Build.tag("a", inline_footnote_label, :href => "#footnote#{id}#{time}")
    end

    # This is the method that will actually spit out the div that the
    # footnote's content is in. This will generally be called after all of the
    # paragraph's text has been spit out so that the footnotes can be appended
    # after. Note that it needs to be passed an id from the caller so that it
    # can be linked to corretly with an anchor tag in the body of the main text.
    #
    # I'm passing in a time variable here to make links unique. You see,
    # if you parse many of these entries on a single HTML page you'll end up
    # with multiple #footnote1 divs. To make them unique, we'll pass down
    # a time variable from above to seed them.
    def footnote_html(id, time)
      footnote_label = Build.tag("span", Build.tag("sup", id.to_s), :class => "footnote-number")
      footnote_content = sequence.elements.map { |s| s.html }.join
      Build.tag("div", footnote_label + footnote_content, :id => "footnote#{id}#{time}", :class => "footnote")
    end
  end
end


module Ropenstack
  ##
  # * Name: DatabaseVersion1
  # * Description: Implementation of the Block Storage V1.0 API Client in Ruby.
  # * Author: Sam 'Tehsmash' Betts, John Davidge
  # * Date: 30/06/2014
  ##
  module Database::Version1
    ## Database Instances
    def instances(id)
      if id.nil?
        get_request(address("/instances"), @token)
      else
        get_request(address("/instances/" + id), @token)
      end
    end

    def instance_create(databases, flavorRef, name, users, volume)
      ## Construct data
      data = { :instance => {
          :databases => databases,
          :flavorRef => flavorRef,
          :name => name,
          :users => users,
          :volume => volume
        }
      }

      post_request(address("/instances"), data, @token)
    end

    def instance_delete(id)
      delete_request(address("/instances/" + id), @token)
    end

    def instance_root(id)
      get_request(address("/instances/" + id + "/root"), @token)
    end

    def instance_root_enable(id)
      ## Empty data field
      post_request(address("/instances/" + id + "/root"), {}, @token)
    end

    ## Database Instance Actions
    def instance_action(id, action, param)
      case action
      when "RESTART"
        post_request(address("/instances/" + id + "/action"), {:restart => {}}, @token)
      when "RESIZE"
        if param.is_a? String
          post_request(address("/instances/" + id + "/action"), {:resize => {:flavorRef => param }}, @token)
        elsif param.is_a? Int
          post_request(address("/instances/" + id + "/action"), {:resize => {:volume => {:size => param }}}, @token)
        else
          raise Ropenstack::RopenstackError, "Invalid Parameter Passed"
        end
      else
        raise Ropenstack::RopenstackError, "Invalid Action Passed"
      end
    end

    ## Databases
    def databases(instance)
      get_request(address("/instances/" + instance + "/databases"), @token)
    end

    def database_create(instance, name)
      data = { :databases => [
          {
            :name => name
          }
        ]
      }
      post_request(address("/instances/" + instance + "/databases"), data, @token)
    end

    def database_delete(instance, name)
      delete_request(address("/instances/" + instance + "/databases/" + name), @token)
    end

    ## Users
    def users(instance)
      get_request(address("/instances/" + instance + "/users"), @token)
    end

    def user_create(instance, name, databases)
      ## TODO Make this work
      post_request(address("/instances/" + instance + "/users"), data, @token)
    end

    def user_delete(instance, name)
      post_request(address("/instances/" + instance + "/users/" + name), @token)
    end

    ## Flavors
    def flavors(id)
      if id.nil?
        get_request(address("/flavors"), @token)
      else
        get_request(address("/flavors/" + id), @token)
      end
    end

    def address(endpoint)
      super(endpoint) + @accountid
    end

    def version
      "V1"
    end
  end
end


module Conject
  class DependencyResolver
    construct_with :class_finder
    #
    # Given a Class, generate a map of dependencies needed to construct a new
    # instance of that class. Dependencies are looked up (and/or instantiated, as
    # determined within the ObjectContext) via the provided ObjectContext.
    #
    # This method assumes the Class has_object_defintion?  (Client code should
    # determine that before invoking this method.)
    #
    def resolve_for_class(klass, object_context, remapping=nil)
      remapping ||= {}
      klass.object_definition.component_names.inject({}) do |obj_map, name|
        obj_map[name] = search_for(klass, object_context, remapping[name.to_sym] || remapping[name.to_s] || name)
        obj_map
      end
    end

    private

    def search_for(klass, object_context, name)
      object = nil
      # If the asking class has a module namespace, first try looking relative
      # to that module:
      if module_path = class_finder.get_module_path(klass)
        qualified_name = "#{module_path}/#{name}"
        begin
          object = object_context.get(qualified_name)
        rescue
          # This means there's no relative object, which might be ok.
          # Fallback is to look for the requested object in the global namespace.
        end
      end
      # Search for the object by the specified name
      object ||= object_context.get(name)
    end
  end
end


module Revenc

  class Errors
    include Enumerable

     def initialize
       @errors ={}
     end

     # add errors, error_on can be a symbol or object instance
     def add(error_on, message = "Unknown error")

       # humanize error_on
       if error_on.is_a?(Symbol)
         error_on_str = error_on.to_s
       else
         error_on_str = underscore(error_on.class.name)
       end
       error_on_str = error_on_str.gsub(/\//, '_')
       error_on_str = error_on_str.gsub(/_/, ' ')
       error_on_str = error_on_str.gsub(/^revenc/, '').strip
       #error_on_str = error_on_str.capitalize

       @errors[error_on_str] ||= []
       @errors[error_on_str] << message.to_s
    end

    def empty?
      @errors.empty?
    end

    def clear
      @errors = {}
    end

    def each
      @errors.each_key { |attr| @errors[attr].each { |msg| yield attr, msg } }
    end

    def size
      @errors.values.inject(0) { |error_count, attribute| error_count + attribute.size }
    end

    alias_method :count, :size
    alias_method :length, :size

    def messages
      messages = []

      @errors.each_key do |attr|
      @errors[attr].each do |message|
        next unless message
        attr_name = attr.to_s
        messages << attr_name + ' ' + message
        end
      end

      messages
    end

    def to_sentences
      messages.join("\n")
    end

    private

    # from ActiveSupport
    def underscore(camel_cased_word)
      camel_cased_word.to_s.gsub(/::/, '/').
        gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
        gsub(/([a-z\d])([A-Z])/,'\1_\2').
        tr("-", "_").
        downcase
    end

  end

end


module GameOfLife
  # Raised when a {Board} gets into an invalid shape
  class InvalidBoardError < RuntimeError; end;

  # The board used in the game. Holds the {Cell}s.
  class Board

    # The {Cell}s in this board,internally maintained as a 2D Array of {Cell}s.
    # The x-coordinate increases horizontally and is always positive.
    # The y-coordinate increases vertically and is always positive.
    # Internally, the cells are arranged as a 2D array. The first-level Array indexed
    # with the y-coordinates. It contains an Array of {Cell}s, whose position is
    # the x-coordinate.
    # @note Use {#each_cell}, {#each_row} etc. methods to access the cells individually.
    attr_reader :cells

    # Creates the board
    # @param [2D Array<Symbol>] seed_data the data for the {Cell}s in the board, as an 2D array.
    # @example seed_data looks like
    #   the output of SimpleStringInputter#parse
    # @raise [InvalidBoardError] if the seed_data is not in the shape of a square,
    #   or if all elements are not present
    def initialize(seed_data)
      @cells = Array.new(Array.new)
      seed_with!(seed_data)
      begin
        validate
      rescue InvalidBoardError => ex
        # Add the seed_data into the error message, so the caller gets a clue
        raise InvalidBoardError, ex.message + " [seed data was: #{seed_data.inspect}]"
      end
    end

    # @param [OutPutter] the outputter that you want to use. Defaults to {Outputters::SimpleStringOutputter}
    def view(outputter = Outputters::SimpleStringOutputter.new)
      outputter.render(self)
    end

    def each_row(&block)
      @cells.each { |row| yield row }
    end

    def each_row_with_index(&block)
      @cells.each_with_index { |row, i| yield row, i }
    end

    def each_cell(&block)
      @cells.flatten.each { |cell| yield cell }
    end

    # Find the cell at a given pair of co-ordinates. Following Array symantics,
    # this method returns nil if nothing exists at that location or if the
    # location is out of the board. To avoid Array's negative index symantics it
    # returns nill if a negative index is passed.
    # @param [Integer] x the x-coordinate
    # @param [Integer] y the y-coordinate
    # @return [Cell] or nil
    def cell_at(x, y)
      return nil if (x < 0 || y < 0)
      @cells[y][x] if @cells[y]
    end

    # Finds the neighbors of a given {Cell}'s co-ordinates. The neighbors are the eight cells
    # that surround the given one.
    # @param [Integer] x the x-coordinate of the cell you find the neighbors of
    # @param [Integer] y the y-coordinate of the cell you find the neighbors of
    # @return [Array<Cell>]
    def neighbors_of_cell_at(x, y)
      neighbors = coords_of_neighbors(x, y).map { |x, y| self.cell_at(x, y) }
      neighbors.reject {|n| n.nil?}
    end

    # This is the first stage in a Game's #tick.
    # @see Game#tick
    def reformat_for_next_generation!
      # create an array of dead cells and insert it as the first and last row of cells
      dead_cells = (1..@cells.first.size).map { Cell.new }
      # don't forget to deep copy the dead_cells
      @cells.unshift Marshal.load(Marshal.dump(dead_cells))
      @cells.push Marshal.load(Marshal.dump(dead_cells))

      # also insert a dead cell at the left and right of each row
      @cells.each do |row|
        row.unshift Cell.new
        row.push Cell.new
      end

      # validate to see if we broke the board
      validate
    end

    # Goes through each {Cell} and marks it (using {Rules}) to signal it's state for the next
    # generation. This prevents modifying any {Cell} in-place as each generation is a pure
    # function of the previous. Once all {Cell}s are marked, it sweeps across them gets them
    # to change their state if they were marked to.
    # @see #mark_changes_for_next_generation
    # @see #sweep_changes_for_next_generation!
    def mark_and_sweep_for_next_generation!
      mark_changes_for_next_generation
      sweep_changes_for_next_generation!
    end

    # This is the third and last stage in a Game's #tick.
    # @see Game#tick
    def shed_dead_weight!
      # Remove the first and last rows if all cells are dead
      @cells.shift if @cells.first.all? { |cell| cell.dead? }
      @cells.pop if @cells.last.all? { |cell| cell.dead? }

      # Remove the first cell of every row, if they are all dead
      first_columns = @cells.map { |row| row.first }
      if first_columns.all? { |cell| cell.dead? }
        @cells.each { |row| row.shift }
      end

      # Remove the last cell of every row, if they are all dead
      last_columns = @cells.map { |row| row.last }
      if last_columns.all? { |cell| cell.dead? }
        @cells.each { |row| row.pop }
      end

      validate
    end

    private
      def validate
        num_o_rows = @cells.size
        columns_in_each_row = @cells.map(&:size)
        unless columns_in_each_row.uniq.size == 1
          msg = "Unequal number of columns, #{columns_in_each_row.inspect} in different rows found"
          raise InvalidBoardError, msg
        end

        num_o_columns = columns_in_each_row.uniq.first
        num_o_elements = @cells.flatten.reject {|d| d.nil? }.size
        unless (num_o_rows * num_o_columns) == num_o_elements
          msg = "Not a rectangular shape: " +
            "rows(#{num_o_rows}) x columns(#{num_o_columns}) != total elements(#{num_o_elements})]. "
          raise InvalidBoardError, msg
        end
      end

      def seed_with!(data)
        data.each_with_index do |row, y|
          @cells << []
          row.each_with_index do |state, x|
            @cells[y] << Cell.new(state)
          end
        end
      end

      def mark_changes_for_next_generation
        self.each_row_with_index do |cells, y|
          cells.each_with_index do |cell, x|
            cell.should_live_in_next_generation =
              Rules.should_cell_live?(self, cell, x, y)
          end
        end
      end

      def sweep_changes_for_next_generation!
        self.each_cell { |cell| cell.change_state_if_needed! }
      end

      # Calculates the co-ordinates of neighbors of a given pair of co-ordinates.
      # @param [Integer] x the x-coordinate
      # @param [Integer] y the y-coordinate
      # @return [Array<Integer, Integer>] the list of neighboring co-ordinates
      # @example
      #   coords_of_neighbors(1,1) =>
      #     [
      #       [0, 0], [0, 1], [0, 2],
      #       [1, 0],         [1, 2],
      #       [2, 0], [2, 1], [2, 2],
      #     ]
      # @note This method returns all possible co-ordinate pairs of neighbors,
      #   so it can contain coordinates of cells not in the board, or negative ones.
      # @see #neighbors_of_cell_at
      def coords_of_neighbors(x, y)
        coords_of_neighbors = []
        (x - 1).upto(x + 1).each do |neighbors_x|
          (y - 1).upto(y + 1).each do |neighbors_y|
            next if (x == neighbors_x) && (y == neighbors_y)
            coords_of_neighbors << [neighbors_x, neighbors_y]
          end
        end
        coords_of_neighbors
      end

  end
end


module RSqoot
  module Merchant

    # Retrieve a list of merchants base on the following parameters
    #
    # @param [String] id (The merchant's ID, Use the Sqoot ID or ID for any supported namespace. Must supply namespace if we don't use Sqoot)
    # @param [String] namespace (One of the supported namespaces. Factual, Foursquare, Facebook, Google, CitySearch, Yelp.)

    def merchant(id, options = {})
      options = update_by_expire_time options
      if merchant_not_latest?(id)
        @rsqoot_merchant = get("merchants/#{id}", options, SqootMerchant)
        @rsqoot_merchant = @rsqoot_merchant.merchant if @rsqoot_merchant
      end
      logger(uri: sqoot_query_uri, records: [@rsqoot_merchant], type: 'merchants', opts: options)
      @rsqoot_merchant
    end
  end
end


# encoding: UTF-8

module EventMachine::WebSocketCodec

  # Internal: Encodes messages into WebSocket frames
  # based on RFC 6455
  class Encoder

    include Protocol

    # Encode a standard payload to a hybi10
    # WebSocket frame
    def encode data, opcode=TEXT_FRAME
      frame = []
      frame << (opcode | 0x80)

      packr = "CC"

      if opcode == TEXT_FRAME
        data.force_encoding("UTF-8")

        if !data.valid_encoding?
          raise "Invalid UTF!"
        end
      end

      # append frame length and mask bit 0x80
      len = data ? data.bytesize : 0
      if len <= 125
        frame << (len | 0x80)
      elsif len < 65536
        frame << (126 | 0x80)
        frame << len
        packr << "n"
      else
        frame << (127 | 0x80)
        frame << len
        packr << "L!>"
      end

      # generate a masking key
      key = rand(2 ** 31)

      # mask each byte with the key
      frame << key
      packr << "N"

      #puts "op #{opcode} len #{len} bytes #{data}"
      # Apply the masking key to every byte
      len.times do |i|
        frame << ((data.getbyte(i) ^ (key >> ((3 - (i % 4)) * 8))) & 0xFF)
      end

      frame.pack("#{packr}C*")
    end

    # create a close payload with code
    def close code, message
      encode [code ? code : 1000, message].pack("nA*"), CLOSE
    end

    # create a ping payload
    def ping data=nil
      encode data, PING
    end

    # create a pong payload
    def pong data=nil
      encode data, PONG
    end

  end

end


module Challah::Rolls
  # Permission is used to extend functionality to a model in your app named Permission.
  # By default, this model already exists within the challah engine.
  #
  # The Permission model is used to store every granular level of restriction for your application.
  # If there is anything within your app that may need to be restricted in any way, you'll likely
  # want to create a permission for it.
  #
  # Permission can be as granular as necessary. For example, you may have a permission called
  # +:people_admin+. Or, you could specify each action taken within an admin section, and add permissions
  # for each of them: +:add_people+, +:edit_people+, +:list_people+, +:delete_people+. Obviously this
  # can be overkill if your app is large, but you get the idea.
  #
  # == Validations
  #
  # A valid permission requires a unique name and key to be provided. The key must be all lower case
  # letters, numbers and underscores only.
  #
  # == Associations
  #
  # The following associations are set on this model by default:
  #
  # * Has many *roles* (connects to {AuthableRole Role})
  # * Has many *users* (connects to {AuthableUser User})
  #
  # The join tables (permission_roles and permission_users) are also included, but likely do not
  # need to be accessed directly.
  #
  # == Scopes
  #
  # By default, the following scopes are included for this model:
  #
  # * default - order by name
  #
  # == Customizing the Permission model
  #
  # By default, the Permission model is included within the gem engine. However, if you wish to
  # include it within your app for any customizations, you can do so by creating a model
  # file named +permission.rb+ and adding the +authable_permission+ line near the top of the class.
  #
  # @example app/models/permission.rb
  #   class Permission < ActiveRecord::Base
  #     # Set up all permission methods from challah gem
  #     authable_permission
  #
  #     # Your customizations here..
  #   end
  module Permission
    # This method sets up the +Permission+ class with all baked in methods.
    #
    # A permission requires the presence of the +name+, +key+ and +description+
    #
    # Once this method has been called, the {InstanceMethods} module
    # will be accessibile within the Permission model.
    def challah_permission
      unless included_modules.include?(InstanceMethods)
        include InstanceMethods
        extend ClassMethods
      end

      class_eval do
        validates_presence_of :name, :key
        validates_uniqueness_of :name, :key
        validates_format_of :key, :with => /^([a-z0-9_])*$/, :message => :invalid_key

        has_many :permission_roles, :dependent => :destroy
        has_many :roles, :through => :permission_roles, :order => 'roles.name'
        has_many :permission_users, :dependent => :destroy
        has_many :users, :through => :permission_users, :order => 'users.last_name, users.first_name'

        default_scope order('permissions.name')

        attr_accessible :name, :description, :key, :locked

        after_create :add_to_admin_role
      end
    end

    module ClassMethods
      # Quickly access a +Permission+ instance by the provided key. If no +Permission+
      # is found with that key, +nil+ is returned.
      #
      # @param [Symbol, String] key A permission +key+ to locate.
      # @return [Permission, nil]
      #
      # @example
      #   Permission[:admin] # => Permission.find_by_key('admin')
      #   Permission['manage_users'] # => Permission.find_by_key('manage_users')
      #   Permission[:does_not_exist] # => nil
      def [](key)
        self.find_by_key(key.to_s.strip.downcase.gsub(' ', '_'))
      end
    end

    # @private
    module InstanceMethods
      # @private
      #
      # When setting a key, make sure it is lower cased and free from padded whitespace.
      def key=(value)
        write_attribute(:key, value.to_s.downcase.strip)
      end

      protected
        # @private
        # After a new permission level is added, automatically add it to the admin user role
        def add_to_admin_role
          admin_role = ::Role.admin

          # if there is an admin role, add this permission to it.
          if admin_role
            admin_role.permission_keys = admin_role.permission_keys + [ self.key ]
            admin_role.save
          end
        end
    end
  end
end


module Epic #:nodoc
  class Configuration
    attr_accessor :base_path, :tmp_path, :vendor_path, :doctype, :jslint_settings, :compressor
  end

  class Base
    class << self
      def configuration
        @configuration ||= Epic::Configuration.new
      end

      def configure
        yield configuration
      end
    end

    def configuration
      Epic::Base.configuration
    end

    # Parses out the <tt>base_path</tt> setting from a path to display it in a
    # less verbose way.
    #
    def display_path(filename=nil)
      filename ||= path
      display_path = File.expand_path(filename)
      display_path.gsub(base_path.to_s, "")
    end

    def base_path
      configuration.base_path || ""
    end

    def tmp_path
      configuration.tmp_path || "#{base_path}/tmp" || ""
    end

    def vendor_path
      @vendor_path ||= configuration.vendor_path || File.join(File.dirname(__FILE__), "..", "..", "vendor", "ext")
    end
  end
end


# * Parent Connector for APIs
# * author: juanma <jm.rodulfo.salcedo@gmail.com>
module Connectors #:nodoc:
  # === Heading
  # This class has all the common logic from <b>api connectors</b>.
  class ApiConnector
    attr_reader :logger, :api_client_id, :api_domain, :api_domain_format,
      :api_headers_token, :connection_protocol, :headers, :code, :cookies,
      :cookie_jar, :request, :body

    def initialize(options = {}) #:notnew:
      options.symbolize_keys!

      #@logger = Logger.new "#{Rails.root}/log/#{self.class.to_s.demodulize.underscore}.log"
      #@logger.level = Rails.logger.level

      opts_to_vars(options)
    end

    # makes a GET request
    #
    # ==== Attributes
    #  * +hash+ - Hash of Parameters
    #  ** +endpoint+ - Url endpoint ex. /product/get (no need to specify the version)
    #  ** +args+ - Request arguments, (add headers key for extra headers options) ex. hash[:headers] = { 'content-type' => 'xml' }
    #  ** +params+ - Request parameters. ex. hash[:params] = { 'merchantId' => 'XXXXXX' }
    def get(hash={})
      hash.symbolize_keys!
      call(:get, hash[:endpoint], (hash[:args]||{}), hash[:params]||{})
    end

    def delete(hash={})
      hash.symbolize_keys!
      call(:delete, hash[:endpoint], (hash[:args]||{}), hash[:params]||{})
    end

    # makes a POST request
    #
    # ==== Attributes
    # * +hash+ - Hash of parameters
    # ** +endpoint+ - Url endpoint ex. /product/createOrUpdate
    # ** +args+ - Request arguments, (add headers key for extra headers options) ex. hash[:headers] = { 'content-type' => 'xml' }
    # * +payload+ - Data for the request ex. { merchantId: 'asdasdsadas', products: [{ ... },{ ...}...]}
    def post hash={}, payload
      raise 'Payload cannot be blank' if payload.nil? || payload.empty?

      hash.symbolize_keys!
      call(:post, hash[:endpoint], (hash[:args]||{}).merge({:method => :post}), payload)
    end

    # low level api for request (needed por PUT, PATCH & DELETE methods)
    #
    # ==== Attributes
    # * +endpoint+ - Url endpoint ex. /merchant/get
    # * +args+ - Request arguments, (add headers key for extra headers options) ex. { method: :get, headers: { 'content-type' => 'xml' } } (method key is needed, otherwise :get will be setted)
    # * +params+ - Request parameters / payload data
    def call method, endpoint, args={}, params
      raise "Endpoint can't be blank" unless endpoint
      raise "Method is missing" unless method

      url = (method == :get || method == :delete) ? url(endpoint,params) : url(endpoint)

      RestClient::Request.execute(method: method,
                              url: url,
                              headers: header(args[:headers]),
                              payload: params || {}
                             ) do |response, request, result|
                               #status = response.code == 200 ? :debug : :error
                               #print(status, request, response.body)
                               parse(response, endpoint)
                             end

    end

    def parse(response, endpoint = nil)
      @headers, @code, @cookies, @cookie_jar, @request, @body = response.headers, response.code, response.cookies, response.cookie_jar, response.request, response.body
      begin
        JSON.parse(response)
      rescue JSON::ParserError
        { status: '400', message: "RestClient failed to parse JSON: #{response}" }
      end
    end

    protected

    def opts_to_vars(opts)
      instance_eval do
        opts.each do |k, v|
          instance_variable_set("@#{k}".to_sym, v)
        end
      end
    end

    def header headers={}
      (common_headers || {}).merge({
        'X-Client-Id' => @x_person_id,
        'Content-Type' => @content_type || 'application/json',
        'Charset' => @charset || 'utf-8'
      }).merge(headers || {})
    end

    def url endpoint, args={}
      url_constructor endpoint, args
    end

    def print(status, request, response)
      status = :debug
      @logger.send(status,
                   "#{DateTime.now} "\
                   "- Request: #{request.inspect} "\
                   "- Response: #{response.force_encoding('utf-8')}"
                  )
    end

    def common_headers
      { 'X-Client-Id' => @api_client_id }.merge(
        {"Authorization" => "Basic #{@api_headers_token}"}
      ) if @api_headers_token
    end

    def url_constructor endpoint, hash
      url = "#{@connection_protocol}://#{format(@api_domain)}" << "/#{format(endpoint)}"
      url << ("?#{parametrize(hash)}") unless hash.empty?
      Addressable::URI.parse(url).normalize.to_str
    end

    def parametrize hash
      hash.map do |key,values|
        [values].flatten.map do |value|
          "#{key}=#{value}"
        end
      end.join('&')
    end

    def format string
      match_data = string.match(/\w+.+\w+/)
      match_data ? match_data[0] : ''
    end
  end
end


module Ropenstack
=begin
	* Name: Networking
	* Description: An implementation of the Networking V2.0 API Client in Ruby
	* Authors: Sam 'Tehsmash' Betts, John Davidge
	* Date: 01/15/2013
=end
  class Networking < OpenstackService
    require 'ropenstack/networking/v2'

    ## Extensions
    include Version2::Extensions::L3
    include Version2::Extensions::LBaaS
    include Version2::Extensions::Metering
    include Version2::Extensions::Quotas
    include Version2::Extensions::SecurityGroups

    ## Networks

    ##
    # Get a list of a tenants networks
    #
    # :call-seq:
    #   networks(id) => A single network with the id matching the parameter
    #   networks => All networks visible to the tenant making the request
    ##
    def networks(id = nil)
      endpoint = "networks"
      unless id.nil?
        endpoint = endpoint + "/" + id
      end
      return get_request(address(endpoint), @token)
    end

    ##
    # Create a new network on Openstack given a name and tenant id.
    ##
    def create_network(name, tenant, admin_state_up = true)
      data = {
        'network' => {
          'name' => name,
          'tenant_id' => tenant,
          'admin_state_up' => admin_state_up
        }
      }
      return post_request(address("networks"), data, @token)
    end

    ##
    # Delete a network given a network id.
    ##
    def delete_network(network)
      return delete_request(address("networks/" + network), @token)
    end

    ## Subnets

    ##
    # Get a list of subnets
    ##
    def subnets
      return get_request(address("subnets"), @token)
    end

    ##
    # Create a new ipv4 subnet in a network, given a network id, and
    # a IP range in CIDR format.
    ##
    def create_subnet(network, cidr)
      data = {
        'subnet' => {
          'network_id' => network,
          'ip_version' => 4,
          'cidr' => cidr
        }
      }
      return post_request(address("subnets"), data, @token)
    end

    ##
    # Delete a subnet given a subnet id
    ##
    def delete_subnet(subnet)
      return delete_request(address("subnets/" + subnet), @token)
    end

    ## Ports

    ##
    # Get a list of ports
    ##
    def ports
      return get_request(address("ports"), @token)
    end

    ##
    # Get a list of ports specific to a device_id
    ##
    def device_ports(device_id)
      return get_request(address("ports?device_id=#{device_id}"), @token)
    end

    ##
    # Create a new port given network and device ids, optional
    # parameter subnet id allows for scoping the port to a single subnet.
    ##
    def create_port(network, subnet = nil, device = nil, device_owner = nil)
      data = {
        'port' => {
          'network_id' => network,
        }
      }
      unless device_owner.nil?
        data['port']['device_owner'] = device_owner
      end
      unless device.nil?
        data['port']['device_id'] = device
      end
      unless subnet.nil?
        data['port']['fixed_ips'] = [{'subnet_id' => subnet}]
      end

      puts data

      return post_request(address("ports"), data, @token)
    end

    ##
    # Update a specific ports fixed_ips, including subnet and ip data.
    ##
    def update_port(port, fixed_ips)
      data = { 'port' => { 'fixed_ips' => fixed_ips } }
      return put_request(address("ports/"+port), data, @token)
    end

    ##
    # Weird function for adding a port to multiple subnets if nessessary.
    ##
    def move_port_to_subnets(port_id, subnet_ids)
      id_list = Array.new()
      subnet_ids.each do |id|
        id_list << { "subnet_id" => id }
      end
      return update_port(port_id, id_list)
    end

    ##
    # Delete a port given a port id.
    ##
    def delete_port(port)
      return delete_request(address("ports/" + port), @token)
    end

    private

    def address(endpoint)
      super("/v2.0/#{endpoint}")
    end
  end
end


require 'time'
require 'json'
require 'rack'
require 'rack/filters'

module Rack
  class Action
    VERSION = '0.5.1'

    extend Filters

    # @private
    RACK_ROUTE_PARAMS = 'rack.route_params'.freeze
    # @private
    CONTENT_TYPE = 'Content-Type'.freeze
    # @private
    HTTP_ACCEPT = 'HTTP_ACCEPT'.freeze
    # @private
    TEXT_HTML = 'text/html'.freeze
    # @private
    APPLICATION_JSON = 'application/json'.freeze
    # @private
    LOCATION = 'Location'.freeze
    # @private
    DEFAULT_RESPONSE = "Default Rack::Action Response"
    # @private
    RACK_INPUT = 'rack.input'.freeze

    # This implements the Rack interface
    #
    # @param [Hash] env The Rack environment
    # @return [Array<Numeric, Hash, #each>] A Rack response
    def self.call(env)
      new(env).call
    end

    attr_accessor :env, :request, :response, :params

    def initialize(env)
      @env = env
    end

    def request
      @request ||= Rack::Request.new(env)
    end

    def response
      @response ||= Rack::Response.new
    end

    def params
      @params ||= begin
        p = request.params.merge(env[RACK_ROUTE_PARAMS] || {})
        if request.content_type.to_s.include?(APPLICATION_JSON)
          body = env[RACK_INPUT].read
          env[RACK_INPUT].rewind
          p.merge!(self.class.json_serializer.load(body)) if body.present?
        end
        p.respond_to?(:with_indifferent_access) ? p.with_indifferent_access : p
      end
    end

    def format
      if params[:format]
        params[:format]
      elsif env[HTTP_ACCEPT] == APPLICATION_JSON
        "json"
      else
        "html"
      end
    end

    # This is the main method responsible for generating a Rack response.
    # You typically won't need to override this method or call it directly.
    # First this will run the before filters for this action.
    # If none of the before filters generate a response, this will call
    # {#respond} to generate a response.
    # All after filters for this action are called once the response
    # is genenated.  Finally the response is returned.
    #
    # @return [Array<Numeric, Hash, #each>] A Rack response
    def call
      log_call
      set_default_headers
      run_before_filters
      run_respond
      run_after_filters
      finish_response
    end

    # This is the main method that you should override in your action.
    # You can either write to the response during this method, or simply
    # return a string, which will be written to the response if the
    # response is still empty after this is called.
    #
    # @return [String] The Rack response or a String
    def respond
      DEFAULT_RESPONSE
    end

    # This is a convenience method that sets the Content-Type headers
    # and writes the JSON String to the response.
    #
    # @param [Hash] data The data
    # @param [Hash] options The options
    # @option options [Fixnum] :status The response status code
    # @return [String] The JSON
    def json(data={}, options={})
      response[CONTENT_TYPE] = APPLICATION_JSON
      response.status = options[:status] if options.has_key?(:status)
      response.write self.class.json_serializer.dump(data)
    end

    # This is a convenience method that forms an absolute URL based on the
    # url parameter, which can be a relative or absolute URL, and then
    # sets the headers and the body appropriately to do a 302 redirect.
    #
    # @see #absolute_url
    # @return [String] The absolute url
    def redirect_to(url, options={})
      full_url = absolute_url(url, options)
      response[LOCATION] = full_url
      respond_with 302
      full_url
    end

    # Convenience method to return a 404
    def not_found
      respond_with 404
    end

    # Convenience method to return a 403
    def forbidden
      respond_with 403
    end

    # This is a convenience method to set the response code and
    # set the response so that it stops respond process.
    #
    # @param [Fixnum] status_code The HTTP status code to use in the response
    def respond_with(status_code)
      response.status = status_code
      response.write ''
      nil
    end

    # Generate an absolute url from the url.  If the url is already
    # an absolute url, this will return it unchanged.
    #
    # @param [String] url The URL
    # @param [Hash] options The options to use to generate the absolute URL
    # @option options [true, false] :https If https should be used,
    #   uses rack.url_scheme from the Rack env to determine the default
    # @option options [String] :host The host to use,
    #   uses SERVER_NAME form the Rack env for the default
    # @option options [String, Numeric] :port The port to use,
    #   users SERVER_PORT from the Rack env for the default
    # @return [String] The absolute url
    def absolute_url(url, options={})
      URL.new(env, url, options).to_absolute
    end

    protected
    def log_call
      if logger
        logger.debug do
          "#{self.class} #{request.env["REQUEST_METHOD"]} format: #{format.inspect}, params: #{params.inspect}"
        end
      end
    end

    def set_default_headers
      response[CONTENT_TYPE] = TEXT_HTML
    end

    def run_before_filters
      self.class.before_filters.each do |filter|
        logger.debug "Running #{filter} before filter" if logger
        send(filter)
        unless response.empty?
          logger.debug "#{filter} responded, halting filter chain" if logger
          return
        end
      end
    end

    def run_respond
      return if !response.empty?
      body = respond
      if response.empty?
        response.write body
      else
        body
      end
    end

    def run_after_filters
      self.class.after_filters.each do |filter|
        logger.debug "Running #{filter} after filter" if logger
        send(filter)
      end
    end

    def finish_response
      response.finish
    end

    def logger
      self.class.logger
    end

    def self.logger
      if defined? @logger
        @logger
      else
        @logger = superclass.logger if superclass.respond_to?(:logger)
      end
    end

    def self.logger=(logger)
      @logger = logger
    end

    def self.json_serializer
      if defined? @json_serializer
        @json_serializer
      else
        @json_serializer = if superclass.respond_to?(:json_serializer)
          superclass.json_serializer
        else
          JSON
        end
      end
    end

    def self.json_serializer=(json_serializer)
      @json_serializer = json_serializer
    end

    # @private
    class URL
      HTTPS = 'https'.freeze
      HTTP_PREFIX = 'http://'.freeze
      HTTPS_PREFIX = 'https://'.freeze
      ABSOLUTE_URL_REGEX = /\Ahttps?:\/\//
      RACK_URL_SCHEME = 'rack.url_scheme'
      SERVER_NAME = 'SERVER_NAME'.freeze
      SERVER_PORT = 'SERVER_PORT'.freeze
      DEFAULT_HTTP_PORT = 80
      DEFAULT_HTTPS_PORT = 443

      attr_accessor :env, :url, :https, :host, :port

      def initialize(env, url, options={})
        @env = env
        @url = url.to_s
        @options = options || {}
        @https = options.fetch(:https, env[RACK_URL_SCHEME] == HTTPS)
        @host = options.fetch(:host, env[SERVER_NAME])
        @port = Integer(options.fetch(:port, env[SERVER_PORT]))
      end

      def to_absolute
        if url =~ ABSOLUTE_URL_REGEX
          url
        else
          absolute_url = [prefix]
          absolute_url << (port == default_port ? host : "#{host}:#{port}")
          absolute_url << url
          ::File.join(*absolute_url)
        end
      end

      def prefix
        https ? HTTPS_PREFIX : HTTP_PREFIX
      end

      def default_port
        https ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT
      end
    end

  end
end


module Ov
  class OverrideMethod # :nodoc:
    attr_accessor :types, :body, :name, :owner, :ancestors

    # +name+ (Symbol) : name for method
    # +types+ (Array) : array with types, for method arguments
    # +body+ (Proc)   : block called with method
    def initialize(name, types, owner, body = proc{})
      @name, @types, @owner, @body = name, types, owner, body
      @ancestors = owner.ancestors.find_all do |ancestor|
        ancestor.method_defined?(:__overload_methods) && ancestor.class == Class
      end
    end

    def eql?(other) #:nodoc:
      return true if @name == other.name && @types == other.types && @owner == other.owner
      false
    end

    def eql0?(other) #:nodoc:
      @ancestors.find{|a|
        a.__overload_methods.find{|m|
          m.name == other.name && m.types == other.types
        }
      }
    end

    def like?(other) #:nodoc:
      return compare?(types, other.types) if @name == other.name
      false
    end

    def like0?(other) #:nodoc:
      @ancestors.find{|a|
        a.__overload_methods.find{|m|
          m.like?(other)
        }
      }
    end

    private
    def compare?(a, b)
      return false if a.size != b.size
      !a.zip(b).map { |arr|
        first, last = arr
        true if (first == Ov::Any) || (last == Ov::Any) || (first == last)
      }.include?(nil)
    end
  end
end


require 'active_support/core_ext/hash/deep_merge'

module Lego
  class Model
    class ParseError < StandardError
      def initialize(errors={})
        @errors = errors
        super(errors.inspect)
      end

      attr_reader :errors
    end

    private_class_method :new

    class << self

      def attribute(attr, type, *args)
        parsers[attr.to_sym] = Lego.value_parser(type, *args)
      end

      def parsers
        @_parsers ||= {}
      end

      def validations
        @_validations ||= Hash.new { |h,k| h[k] = [] }
      end

      def attribute_names
        parsers.keys
      end

      def validates(attr, callable=nil, &block)
        attr = attr.to_sym
        if callable && callable.is_a?(Symbol)
          validations[attr] << callable
        else
          validations[attr] << block
        end
      end

      def coerce(hash)
        res = parse(hash)
        res.value? ? res.value : fail(ParseError.new(res.error))
      end

      def parse(hash)
        return Lego.just(hash) if hash.instance_of?(self)

        fail ArgumentError, "attrs must be hash: '#{hash.inspect}'" unless hash.respond_to?(:key?)

        result = _parse(hash)

        if result.value?
          model = new(result.value)
          _validate(model)
        else
          result
        end
      end

      def _validate(obj)
        attrs = {}
        validations.each do |name, attr_validations|
          attrs[name] = Lego.just(obj)
          attr_validations.each do |validation|
            if validation.is_a?(Symbol)
              callable_method_name = validation.to_sym
              validation = ->(o){ o.method(callable_method_name).call }
            end
            attrs[name] = attrs[name].next(validation)
          end
        end

        if attrs.all?{ |k,v| v.value? }
          Lego.just(obj)
        else
          Lego.fail(Hash[*attrs.map{ |k,v| [k, v.error] if v.error? }.compact.flatten(1)])
        end
      end

      def _parse(data)
        data = data.dup

        attrs = {}

        parsers.each do |name, parser|
          name = name.to_sym
          value = data.key?(name) ? data.delete(name) : data.delete(name.to_s)

          attrs[name] = parser.parse(value)
        end

        fail ArgumentError, "Unknown attributes: #{data}" unless data.empty?

        if attrs.all?{ |k,v| v.value? }
          Lego.just(Hash[*attrs.map{ |k,v| [k, v.value] }.flatten(1)])
        else
          Lego.fail(Hash[*attrs.map{ |k,v| [k, v.error] if v.error? }.compact.flatten(1)])
        end
      end
    end

    def initialize(attrs={})
      @attributes = attrs.freeze
    end

    attr_reader :attributes

    def merge(other)
      self.class.coerce(as_json.deep_merge(other))
    end

    def method_missing(name, *args, &block)
      attributes.fetch(name.to_sym) { super }
    end

    # Equality

    def ==(o)
      o.class == self.class && o.attributes == attributes
    end
    alias_method :eql?, :==

    def hash
      attributes.hash
    end

    # Serialize

    def as_json(opts={})
      raise NotImplementedError, 'as_json with arguments' unless opts.empty?
      {}.tap do |h|
        attributes.each do |attr, val|
          h[attr] = val.as_json
        end
      end
    end
  end
end


require 'ropenstack/common/rest'
require 'uri'

module Ropenstack
=begin
	* Name: Compute
	* Description: Implementation of the Compute API Client in Ruby
	* Author: Sam 'Tehsmash' Betts
	* Date: 01/15/2013
=end
  class Compute < OpenstackService
    require 'ropenstack/compute/v2'
    require 'ropenstack/compute/v3'

    include Version2

    ##
    # Gets a list of servers from OpenStack
    #
    # :call-seq:
    #   servers(id) => A single server with the id matching the parameter
    #   servers() => All servers visible to the tenant making the request
    ##
    def servers(id)
      endpoint = "/servers"
      unless id.nil?
        endpoint = endpoint + "/" + id
      end
      return get_request(address(endpoint), @token)
    end

    ##
    # Gets a more detailed list of servers from openstack.
    ##
    def servers_detailed()
      return get_request(address("/servers/detail"), @token)
    end

    ##
    # Creates a server on OpenStack.
    ##
    def create_server(name, image, flavor, networks = nil, keypair = nil, security_group = nil, metadata = nil)
      data = {
        "server" => {
          "name" => name,
          "imageRef" => image,
          "flavorRef" => flavor,
        }
      }
      unless networks.nil?
        data["server"]["networks"] = networks
      end
      unless keypair.nil?
        data["server"]["key_name"] = keypair
      end
      unless security_group.nil?
        data["server"]["security_group"] = security_group
      end
      return post_request(address("/servers"), data, @token)
    end

    ##
    # Deletes a server from Openstack based on an id
    ##
    def delete_server(id)
      return delete_request(address("/servers/" + id), @token)
    end

    ##
    # Perform an action on a server on Openstack, by passing an id,
    # and an action, some actions require more data.
    #
    # E.g. action(id, "reboot", "hard")
    ##
    def action(id, act, *args)
      data = case act
        when "reboot" then {'reboot' =>{"type" => args[0]}}
        when "vnc" then {'os-getVNCConsole' => { "type" => "novnc" }}
        when "stop" then {'os-stop' => 'null'}
        when "start" then {'os-start' => 'null'}
        when "pause" then {'pause' => 'null'}
        when "unpause" then {'unpause' => 'null'}
        when "suspend" then {'suspend' => 'null'}
        when "resume" then {'resume' => 'null'}
        when "create_image" then {'createImage' => {'name' => args[0], 'metadata' => args[1]}}
        else raise "Invalid Action"
        end
      return post_request(address("/servers/" + id + "/action"), data, @token)
    end

    ##
    # Retrieve a list of images from Openstack through the nova endpoint
    ##
    def images()
      uri = URI.parse("http://" + @location.host + ":9292/v2/images")
      return get_request(uri, @token)
    end

    ##
    # Delete an image stored on Openstack through the nova endpoint
    ##
    def delete_image(id)
      uri = URI.parse("http://" + @location.host + ":" + @location.port.to_s + "/v2/images/" + id)
      return delete_request(uri, @token)
    end

    ##
    # Get a list of flavors that Servers can be
    ##
    def flavors()
      return get_request(address("/flavors/detail"), @token)
    end

    ##
    # Get a tenants compute quotas
    ##
    def limits()
      return get_request(address("/limits"), @token)
    end

    ##
    # Get a list of Compute Extensions
    ##
    def extensions(ali)
      if ali.nil?
        return get_request(address("/extensions"), @token)
      else
        return get_request(address("/extensions/"+ ali), @token)
      end
    end

    def metadata(id, key)
      if key.nil?
        return get_request(address("/servers/"+id+"/metadata"), @token)
      else
        return get_request(address("/servers/"+id+"/metadata/" + key), @token)
      end
    end

    def set_metadata(id, data, key)
      if key.nil?
        return put_request(address("/servers/"+id+"/metadata"), data, @token)
      else
        return put_request(address("/servers/"+id+"/metadata/"+key), data, @token)
      end
    end

    def update_metadata(id, data)
      return post_request(address("/servers/"+id+"/metadata"), data, @token)
    end

    def delete_metadata(id, key)
      return delete_request(address("/servers/"+id+"/metadata/" + key), @token)
    end

    def ips(id, network)
      if network.nil?
        return get_request(address("/servers/"+id+"/ips"), @token)
      else
        return get_request(address("/servers/"+id+"/ips/" + network), @token)
      end
    end
  end
end


require 'open-uri'
require 'json'

module RSqoot
  module Request

    # Get method, use by all other API qeury methods, fetch records
    # from the Sqoot API V2 url, and provide wrapper functionality
    #
    def get(path, opts = {}, wrapper = ::Hashie::Mash)
      uri, headers = url_generator(path, opts)
      begin
        json = JSON.parse uri.open(headers).read
        result = wrapper.new json
        @query_options = result.query
        result
      rescue => e
        logger(error: e)
        nil
      end
    end

    # Generate valid Sqoot API V2 url and provide two different way of
    # authentication: :header, :parameter
    #
    def url_generator(path, opts = {}, require_key = false)
      uri      = URI.parse base_api_url
      headers  = { read_timeout: read_timeout }
      uri.path = '/v2/' + path
      query    = options_parser opts
      endpoint = path.split('/')[0]
      case authentication_method
      when :header
        headers.merge! 'Authorization' => "api_key #{api_key(endpoint)}"
        query += "&api_key=#{api_key(endpoint)}" if require_key
      when :parameter
        query += "&api_key=#{api_key(endpoint)}"
      end
      uri.query = query
      @sqoot_query_uri = uri
      [uri, headers]
    end

    private

    # Endpoints that needs private key
    #
    def private_endpoints
      %w(clicks commissions)
    end

    # Endpoints that both public or private key will work
    #
    def public_endpoints
      %w(categories deals merchants providers)
    end

    # Decide which api key should be used: private, public
    def api_key(endpoint = '')
      if private_endpoints.include? endpoint
        private_api_key
      elsif public_endpoints.include? endpoint
        public_api_key
      else
        fail "No such endpoint #{endpoint} available."
      end
    end

    # Example: options = {per_page: 10, page: 1}
    # Options should be parsed as http query: per_page=10&page=1
    #
    # @return [String]
    def options_parser(options = {})
      query = options.map do |key, value|
        [key, value].map(&:to_s).join('=')
      end.join('&')
      URI.encode query
    end
  end
end