text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>ActiveRecord::Associations::CollectionProxy</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" href="../../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../../css/github.css" type="text/css" media="screen" />

            Ruby on Rails 4.2.1

            Class
            ActiveRecord::Associations::CollectionProxy

                <

                    Relation

/Users/tony/.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb

Association proxies in Active Record are middlemen between the object that
holds the association, known as the @owner, and the actual
associated object, known as the @target. The kind of
association any proxy is about is available in @reflection.
That's an instance of the class
ActiveRecord::Reflection::AssociationReflection.

For example, given

class Blog < ActiveRecord::Base
  has_many :posts
end

blog = Blog.first

the association proxy in blog.posts has the object in
blog as @owner, the collection of its posts as
@target, and the @reflection object represents a
:has_many macro.

This class delegates unknown methods to @target via
method_missing.

The @target object is not loaded until needed. For example,

blog.posts.count

is computed directly through SQL and does not trigger by itself the
instantiation of the actual post records.

Methods

#

                <<,

                ==

A

                any?,

                append,

                arel

B

                build

C

                clear,

                concat,

                count,

                create,

                create!

D

                delete,

                delete_all,

                destroy,

                destroy_all,

                distinct

E

                empty?

F

                fifth,

                find,

                first,

                forty_two,

                fourth

I

                include?

L

                last,

                length,

                load_target,

                loaded?

M

                many?

N

                new

P

                prepend,

                proxy_association,

                push

R

                reload,

                replace,

                reset

S

                scope,

                scoping,

                second,

                select,

                size,

                spawn

T

                take,

                target,

                third,

                to_a,

                to_ary

U

                uniq

Instance Public methods

              <<(*records)

            Link

Adds one or more records to the collection by setting their
foreign keys to the association's primary key. Returns
self, so several appends may be chained together.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets.size # => 0
person.pets << Pet.new(name: 'Fancy-Fancy')
person.pets << [Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo')]
person.pets.size # => 3

person.id # => 1
person.pets
# => [
#      #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#      #<Pet id: 2, name: "Spook", person_id: 1>,
#      #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

              Also aliased as: push, append

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 968
def <<(*records)
  proxy_association.concat(records) && self
end

              ==(other)

            Link

Equivalent to Array#==. Returns true if the two
arrays contain the same number of elements and if each element is equal to
the corresponding element in the other array, otherwise
returns false.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets
# => [
#      #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#      #<Pet id: 2, name: "Spook", person_id: 1>
#    ]

other = person.pets.to_ary

person.pets == other
# => true

other = [Pet.new(id: 1), Pet.new(id: 2)]

person.pets == other
# => false

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 906
def ==(other)
  load_target == other
end

              any?(&block)

            Link

Returns true if the collection is not empty.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets.count # => 0
person.pets.any?  # => false

person.pets << Pet.new(name: 'Snoop')
person.pets.count # => 0
person.pets.any?  # => true

You can also pass a block to define criteria. The behavior is
the same, it returns true if the collection based on the criteria is not
empty.

person.pets
# => [#<Pet name: "Snoop", group: "dogs">]

person.pets.any? do |pet|
  pet.group == 'cats'
end
# => false

person.pets.any? do |pet|
  pet.group == 'dogs'
end
# => true

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 804
def any?(&block)
  @association.any?(&block)
end

              append(*records)

            Link

              Alias for: <<

              arel()

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 860
def arel
  scope.arel
end

              build(attributes = {}, &block)

            Link

Returns a new object of the collection type that has been instantiated with
attributes and linked to this object, but have not yet been
saved. You can pass an array of attributes hashes, this will return an
array with the new objects.

class Person
  has_many :pets
end

person.pets.build
# => #<Pet id: nil, name: nil, person_id: 1>

person.pets.build(name: 'Fancy-Fancy')
# => #<Pet id: nil, name: "Fancy-Fancy", person_id: 1>

person.pets.build([{name: 'Spook'}, {name: 'Choo-Choo'}, {name: 'Brain'}])
# => [
#      #<Pet id: nil, name: "Spook", person_id: 1>,
#      #<Pet id: nil, name: "Choo-Choo", person_id: 1>,
#      #<Pet id: nil, name: "Brain", person_id: 1>
#    ]

person.pets.size  # => 5 # size of the collection
person.pets.count # => 0 # count from database

              Also aliased as: new

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 258
def build(attributes = {}, &block)
  @association.build(attributes, &block)
end

              clear()

            Link

Equivalent to delete_all. The difference is that returns
self, instead of an array with the deleted objects, so methods
can be chained. See delete_all for more information.

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 981
def clear
  delete_all
  self
end

              concat(*records)

            Link

Add one or more records to the collection by setting their foreign keys to
the association's primary key. Since << flattens its argument
list and inserts each record, push and concat
behave identically. Returns self so method calls may be
chained.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets.size # => 0
person.pets.concat(Pet.new(name: 'Fancy-Fancy'))
person.pets.concat(Pet.new(name: 'Spook'), Pet.new(name: 'Choo-Choo'))
person.pets.size # => 3

person.id # => 1
person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.concat([Pet.new(name: 'Brain'), Pet.new(name: 'Benny')])
person.pets.size # => 5

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 333
def concat(*records)
  @association.concat(*records)
end

              count(column_name = nil, options = {})

            Link

Count all records using SQL.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets.count # => 3
person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 695
def count(column_name = nil, options = {})
  # TODO: Remove options argument as soon we remove support to
  # activerecord-deprecated_finders.
  @association.count(column_name, options)
end

              create(attributes = {}, &block)

            Link

Returns a new object of the collection type that has been instantiated with
attributes, linked to this object and that has already been saved (if it
passes the validations).

class Person
  has_many :pets
end

person.pets.create(name: 'Fancy-Fancy')
# => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>

person.pets.create([{name: 'Spook'}, {name: 'Choo-Choo'}])
# => [
#      #<Pet id: 2, name: "Spook", person_id: 1>,
#      #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.size  # => 3
person.pets.count # => 3

person.pets.find(1, 2, 3)
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 289
def create(attributes = {}, &block)
  @association.create(attributes, &block)
end

              create!(attributes = {}, &block)

            Link

Like create, except that if the record is invalid, raises an
exception.

class Person
  has_many :pets
end

class Pet
  validates :name, presence: true
end

person.pets.create!(name: nil)
# => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 305
def create!(attributes = {}, &block)
  @association.create!(attributes, &block)
end

              delete(*records)

            Link

Deletes the records supplied and removes them from the
collection. For has_many associations, the deletion is done
according to the strategy specified by the :dependent option.
Returns an array with the deleted records.

If no :dependent option is given, then it will follow the
default strategy. The default strategy is :nullify. This sets
the foreign keys to NULL. For, has_many
:through, the default strategy is delete_all.

class Person < ActiveRecord::Base
  has_many :pets # dependent: :nullify option by default
end

person.pets.size # => 3
person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.delete(Pet.find(1))
# => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]

person.pets.size # => 2
person.pets
# => [
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

Pet.find(1)
# => #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>

If it is set to :destroy all the records are
removed by calling their destroy method. See
destroy for more information.

class Person < ActiveRecord::Base
  has_many :pets, dependent: :destroy
end

person.pets.size # => 3
person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.delete(Pet.find(1), Pet.find(3))
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.size # => 1
person.pets
# => [#<Pet id: 2, name: "Spook", person_id: 1>]

Pet.find(1, 3)
# => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 3)

If it is set to :delete_all, all the records are
deleted without calling their destroy method.

class Person < ActiveRecord::Base
  has_many :pets, dependent: :delete_all
end

person.pets.size # => 3
person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.delete(Pet.find(1))
# => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]

person.pets.size # => 2
person.pets
# => [
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

Pet.find(1)
# => ActiveRecord::RecordNotFound: Couldn't find Pet with id=1

You can pass Fixnum or String values, it finds
the records responding to the id and executes delete on them.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets.size # => 3
person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.delete("1")
# => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]

person.pets.delete(2, 3)
# => [
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 587
def delete(*records)
  @association.delete(*records)
end

              delete_all(dependent = nil)

            Link

Deletes all the records from the collection according to the strategy
specified by the :dependent option. If no
:dependent option is given, then it will follow the default
strategy.

For +has_many :through+ associations, the default deletion strategy is
:delete_all.

For has_many associations, the default deletion strategy is
:nullify. This sets the foreign keys to NULL.

class Person < ActiveRecord::Base
  has_many :pets # dependent: :nullify option by default
end

person.pets.size # => 3
person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.delete_all
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.size # => 0
person.pets      # => []

Pet.find(1, 2, 3)
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: nil>,
#       #<Pet id: 2, name: "Spook", person_id: nil>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: nil>
#    ]

Both has_many and +has_many :through+ dependencies default to
the :delete_all strategy if the :dependent option
is set to :destroy. Records are not instantiated and callbacks
will not be fired.

class Person < ActiveRecord::Base
  has_many :pets, dependent: :destroy
end

person.pets.size # => 3
person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.delete_all

Pet.find(1, 2, 3)
# => ActiveRecord::RecordNotFound

If it is set to :delete_all, all the objects are deleted
without calling their destroy method.

class Person < ActiveRecord::Base
  has_many :pets, dependent: :delete_all
end

person.pets.size # => 3
person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.delete_all

Pet.find(1, 2, 3)
# => ActiveRecord::RecordNotFound

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 442
def delete_all(dependent = nil)
  @association.delete_all(dependent)
end

              destroy(*records)

            Link

Destroys the records supplied and removes them from the
collection. This method will always remove record from the
database ignoring the :dependent option. Returns an array with
the removed records.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets.size # => 3
person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.destroy(Pet.find(1))
# => [#<Pet id: 1, name: "Fancy-Fancy", person_id: 1>]

person.pets.size # => 2
person.pets
# => [
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.destroy(Pet.find(2), Pet.find(3))
# => [
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.size  # => 0
person.pets       # => []

Pet.find(1, 2, 3) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (1, 2, 3)

You can pass Fixnum or String values, it finds
the records responding to the id and then deletes them from
the database.

person.pets.size # => 3
person.pets
# => [
#       #<Pet id: 4, name: "Benny", person_id: 1>,
#       #<Pet id: 5, name: "Brain", person_id: 1>,
#       #<Pet id: 6, name: "Boss",  person_id: 1>
#    ]

person.pets.destroy("4")
# => #<Pet id: 4, name: "Benny", person_id: 1>

person.pets.size # => 2
person.pets
# => [
#       #<Pet id: 5, name: "Brain", person_id: 1>,
#       #<Pet id: 6, name: "Boss",  person_id: 1>
#    ]

person.pets.destroy(5, 6)
# => [
#       #<Pet id: 5, name: "Brain", person_id: 1>,
#       #<Pet id: 6, name: "Boss",  person_id: 1>
#    ]

person.pets.size  # => 0
person.pets       # => []

Pet.find(4, 5, 6) # => ActiveRecord::RecordNotFound: Couldn't find all Pets with IDs (4, 5, 6)

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 659
def destroy(*records)
  @association.destroy(*records)
end

              destroy_all()

            Link

Deletes the records of the collection directly from the database ignoring
the :dependent option. Records are instantiated and it invokes
before_remove, after_remove ,
before_destroy and after_destroy callbacks.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets.size # => 3
person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.destroy_all

person.pets.size # => 0
person.pets      # => []

Pet.find(1) # => Couldn't find Pet with id=1

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 469
def destroy_all
  @association.destroy_all
end

              distinct()

            Link

Specifies whether the records should be unique or not.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets.select(:name)
# => [
#      #<Pet name: "Fancy-Fancy">,
#      #<Pet name: "Fancy-Fancy">
#    ]

person.pets.select(:name).distinct
# => [#<Pet name: "Fancy-Fancy">]

              Also aliased as: uniq

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 677
def distinct
  @association.distinct
end

              empty?()

            Link

Returns true if the collection is empty. If the collection has
been loaded it is equivalent to collection.size.zero?. If the
collection has not been loaded, it is equivalent to
collection.exists?. If the collection has not already been
loaded and you are going to fetch the records anyway it is better to check
collection.length.zero?.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets.count  # => 1
person.pets.empty? # => false

person.pets.delete_all

person.pets.count  # => 0
person.pets.empty? # => true

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 771
def empty?
  @association.empty?
end

              fifth(*args)

            Link

Same as first except returns only the fifth record.

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 190
def fifth(*args)
  @association.fifth(*args)
end

              find(*args, &block)

            Link

Finds an object in the collection responding to the id. Uses
the same rules as ActiveRecord::Base.find. Returns
ActiveRecord::RecordNotFound error if the object cannot be
found.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.find(1) # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>
person.pets.find(4) # => ActiveRecord::RecordNotFound: Couldn't find Pet with id=4

person.pets.find(2) { |pet| pet.name.downcase! }
# => #<Pet id: 2, name: "fancy-fancy", person_id: 1>

person.pets.find(2, 3)
# => [
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 140
def find(*args, &block)
  @association.find(*args, &block)
end

              first(*args)

            Link

Returns the first record, or the first n records, from the
collection. If the collection is empty, the first form returns
nil, and the second form returns an empty array.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.first # => #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>

person.pets.first(2)
# => [
#      #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#      #<Pet id: 2, name: "Spook", person_id: 1>
#    ]

another_person_without.pets          # => []
another_person_without.pets.first    # => nil
another_person_without.pets.first(3) # => []

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 170
def first(*args)
  @association.first(*args)
end

              forty_two(*args)

            Link

Same as first except returns only the forty second record.
Also known as accessing "the reddit".

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 196
def forty_two(*args)
  @association.forty_two(*args)
end

              fourth(*args)

            Link

Same as first except returns only the fourth record.

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 185
def fourth(*args)
  @association.fourth(*args)
end

              include?(record)

            Link

Returns true if the given record is present in
the collection.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets # => [#<Pet id: 20, name: "Snoop">]

person.pets.include?(Pet.find(20)) # => true
person.pets.include?(Pet.find(21)) # => false

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 856
def include?(record)
  !!@association.include?(record)
end

              last(*args)

            Link

Returns the last record, or the last n records, from the
collection. If the collection is empty, the first form returns
nil, and the second form returns an empty array.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.last # => #<Pet id: 3, name: "Choo-Choo", person_id: 1>

person.pets.last(2)
# => [
#      #<Pet id: 2, name: "Spook", person_id: 1>,
#      #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

another_person_without.pets         # => []
another_person_without.pets.last    # => nil
another_person_without.pets.last(3) # => []

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 226
def last(*args)
  @association.last(*args)
end

              length()

            Link

Returns the size of the collection calling size on the target.
If the collection has been already loaded, length and
size are equivalent. If not and you are going to need the
records anyway this method will take one less query. Otherwise
size is more efficient.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets.length # => 3
# executes something like SELECT "pets".* FROM "pets" WHERE "pets"."person_id" = 1

# Because the collection is loaded, you can
# call the collection with no additional queries:
person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 749
def length
  @association.length
end

              load_target()

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 44
def load_target
  @association.load_target
end

              loaded?()

            Link

Returns true if the association has been loaded, otherwise
false.

person.pets.loaded? # => false
person.pets
person.pets.loaded? # => true

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 53
def loaded?
  @association.loaded?
end

              many?(&block)

            Link

Returns true if the collection has more than one record. Equivalent to
collection.size > 1.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets.count # => 1
person.pets.many? # => false

person.pets << Pet.new(name: 'Snoopy')
person.pets.count # => 2
person.pets.many? # => true

You can also pass a block to define criteria. The behavior is
the same, it returns true if the collection based on the criteria has more
than one record.

person.pets
# => [
#      #<Pet name: "Gorby", group: "cats">,
#      #<Pet name: "Puff", group: "cats">,
#      #<Pet name: "Snoop", group: "dogs">
#    ]

person.pets.many? do |pet|
  pet.group == 'dogs'
end
# => false

person.pets.many? do |pet|
  pet.group == 'cats'
end
# => true

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 842
def many?(&block)
  @association.many?(&block)
end

              new(attributes = {}, &block)

            Link

              Alias for: build

              prepend(*args)

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 974
def prepend(*args)
  raise NoMethodError, "prepend on association is not defined. Please use << or append"
end

              proxy_association()

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 864
def proxy_association
  @association
end

              push(*records)

            Link

              Alias for: <<

              reload()

            Link

Reloads the collection from the database. Returns self.
Equivalent to collection(true).

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets # fetches pets from the database
# => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]

person.pets # uses the pets cache
# => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]

person.pets.reload # fetches pets from the database
# => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]

person.pets(true)  # fetches pets from the database
# => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 1004
def reload
  proxy_association.reload
  self
end

              replace(other_array)

            Link

Replaces this collection with other_array. This will perform a
diff and delete/add only records that have changed.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets
# => [#<Pet id: 1, name: "Gorby", group: "cats", person_id: 1>]

other_pets = [Pet.new(name: 'Puff', group: 'celebrities']

person.pets.replace(other_pets)

person.pets
# => [#<Pet id: 2, name: "Puff", group: "celebrities", person_id: 1>]

If the supplied array has an incorrect association type, it raises an
ActiveRecord::AssociationTypeMismatch error:

person.pets.replace(["doo", "ggie", "gaga"])
# => ActiveRecord::AssociationTypeMismatch: Pet expected, got String

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 359
def replace(other_array)
  @association.replace(other_array)
end

              reset()

            Link

Unloads the association. Returns self.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets # fetches pets from the database
# => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]

person.pets # uses the pets cache
# => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]

person.pets.reset # clears the pets cache

person.pets  # fetches pets from the database
# => [#<Pet id: 1, name: "Snoop", group: "dogs", person_id: 1>]

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 1025
def reset
  proxy_association.reset
  proxy_association.reset_scope
  self
end

              scope()

            Link

Returns a Relation object for the records in this association

              Also aliased as: spawn

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 877
def scope
  @association.scope
end

              scoping()

            Link

We don't want this object to be put on the scoping stack, because that
could create an infinite loop where we call an @association method, which
gets the current scope, which is this object, which delegates to
@association, and so on.

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 872
def scoping
  @association.scope.scoping { yield }
end

              second(*args)

            Link

Same as first except returns only the second record.

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 175
def second(*args)
  @association.second(*args)
end

              select(*fields, &block)

            Link

Works in two ways.

First: Specify a subset of fields to be selected from the
result set.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.select(:name)
# => [
#      #<Pet id: nil, name: "Fancy-Fancy">,
#      #<Pet id: nil, name: "Spook">,
#      #<Pet id: nil, name: "Choo-Choo">
#    ]

person.pets.select(:id, :name )
# => [
#      #<Pet id: 1, name: "Fancy-Fancy">,
#      #<Pet id: 2, name: "Spook">,
#      #<Pet id: 3, name: "Choo-Choo">
#    ]

Be careful because this also means you're initializing a model object
with only the fields that you've selected. If you attempt to access a
field except id that is not in the initialized record
you'll receive:

person.pets.select(:name).first.person_id
# => ActiveModel::MissingAttributeError: missing attribute: person_id

Second: You can pass a block so it can be used just like
Array#select. This builds an array of objects from the database for the
scope, converting them into an array and iterating through them using
Array#select.

person.pets.select { |pet| pet.name =~ /oo/ }
# => [
#      #<Pet id: 2, name: "Spook", person_id: 1>,
#      #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.select(:name) { |pet| pet.name =~ /oo/ }
# => [
#      #<Pet id: 2, name: "Spook">,
#      #<Pet id: 3, name: "Choo-Choo">
#    ]

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 110
def select(*fields, &block)
  @association.select(*fields, &block)
end

              size()

            Link

Returns the size of the collection. If the collection hasn't been
loaded, it executes a SELECT COUNT(*) query. Else it calls
collection.size.

If the collection has been already loaded size and
length are equivalent. If not and you are going to need the
records anyway length will take one less query. Otherwise
size is more efficient.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets.size # => 3
# executes something like SELECT COUNT(*) FROM "pets" WHERE "pets"."person_id" = 1

person.pets # This will execute a SELECT * FROM query
# => [
#       #<Pet id: 1, name: "Fancy-Fancy", person_id: 1>,
#       #<Pet id: 2, name: "Spook", person_id: 1>,
#       #<Pet id: 3, name: "Choo-Choo", person_id: 1>
#    ]

person.pets.size # => 3
# Because the collection is already loaded, this will behave like
# collection.size and no SQL count query is executed.

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 725
def size
  @association.size
end

              spawn()

            Link

              Alias for: scope

              take(n = nil)

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 230
def take(n = nil)
  @association.take(n)
end

              target()

            Link

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 40
def target
  @association.target
end

              third(*args)

            Link

Same as first except returns only the third record.

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 180
def third(*args)
  @association.third(*args)
end

              to_a()

            Link

              Alias for: to_ary

              to_ary()

            Link

Returns a new array of objects from the collection. If the collection
hasn't been loaded, it fetches the records from the database.

class Person < ActiveRecord::Base
  has_many :pets
end

person.pets
# => [
#       #<Pet id: 4, name: "Benny", person_id: 1>,
#       #<Pet id: 5, name: "Brain", person_id: 1>,
#       #<Pet id: 6, name: "Boss",  person_id: 1>
#    ]

other_pets = person.pets.to_ary
# => [
#       #<Pet id: 4, name: "Benny", person_id: 1>,
#       #<Pet id: 5, name: "Brain", person_id: 1>,
#       #<Pet id: 6, name: "Boss",  person_id: 1>
#    ]

other_pets.replace([Pet.new(name: 'BooGoo')])

other_pets
# => [#<Pet id: nil, name: "BooGoo", person_id: 1>]

person.pets
# This is not affected by replace
# => [
#       #<Pet id: 4, name: "Benny", person_id: 1>,
#       #<Pet id: 5, name: "Brain", person_id: 1>,
#       #<Pet id: 6, name: "Boss",  person_id: 1>
#    ]

              Also aliased as: to_a

                Source:
                show

# File ../../../.rbenv/versions/2.2.1/lib/ruby/gems/2.2.0/gems/activerecord-4.2.1/lib/active_record/associations/collection_proxy.rb, line 943
def to_ary
  load_target.dup
end

              uniq()

            Link

              Alias for: distinct


text:
<?php

namespace SilverStripe\GraphQL\Schema\DataObject\Plugin;

use SilverStripe\Core\ClassInfo;
use SilverStripe\Core\Injector\Injector;
use SilverStripe\GraphQL\Schema\DataObject\DataObjectModel;
use SilverStripe\GraphQL\Schema\DataObject\FieldAccessor;
use SilverStripe\GraphQL\Schema\Exception\SchemaBuilderException;
use SilverStripe\GraphQL\Schema\Field\ModelField;
use SilverStripe\GraphQL\Schema\Interfaces\ModelTypePlugin;
use SilverStripe\GraphQL\Schema\Schema;
use SilverStripe\GraphQL\Schema\Type\Enum;
use SilverStripe\GraphQL\Schema\Type\ModelType;
use SilverStripe\GraphQL\Schema\Type\Type;
use SilverStripe\ORM\FieldType\DBComposite;
use SilverStripe\ORM\FieldType\DBEnum;

class DBFieldTypes implements ModelTypePlugin
{
    const IDENTIFIER = 'dbFieldTypes';

    /**
     * @return string
     */
    public function getIdentifier(): string
    {
        return self::IDENTIFIER;
    }

    /**
     * @param ModelType $type
     * @param Schema $schema
     * @param array $config
     * @throws SchemaBuilderException
     */
    public function apply(ModelType $type, Schema $schema, array $config = []): void
    {
        $ignore = $config['ignore'] ?? [];
        $mapping = $config['enumTypeMapping'] ?? [];
        foreach ($type->getFields() as $field) {
            if ($field instanceof ModelField && $field->getModel() instanceof DataObjectModel) {
                $ignored = $ignore[$field->getName()] ?? null;
                if (!!$ignored) {
                    continue;
                }
                $dataClass = $field->getMetadata()->get('dataClass');
                if (!$dataClass) {
                    continue;
                }
                if ($dataClass === DBEnum::class || is_subclass_of($dataClass, DBEnum::class)) {
                    $customName = $mapping[$type->getName()][$field->getName()] ?? null;
                    $this->applyEnum($type, $field, $schema, $customName);
                } elseif ($dataClass === DBComposite::class || is_subclass_of($dataClass, DBComposite::class)) {
                    $this->applyComposite($field, $schema);
                }
            }
        }
    }

    /**
     * @throws SchemaBuilderException
     */
    private function applyEnum(
        ModelType $type,
        ModelField $field,
        Schema $schema,
        ?string $customName = null
    ): void {
        $sng = Injector::inst()->get($field->getModel()->getSourceClass());
        /* @var DBEnum $enumField */
        $enumField = $sng->dbObject($field->getPropertyName());
        if (!$enumField) {
            return;
        }

        $values = $enumField->enumValues();

        // If another enum exists with the same values, recycle it.
        $hash = md5(json_encode($values) ?? '');
        $enum = null;
        foreach ($schema->getEnums() as $candidate) {
            $candidateHash = md5(json_encode($candidate->getValues()) ?? '');
            if ($candidateHash === $hash) {
                $enum = $candidate;
                break;
            }
        }

        if (!$enum) {
            $enum = Enum::create(
                $customName ?: sprintf('%sEnum', $field->getName()),
                $values
            );

            // Name collision detection. If already exists, prefix with type.
            $enums = $schema->getEnums();
            $existing = $enums[$enum->getName()] ?? null;
            if ($existing) {
                $enum->setName($type->getName() . $enum->getName());
            }

            $schema->addEnum($enum);
        }

        $field->setType($enum->getName());
    }

    /**
     * @throws SchemaBuilderException
     */
    private function applyComposite(ModelField $field, Schema $schema): void
    {
        $sng = Injector::inst()->get($field->getModel()->getSourceClass());
        /* @var DBComposite $compositeField */
        $compositeField = $sng->dbObject($field->getPropertyName());
        if ($compositeField) {
            $name = ClassInfo::shortName(get_class($compositeField)) . 'Composite';
            if (!$schema->getType($name)) {
                $nestedDBFields = $compositeField->compositeDatabaseFields();
                $compositeType = Type::create($name);
                foreach ($nestedDBFields as $nestedFieldName => $nestedFieldType) {
                    $graphqlType = Injector::inst()->get($nestedFieldType)->config()->get('graphql_type');
                    $fieldName = FieldAccessor::formatField($nestedFieldName);
                    $compositeType->addField($fieldName, $graphqlType);
                }
                $schema->addType($compositeType);
            }

            $field->setType($name);
            $field->addResolverAfterware([static::class, 'resolveComposite']);
        }
    }

    /**
     * @param mixed @obj
     * @param array $args
     * @return mixed
     */
    public static function resolveComposite($obj, array $args)
    {
        if ($obj instanceof DBComposite) {
            $result = [];
            foreach ($obj->compositeDatabaseFields() as $fieldName => $type) {
                $result[FieldAccessor::formatField($fieldName)] = $obj->$fieldName;
            }

            return $result;
        }

        return $obj;
    }
}

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#ifndef GEODE_CACHEABLETOKEN_H_
#define GEODE_CACHEABLETOKEN_H_

#include <geode/geode_globals.hpp>
#include <geode/Cacheable.hpp>

namespace apache {
namespace geode {
namespace client {

class CPPCACHE_EXPORT CacheableToken;
typedef SharedPtr<CacheableToken> CacheableTokenPtr;

/** Implement a non-mutable int64_t wrapper that can serve as a distributable
 * key object for cacheing as well as being a 64 bit value. */
class CPPCACHE_EXPORT CacheableToken : public Cacheable {
 private:
  enum TokenType { NOT_USED = 0, INVALID, DESTROYED, OVERFLOWED, TOMBSTONE };

  TokenType m_value;

  static CacheableTokenPtr* invalidToken;
  static CacheableTokenPtr* destroyedToken;
  static CacheableTokenPtr* overflowedToken;
  static CacheableTokenPtr* tombstoneToken;

 public:
  inline static CacheableTokenPtr& invalid() { return *invalidToken; }

  inline static CacheableTokenPtr& destroyed() { return *destroyedToken; }

  inline static CacheableTokenPtr& overflowed() { return *overflowedToken; }
  inline static CacheableTokenPtr& tombstone() { return *tombstoneToken; }
  /**
   *@brief serialize this object
   **/
  virtual void toData(DataOutput& output) const;

  /**
   *@brief deserialize this object
   **/
  virtual Serializable* fromData(DataInput& input);

  /**
   * @brief creation function for strings.
   */
  static Serializable* createDeserializable();

  /**
   *@brief Return the classId of the instance being serialized.
   * This is used by deserialization to determine what instance
   * type to create and deserialize into.
   */
  virtual int32_t classId() const;

  /**
   *@brief return the typeId byte of the instance being serialized.
   * This is used by deserialization to determine what instance
   * type to create and deserialize into.
   */
  virtual int8_t typeId() const;

  virtual ~CacheableToken();

  inline bool isInvalid() { return m_value == INVALID; }

  inline bool isDestroyed() { return m_value == DESTROYED; }

  inline bool isOverflowed() { return m_value == OVERFLOWED; }

  inline bool isTombstone() { return m_value == TOMBSTONE; }

  static bool isToken(const CacheablePtr& ptr) {
    return (*invalidToken == ptr) || (*destroyedToken == ptr) ||
           (*overflowedToken == ptr) || (*tombstoneToken == ptr);
  }

  static bool isInvalid(const CacheablePtr& ptr) {
    return *invalidToken == ptr;
  }

  static bool isDestroyed(const CacheablePtr& ptr) {
    return *destroyedToken == ptr;
  }

  static bool isOverflowed(const CacheablePtr& ptr) {
    return *overflowedToken == ptr;
  }

  static bool isTombstone(const CacheablePtr& ptr) {
    return *tombstoneToken == ptr;
  }
  static void init();

  /**
   * Display this object as 'string', which depend on the implementation in
   * the subclasses. The default implementation renders the classname.
   * This returns constant strings of the form "CacheableToken::INVALID".
   */
  virtual CacheableStringPtr toString() const;

  virtual uint32_t objectSize() const;

 protected:
  CacheableToken(TokenType value);
  CacheableToken();  // used for deserialization.

 private:
  // never implemented.
  void operator=(const CacheableToken& other);
  CacheableToken(const CacheableToken& other);
};
}  // namespace client
}  // namespace geode
}  // namespace apache

#endif  // GEODE_CACHEABLETOKEN_H_


text:
#import <Foundation/Foundation.h>

@interface A : NSObject {

}
@end

@implementation A

-(void) noProblem {
  NSArray *foo = [NSArray arrayWithObjects: @"aaa", @"bbb", nil];
}

-(void) nilInArrayWithObjects {
  NSString *str = nil;

  // nil argument in arrayWithObjects terminates the list of arguments prematurely
  NSArray *foo = [NSArray arrayWithObjects: @"aaa", str, @"bbb", nil];
}

@end

int main() {
  A *a = [A alloc];
  [a noProblem];
  [a nilInArrayWithObjects];
  return 0;
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<!-- Session will expire in 45minutes -->
	<session-config>
		<session-timeout>45</session-timeout>
	</session-config>

	<context-param>
    <param-name>com.sun.faces.numberOfViewsInSession</param-name>
    <param-value>500</param-value>

	</context-param>
	<context-param>
    <param-name>com.sun.faces.numberOfLogicalViews</param-name>
    <param-value>500</param-value>
	</context-param>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/app-config.xml</param-value>
	</context-param>

		<!-- you need a unique webroot key -->
	<context-param>
		<param-name>webAppRootKey</param-name>
		<param-value>webapp.infrafrontier.MeetingTool</param-value>
	</context-param>

	<context-param>
		<param-name>javax.faces.CONFIG_FILES</param-name>
		<param-value>/WEB-INF/faces-config.xml</param-value>
	</context-param>

	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>/WEB-INF/classes/log4j.xml</param-value>
	</context-param>

	<context-param>
      <param-name>baseUrl</param-name>
      <param-value>${baseUrl}</param-value>
   </context-param>

   <context-param>
      <param-name>googleAnalytics</param-name>
      <param-value>${googleAnalytics}</param-value>
   </context-param>

   <context-param>
      <param-name>googleAnalyticsBaseUrl</param-name>
      <param-value>${googleAnalyticsBaseUrl}</param-value>
   </context-param>

	<!-- Just here so the JSF implementation can initialize, *not* used at runtime -->
	<servlet>
		<servlet-name>Faces Servlet</servlet-name>
		<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<!-- Just here so the JSF implementation can initialize -->
	<servlet-mapping>
		<servlet-name>Faces Servlet</servlet-name>
		<url-pattern>*.jsf</url-pattern>
	</servlet-mapping>

	 <context-param>
    	<param-name>javax.faces.PROJECT_STAGE</param-name>
    	<param-value>Development</param-value>
  	</context-param>

	 <context-param>
        <param-name>javax.faces.DEFAULT_SUFFIX</param-name>
        <param-value>.xhtml</param-value>
    </context-param>

	<filter>
		<filter-name>serializeRequestsFilter</filter-name>
		<filter-class>
			de.ieg.infra.filter.SerializeRequestFilter
		</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>serializeRequestsFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<filter>
		<filter-name>springFilter</filter-name>
		<filter-class>
			org.springframework.web.filter.RequestContextFilter
		</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<!-- Loads /WEB-INF/applicationContext.xml and puts reference to it in servlet context.
	Can be accessed with WebApplicationContextUtils.getRequiredWebApplicationContext  -->

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

<!-- Lets you give request or session scopes to beans in applicationContext.xml.
If you don't use these scopes, this listener is not required. But you should probably have this entry commented
out in web.xml just in case you want those scopes later -->
  <listener>
    <listener-class>
      org.springframework.web.context.request.RequestContextListener
    </listener-class>
  </listener>

	<listener>
		<listener-class>uk.ac.ebi.phenotype.util.ContextFinalizer</listener-class>
	</listener>

	<!-- Log4j -->
	<!--  >listener>
		<listener-class>
			org.springframework.web.util.Log4jConfigListener
		</listener-class>
	</listener-->

	<welcome-file-list>
		<welcome-file>/index.jsp</welcome-file>
	</welcome-file-list>

	<error-page>
		<error-code>500</error-code>
		<location>/jsp/error.jsp</location>
	</error-page>

	<!-- >error-page>
    	<exception-type>javax.faces.application.ViewExpiredException</exception-type>
    	<location>/xhtml/infraFrontierEvents.xhtml</location>
	</error-page -->

</web-app>


text:
package test.me.chan.spark2pidgin;

import static org.junit.Assert.*;
import me.chan.spark2pidgin.AppConstants;

import org.junit.Test;

/**
 * Makes sure {@link AppConstants} is initialized properly with
 * <code>app.properties<code>.
 *
 * @author chan
 *
 */
public class AppConstantsTest {

	@Test
	public void test() {
		assertNotNull(AppConstants.OWNER);
	}

}


text:
package sk.tuke.gamedev.iddqd.tukequest.managers;

import sk.tuke.gamedev.iddqd.tukequest.actors.game.FxFlameMaster;
import sk.tuke.gamedev.iddqd.tukequest.actors.game.platforms.Platform;
import sk.tuke.gamedev.iddqd.tukequest.util.Log;
import sk.tuke.gamedev.iddqd.tukequest.visual.HUD;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class ScoreManager {

    private static final int ONE_PLATFORM_SCORE_VALUE = 20;
    private static final int JUMP_COMBO_MULTIPLIER = 5;
    private static final int COMBO_TIMEOUT_SECONDS = 3;
    public static ScoreManager INSTANCE;

    private int platformStreak;
    private int lastPlatformStreak;
    private int jumpingStreak;

    private List<Platform> platformsInCurrentJump = new ArrayList<>();

    private int score;
    private boolean playerIsJumping = false;
    private HUD hud;
    private FxFlameMaster fxFlame;

    public int addScore(int score) {
        if (score < 0) {
            throw new RuntimeException("Attempted to add negative score, this should never happen");
        }
        if (this.fxFlame != null) {
            score *= this.fxFlame.getScoreMultiplier();
        }
        this.score += score;
        updateScoreLabel();
        return score;
    }

    public int getCurrentScore() {
        return score;
    }

    // there are 3 reasons why streak might end:
    // 1. player has jumped only 1 platform (to continue streak, you have to jump 2+ platforms
    // 2. player has fallen to platform below without jumping
    public void notifyPlatformActiveChanged(Platform platform, boolean active) {
        // Player is jumping and reached the platform, so it should be added to the streak
        if (active && playerIsJumping) {
            platformsInCurrentJump.add(platform);
            platformStreak++;
            Log.d(this, "Increasing jump streak to " + platformStreak);
            updateComboLabel();
            return;
        }
        // Player fell down without jumping
//        if (!active && !playerIsJumping) {
//            Log.d(this, "Player FELL!");
//            endStreak();
//            return;
//        }
        // Player didn't manage to land on the platform while jumping, but was above it before
        if (!active) {
            platformsInCurrentJump.remove(platform);
            platformStreak = platformStreak > 0 ? platformStreak - 1 : 0;
            Log.d(this, "Decreasing jump streak down to " + platformStreak);
            updateComboLabel();
            return;
        }

        Log.w(this, "Other reason of active platform change happened!");
    }

    public void notifyJumpStarted() {
        this.playerIsJumping = true;
    }

    public void notifyOnGround() {
        this.playerIsJumping = false;
        if (this.platformStreak < this.lastPlatformStreak) {
            // The streak has ended
            addScoreForJump();
            TaskManager.INSTANCE.removeTimers("comboReset");
        } else if (this.platformStreak == this.lastPlatformStreak) {
            // If player jumps and lands on the same platform, the streak should continue
            Log.d(this, "Player landed on the same or already awarded platform, continuing streak!");
        } else {
            this.lastPlatformStreak = this.platformStreak;
            this.jumpingStreak++;
            TaskManager.INSTANCE.removeTimers("comboReset");
            TaskManager.INSTANCE.scheduleTimer("comboReset", COMBO_TIMEOUT_SECONDS, () -> {
                this.platformStreak--;
                addScoreForJump();
            });
        }
        updateComboLabel();
    }

    private void endStreak() {
        platformsInCurrentJump.clear();
        this.platformStreak = 0;
        this.lastPlatformStreak = 0;
        this.jumpingStreak = 0;
        Log.d(this, "Ending streak");
        updateComboLabel();
    }

    private void addScoreForJump() {
        int multipliedScore = calculateMultipliedScore();
        int actualScore = addScore(multipliedScore);
        Log.i(this,
            "Jump streak " + this.jumpingStreak
                + " added score bonus " + multipliedScore
                + "x" + actualScore / (multipliedScore == 0 ? 1 : multipliedScore)
                + " with " + this.platformStreak
                + " platforms, score is now " + getCurrentScore());
        // Mark all platforms that awarded score
        // Probably obsolete from now on, it makes more sense to let player get awarded again
        //platformsInCurrentJump.forEach(Platform::markAsScoreAwarded);
        endStreak();
    }

    private int calculateMultipliedScore() {
        return calculateMultipliedScore(this.platformStreak);
    }

    private int calculateMultipliedScore(int scoreForPlatformStreak) {
//        int multipliedScore = ONE_PLATFORM_SCORE_VALUE * platformsInCurrentJump.size();
        int multipliedScore = ONE_PLATFORM_SCORE_VALUE * scoreForPlatformStreak;
        for (int i = 0; i < this.jumpingStreak; i++) {
            // First jump is not rewarded
            multipliedScore += i * JUMP_COMBO_MULTIPLIER;
        }
        return multipliedScore < 0 ? 0 : multipliedScore;
    }

    public void setHud(HUD hud) {
        this.hud = hud;
        updateScoreLabel();
        updateComboLabel();
    }

    private void updateScoreLabel() {
        this.hud.setScore(getCurrentScore());
    }

    private void updateComboLabel() {
        if (this.platformStreak == 0) {
            this.hud.setCombo(0, 0, 0, 0);
            return;
        }
        this.hud.setCombo(
            this.platformStreak - 1,
            this.jumpingStreak,
            calculateMultipliedScore(this.platformStreak - 1),
            this.fxFlame != null ? this.fxFlame.getScoreMultiplier() : 1);
    }

    public void registerFxFlame(FxFlameMaster firstFlame) {
        this.fxFlame = firstFlame;
    }

}


text:
using System;
using System.Diagnostics;
using System.Threading;
using Foundatio.Caching;
using Foundatio.Extensions;
using Foundatio.Lock;
using Foundatio.Tests.Utility;
using Xunit;
using Xunit.Abstractions;

namespace Foundatio.Tests {
    public class ThrottlingLockTests : LockTestBase {
        private readonly TimeSpan _period = TimeSpan.FromSeconds(1);

        public ThrottlingLockTests(CaptureFixture fixture, ITestOutputHelper output)
            : base(fixture, output)
        {
        }

        protected override ILockProvider GetLockProvider() {
            return new ThrottlingLockProvider(new InMemoryCacheClient(), 5, _period);
        }

        [Fact]
        public void WillThrottleCalls() {
            var locker = GetLockProvider();
            if (locker == null)
                return;

            // sleep until start of throttling period
            Thread.Sleep(DateTime.Now.Ceiling(_period) - DateTime.Now);
            var sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 5; i++)
                locker.AcquireLock("test");
            sw.Stop();

            _output.WriteLine(sw.Elapsed.ToString());
            Assert.True(sw.Elapsed.TotalSeconds < 1);

            sw.Reset();
            sw.Start();
            var result = locker.AcquireLock("test", acquireTimeout: TimeSpan.Zero);
            sw.Stop();
            Assert.Null(result);
            _output.WriteLine(sw.Elapsed.ToString());

            sw.Reset();
            sw.Start();
            result = locker.AcquireLock("test", acquireTimeout: TimeSpan.FromMilliseconds(250));
            sw.Stop();
            Assert.Null(result);
            _output.WriteLine(sw.Elapsed.ToString());

            sw.Reset();
            sw.Start();
            result = locker.AcquireLock("test", acquireTimeout: TimeSpan.FromSeconds(2));
            sw.Stop();
            Assert.NotNull(result);
            _output.WriteLine(sw.Elapsed.ToString());
        }
    }
}


text:
from tests.compat import mock
import re
import xml.dom.minidom
from boto.exception import BotoServerError
from boto.route53.connection import Route53Connection
from boto.route53.exception import DNSServerError
from boto.route53.healthcheck import HealthCheck
from boto.route53.record import ResourceRecordSets, Record
from boto.route53.zone import Zone

from nose.plugins.attrib import attr
from tests.unit import AWSMockServiceTestCase
from boto.compat import six
urllib = six.moves.urllib

@attr(route53=True)
class TestRoute53Connection(AWSMockServiceTestCase):
    connection_class = Route53Connection

    def setUp(self):
        super(TestRoute53Connection, self).setUp()
        self.calls = {
            'count': 0,
        }

    def default_body(self):
        return b"""<Route53Result>
    <Message>It failed.</Message>
</Route53Result>
"""

    def test_typical_400(self):
        self.set_http_response(status_code=400, header=[
            ['Code', 'AccessDenied'],
        ])

        with self.assertRaises(DNSServerError) as err:
            self.service_connection.get_all_hosted_zones()

        self.assertTrue('It failed.' in str(err.exception))

    def test_retryable_400_prior_request_not_complete(self):
        # Test ability to retry on ``PriorRequestNotComplete``.
        self.set_http_response(status_code=400, body="""<?xml version="1.0"?>
<ErrorResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/"><Error><Type>Sender</Type>PriorRequestNotComplete<Message>The request was rejected because Route 53 was still processing a prior request.</Message></Error><RequestId>12d222a0-f3d9-11e4-a611-c321a3a00f9c</RequestId></ErrorResponse>
""")
        self.do_retry_handler()

    def test_retryable_400_throttling(self):
        # Test ability to rety on ``Throttling``.
        self.set_http_response(status_code=400, body="""<?xml version="1.0"?>
<ErrorResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/"><Error><Type>Sender</Type>Throttling<Message>Rate exceeded</Message></Error><RequestId>19d0a9a0-f3d9-11e4-a611-c321a3a00f9c</RequestId></ErrorResponse>
""")
        self.do_retry_handler()

    @mock.patch('time.sleep')
    def do_retry_handler(self, sleep_mock):

        def incr_retry_handler(func):
            def _wrapper(*args, **kwargs):
                self.calls['count'] += 1
                return func(*args, **kwargs)
            return _wrapper

        # Patch.
        orig_retry = self.service_connection._retry_handler
        self.service_connection._retry_handler = incr_retry_handler(
            orig_retry
        )
        self.assertEqual(self.calls['count'], 0)

        # Retries get exhausted.
        with self.assertRaises(BotoServerError):
            self.service_connection.get_all_hosted_zones()

        self.assertEqual(self.calls['count'], 7)

        # Unpatch.
        self.service_connection._retry_handler = orig_retry

    def test_private_zone_invalid_vpc_400(self):
        self.set_http_response(status_code=400, header=[
            ['Code', 'InvalidVPCId'],
        ])

        with self.assertRaises(DNSServerError) as err:
            self.service_connection.create_hosted_zone("example.com.",
                                                       private_zone=True)
        self.assertTrue('It failed.' in str(err.exception))

@attr(route53=True)
class TestCreateZoneRoute53(AWSMockServiceTestCase):
    connection_class = Route53Connection

    def setUp(self):
        super(TestCreateZoneRoute53, self).setUp()

    def default_body(self):
        return b"""
<CreateHostedZoneResponse xmlns="https://route53.amazonaws.com/doc/2012-02-29/">
    <HostedZone>
        <Id>/hostedzone/Z11111</Id>
        <Name>example.com.</Name>
        <CallerReference>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</CallerReference>
        <Config>
            <Comment></Comment>
            <PrivateZone>false</PrivateZone>
        </Config>
        <ResourceRecordSetCount>2</ResourceRecordSetCount>
    </HostedZone>
    <ChangeInfo>
        <Id>/change/C1111111111111</Id>
        <Status>PENDING</Status>
        <SubmittedAt>2014-02-02T10:19:29.928Z</SubmittedAt>
    </ChangeInfo>
    <DelegationSet>
        <NameServers>
            <NameServer>ns-100.awsdns-01.com</NameServer>
            <NameServer>ns-1000.awsdns-01.co.uk</NameServer>
            <NameServer>ns-1000.awsdns-01.org</NameServer>
            <NameServer>ns-900.awsdns-01.net</NameServer>
        </NameServers>
    </DelegationSet>
</CreateHostedZoneResponse>
        """

    def test_create_zone(self):
        self.set_http_response(status_code=201)
        response = self.service_connection.create_zone("example.com.")

        self.assertTrue(isinstance(response, Zone))
        self.assertEqual(response.id, "Z11111")
        self.assertEqual(response.name, "example.com.")

    def test_create_hosted_zone(self):
        self.set_http_response(status_code=201)
        response = self.service_connection.create_hosted_zone("example.com.",
                                                              "my_ref",
                                                              "a comment")

        self.assertEqual(response['CreateHostedZoneResponse']
                                 ['DelegationSet']['NameServers'],
                                 ['ns-100.awsdns-01.com',
                                  'ns-1000.awsdns-01.co.uk',
                                  'ns-1000.awsdns-01.org',
                                  'ns-900.awsdns-01.net'])

        self.assertEqual(response['CreateHostedZoneResponse']
                                 ['HostedZone']['Config']['PrivateZone'],
                         u'false')

@attr(route53=True)
class TestCreatePrivateZoneRoute53(AWSMockServiceTestCase):
    connection_class = Route53Connection

    def setUp(self):
        super(TestCreatePrivateZoneRoute53, self).setUp()

    def default_body(self):
        return b"""
<CreateHostedZoneResponse xmlns="https://route53.amazonaws.com/doc/2012-02-29/">
    <HostedZone>
        <Id>/hostedzone/Z11111</Id>
        <Name>example.com.</Name>
        <VPC>
           <VPCId>vpc-1a2b3c4d</VPCId>
           <VPCRegion>us-east-1</VPCRegion>
        </VPC>
        <CallerReference>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</CallerReference>
        <Config>
            <Comment></Comment>
            <PrivateZone>true</PrivateZone>
        </Config>
        <ResourceRecordSetCount>2</ResourceRecordSetCount>
    </HostedZone>
    <ChangeInfo>
        <Id>/change/C1111111111111</Id>
        <Status>PENDING</Status>
        <SubmittedAt>2014-02-02T10:19:29.928Z</SubmittedAt>
    </ChangeInfo>
    <DelegationSet>
        <NameServers>
            <NameServer>ns-100.awsdns-01.com</NameServer>
            <NameServer>ns-1000.awsdns-01.co.uk</NameServer>
            <NameServer>ns-1000.awsdns-01.org</NameServer>
            <NameServer>ns-900.awsdns-01.net</NameServer>
        </NameServers>
    </DelegationSet>
</CreateHostedZoneResponse>
        """

    def test_create_private_zone(self):
        self.set_http_response(status_code=201)
        r = self.service_connection.create_hosted_zone("example.com.",
                                                       private_zone=True,
                                                       vpc_id='vpc-1a2b3c4d',
                                                       vpc_region='us-east-1'
                                                       )

        self.assertEqual(r['CreateHostedZoneResponse']['HostedZone']
                          ['Config']['PrivateZone'], u'true')
        self.assertEqual(r['CreateHostedZoneResponse']['HostedZone']
                          ['VPC']['VPCId'], u'vpc-1a2b3c4d')
        self.assertEqual(r['CreateHostedZoneResponse']['HostedZone']
                          ['VPC']['VPCRegion'], u'us-east-1')

@attr(route53=True)
class TestGetZoneRoute53(AWSMockServiceTestCase):
    connection_class = Route53Connection

    def setUp(self):
        super(TestGetZoneRoute53, self).setUp()

    def default_body(self):
        return b"""
<ListHostedZonesResponse xmlns="https://route53.amazonaws.com/doc/2012-02-29/">
    <HostedZones>
        <HostedZone>
            <Id>/hostedzone/Z1111</Id>
            <Name>example2.com.</Name>
            <CallerReference>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</CallerReference>
            <Config/>
            <ResourceRecordSetCount>3</ResourceRecordSetCount>
        </HostedZone>
        <HostedZone>
            <Id>/hostedzone/Z2222</Id>
            <Name>example1.com.</Name>
            <CallerReference>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeef</CallerReference>
            <Config/>
            <ResourceRecordSetCount>6</ResourceRecordSetCount>
        </HostedZone>
        <HostedZone>
            <Id>/hostedzone/Z3333</Id>
            <Name>example.com.</Name>
            <CallerReference>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeeg</CallerReference>
            <Config/>
            <ResourceRecordSetCount>6</ResourceRecordSetCount>
        </HostedZone>
    </HostedZones>
    <IsTruncated>false</IsTruncated>
    <MaxItems>100</MaxItems>
</ListHostedZonesResponse>
        """

    def test_list_zones(self):
        self.set_http_response(status_code=201)
        response = self.service_connection.get_all_hosted_zones()

        domains = ['example2.com.', 'example1.com.', 'example.com.']
        print(response['ListHostedZonesResponse']['HostedZones'][0])
        for d in response['ListHostedZonesResponse']['HostedZones']:
            print("Removing: %s" % d['Name'])
            domains.remove(d['Name'])

        self.assertEqual(domains, [])

    def test_get_zone(self):
        self.set_http_response(status_code=201)
        response = self.service_connection.get_zone('example.com.')

        self.assertTrue(isinstance(response, Zone))
        self.assertEqual(response.name, "example.com.")

@attr(route53=True)
class TestGetHostedZoneRoute53(AWSMockServiceTestCase):
    connection_class = Route53Connection

    def setUp(self):
        super(TestGetHostedZoneRoute53, self).setUp()

    def default_body(self):
        return b"""
<GetHostedZoneResponse xmlns="https://route53.amazonaws.com/doc/2012-02-29/">
    <HostedZone>
        <Id>/hostedzone/Z1111</Id>
        <Name>example.com.</Name>
        <CallerReference>aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee</CallerReference>
        <Config/>
        <ResourceRecordSetCount>3</ResourceRecordSetCount>
    </HostedZone>
    <DelegationSet>
        <NameServers>
            <NameServer>ns-1000.awsdns-40.org</NameServer>
            <NameServer>ns-200.awsdns-30.com</NameServer>
            <NameServer>ns-900.awsdns-50.net</NameServer>
            <NameServer>ns-1000.awsdns-00.co.uk</NameServer>
        </NameServers>
    </DelegationSet>
</GetHostedZoneResponse>
"""

    def test_list_zones(self):
        self.set_http_response(status_code=201)
        response = self.service_connection.get_hosted_zone("Z1111")

        self.assertEqual(response['GetHostedZoneResponse']
                                 ['HostedZone']['Id'],
                         '/hostedzone/Z1111')
        self.assertEqual(response['GetHostedZoneResponse']
                                 ['HostedZone']['Name'],
                         'example.com.')
        self.assertEqual(response['GetHostedZoneResponse']
                                 ['DelegationSet']['NameServers'],
                         ['ns-1000.awsdns-40.org', 'ns-200.awsdns-30.com',
                          'ns-900.awsdns-50.net', 'ns-1000.awsdns-00.co.uk'])

@attr(route53=True)
class TestGetAllRRSetsRoute53(AWSMockServiceTestCase):
    connection_class = Route53Connection

    def setUp(self):
        super(TestGetAllRRSetsRoute53, self).setUp()

    def default_body(self):
        return b"""
<ListResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
    <ResourceRecordSets>
        <ResourceRecordSet>
            <Name>test.example.com.</Name>
            <Type>A</Type>
            <TTL>60</TTL>
            <ResourceRecords>
                <ResourceRecord>
                    <Value>10.0.0.1</Value>
                </ResourceRecord>
            </ResourceRecords>
        </ResourceRecordSet>
        <ResourceRecordSet>
            <Name>www.example.com.</Name>
            <Type>A</Type>
            <TTL>60</TTL>
            <ResourceRecords>
                <ResourceRecord>
                    <Value>10.0.0.2</Value>
                </ResourceRecord>
            </ResourceRecords>
        </ResourceRecordSet>
        <ResourceRecordSet>
            <Name>us-west-2-evaluate-health.example.com.</Name>
            <Type>A</Type>
            <SetIdentifier>latency-example-us-west-2-evaluate-health</SetIdentifier>
            <Region>us-west-2</Region>
            <AliasTarget>
                <HostedZoneId>ABCDEFG123456</HostedZoneId>
                <EvaluateTargetHealth>true</EvaluateTargetHealth>
                <DNSName>example-123456-evaluate-health.us-west-2.elb.amazonaws.com.</DNSName>
            </AliasTarget>
            <HealthCheckId>abcdefgh-abcd-abcd-abcd-abcdefghijkl</HealthCheckId>
        </ResourceRecordSet>
        <ResourceRecordSet>
            <Name>us-west-2-no-evaluate-health.example.com.</Name>
            <Type>A</Type>
            <SetIdentifier>latency-example-us-west-2-no-evaluate-health</SetIdentifier>
            <Region>us-west-2</Region>
            <AliasTarget>
                <HostedZoneId>ABCDEFG567890</HostedZoneId>
                <EvaluateTargetHealth>false</EvaluateTargetHealth>
                <DNSName>example-123456-no-evaluate-health.us-west-2.elb.amazonaws.com.</DNSName>
            </AliasTarget>
            <HealthCheckId>abcdefgh-abcd-abcd-abcd-abcdefghijkl</HealthCheckId>
        </ResourceRecordSet>
        <ResourceRecordSet>
            <Name>failover.example.com.</Name>
            <Type>A</Type>
            <SetIdentifier>failover-primary</SetIdentifier>
            <Failover>PRIMARY</Failover>
            <TTL>60</TTL>
            <ResourceRecords>
                <ResourceRecord>
                    <Value>10.0.0.4</Value>
                </ResourceRecord>
            </ResourceRecords>
        </ResourceRecordSet>
        <ResourceRecordSet>
            <Name>us-west-2-evaluate-health-healthcheck.example.com.</Name>
            <Type>A</Type>
            <SetIdentifier>latency-example-us-west-2-evaluate-health-healthcheck</SetIdentifier>
            <Region>us-west-2</Region>
            <AliasTarget>
                <HostedZoneId>ABCDEFG123456</HostedZoneId>
                <EvaluateTargetHealth>true</EvaluateTargetHealth>
                <DNSName>example-123456-evaluate-health-healthcheck.us-west-2.elb.amazonaws.com.</DNSName>
            </AliasTarget>
            <HealthCheckId>076a32f8-86f7-4c9e-9fa2-c163d5be67d9</HealthCheckId>
        </ResourceRecordSet>
    </ResourceRecordSets>
    <IsTruncated>false</IsTruncated>
    <MaxItems>100</MaxItems>
</ListResourceRecordSetsResponse>
        """

    def test_get_all_rr_sets(self):
        self.set_http_response(status_code=200)
        response = self.service_connection.get_all_rrsets("Z1111",
                                                          "A",
                                                          "example.com.")

        self.assertIn(self.actual_request.path,
                      ("/2013-04-01/hostedzone/Z1111/rrset?type=A&name=example.com.",
                       "/2013-04-01/hostedzone/Z1111/rrset?name=example.com.&type=A"))

        self.assertTrue(isinstance(response, ResourceRecordSets))
        self.assertEqual(response.hosted_zone_id, "Z1111")
        self.assertTrue(isinstance(response[0], Record))

        self.assertTrue(response[0].name, "test.example.com.")
        self.assertTrue(response[0].ttl, "60")
        self.assertTrue(response[0].type, "A")

        evaluate_record = response[2]
        self.assertEqual(evaluate_record.name, 'us-west-2-evaluate-health.example.com.')
        self.assertEqual(evaluate_record.type, 'A')
        self.assertEqual(evaluate_record.identifier, 'latency-example-us-west-2-evaluate-health')
        self.assertEqual(evaluate_record.region, 'us-west-2')
        self.assertEqual(evaluate_record.alias_hosted_zone_id, 'ABCDEFG123456')
        self.assertTrue(evaluate_record.alias_evaluate_target_health)
        self.assertEqual(evaluate_record.alias_dns_name, 'example-123456-evaluate-health.us-west-2.elb.amazonaws.com.')
        evaluate_xml = evaluate_record.to_xml()
        self.assertTrue(evaluate_record.health_check, 'abcdefgh-abcd-abcd-abcd-abcdefghijkl')
        self.assertTrue('<EvaluateTargetHealth>true</EvaluateTargetHealth>' in evaluate_xml)

        no_evaluate_record = response[3]
        self.assertEqual(no_evaluate_record.name, 'us-west-2-no-evaluate-health.example.com.')
        self.assertEqual(no_evaluate_record.type, 'A')
        self.assertEqual(no_evaluate_record.identifier, 'latency-example-us-west-2-no-evaluate-health')
        self.assertEqual(no_evaluate_record.region, 'us-west-2')
        self.assertEqual(no_evaluate_record.alias_hosted_zone_id, 'ABCDEFG567890')
        self.assertFalse(no_evaluate_record.alias_evaluate_target_health)
        self.assertEqual(no_evaluate_record.alias_dns_name, 'example-123456-no-evaluate-health.us-west-2.elb.amazonaws.com.')
        no_evaluate_xml = no_evaluate_record.to_xml()
        self.assertTrue(no_evaluate_record.health_check, 'abcdefgh-abcd-abcd-abcd-abcdefghijkl')
        self.assertTrue('<EvaluateTargetHealth>false</EvaluateTargetHealth>' in no_evaluate_xml)

        failover_record = response[4]
        self.assertEqual(failover_record.name, 'failover.example.com.')
        self.assertEqual(failover_record.type, 'A')
        self.assertEqual(failover_record.identifier, 'failover-primary')
        self.assertEqual(failover_record.failover, 'PRIMARY')
        self.assertEqual(failover_record.ttl, '60')

        healthcheck_record = response[5]
        self.assertEqual(healthcheck_record.health_check, '076a32f8-86f7-4c9e-9fa2-c163d5be67d9')
        self.assertEqual(healthcheck_record.name, 'us-west-2-evaluate-health-healthcheck.example.com.')
        self.assertEqual(healthcheck_record.identifier, 'latency-example-us-west-2-evaluate-health-healthcheck')
        self.assertEqual(healthcheck_record.alias_dns_name, 'example-123456-evaluate-health-healthcheck.us-west-2.elb.amazonaws.com.')

@attr(route53=True)
class TestTruncatedGetAllRRSetsRoute53(AWSMockServiceTestCase):
    connection_class = Route53Connection

    def setUp(self):
        super(TestTruncatedGetAllRRSetsRoute53, self).setUp()

    def default_body(self):
        return b"""
<ListResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
  <ResourceRecordSets>
    <ResourceRecordSet>
      <Name>example.com.</Name>
      <Type>NS</Type>
      <TTL>900</TTL>
      <ResourceRecords>
        <ResourceRecord>
          <Value>ns-91.awsdns-41.co.uk.</Value>
        </ResourceRecord>
        <ResourceRecord>
          <Value>ns-1929.awsdns-93.net.</Value>
        </ResourceRecord>
        <ResourceRecord>
          <Value>ns-12.awsdns-21.org.</Value>
        </ResourceRecord>
        <ResourceRecord>
          <Value>ns-102.awsdns-96.com.</Value>
        </ResourceRecord>
      </ResourceRecords>
    </ResourceRecordSet>
    <ResourceRecordSet>
      <Name>example.com.</Name>
      <Type>SOA</Type>
      <TTL>1800</TTL>
      <ResourceRecords>
        <ResourceRecord>
          <Value>ns-1929.awsdns-93.net. hostmain.awsdns.net. 1 10800 3600 604800 1800</Value>
        </ResourceRecord>
      </ResourceRecords>
    </ResourceRecordSet>
    <ResourceRecordSet>
      <Name>wrr.example.com.</Name>
      <Type>A</Type>
      <SetIdentifier>primary</SetIdentifier>
      <Weight>100</Weight>
      <TTL>300</TTL>
      <ResourceRecords>
        <ResourceRecord><Value>127.0.0.1</Value></ResourceRecord>
      </ResourceRecords>
    </ResourceRecordSet>
  </ResourceRecordSets>
  <IsTruncated>true</IsTruncated>
  <NextRecordName>wrr.example.com.</NextRecordName>
  <NextRecordType>A</NextRecordType>
  <NextRecordIdentifier>secondary</NextRecordIdentifier>
  <MaxItems>3</MaxItems>
</ListResourceRecordSetsResponse>"""

    def paged_body(self):
        return b"""
<ListResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
  <ResourceRecordSets>
    <ResourceRecordSet>
      <Name>wrr.example.com.</Name>
      <Type>A</Type>
      <SetIdentifier>secondary</SetIdentifier>
      <Weight>50</Weight>
      <TTL>300</TTL>
      <ResourceRecords>
        <ResourceRecord><Value>127.0.0.2</Value></ResourceRecord>
      </ResourceRecords>
    </ResourceRecordSet>
  </ResourceRecordSets>
  <IsTruncated>false</IsTruncated>
  <MaxItems>3</MaxItems>
</ListResourceRecordSetsResponse>"""

    def test_get_all_rr_sets(self):
        self.set_http_response(status_code=200)
        response = self.service_connection.get_all_rrsets("Z1111", maxitems=3)

        # made first request
        self.assertEqual(self.actual_request.path, '/2013-04-01/hostedzone/Z1111/rrset?maxitems=3')

        # anticipate a second request when we page it
        self.set_http_response(status_code=200, body=self.paged_body())

        # this should trigger another call to get_all_rrsets
        self.assertEqual(len(list(response)), 4)

        url_parts = urllib.parse.urlparse(self.actual_request.path)
        self.assertEqual(url_parts.path, '/2013-04-01/hostedzone/Z1111/rrset')
        self.assertEqual(urllib.parse.parse_qs(url_parts.query),
                         dict(type=['A'], name=['wrr.example.com.'], identifier=['secondary']))

@attr(route53=True)
class TestCreateHealthCheckRoute53IpAddress(AWSMockServiceTestCase):
    connection_class = Route53Connection

    def setUp(self):
        super(TestCreateHealthCheckRoute53IpAddress, self).setUp()

    def default_body(self):
        return b"""
<CreateHealthCheckResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
   <HealthCheck>
      <Id>34778cf8-e31e-4974-bad0-b108bd1623d3</Id>
      <CallerReference>2fa48c8f-76ef-4253-9874-8bcb2b0d7694</CallerReference>
      <HealthCheckConfig>
         <IPAddress>74.125.228.81</IPAddress>
         <Port>443</Port>
         <Type>HTTPS_STR_MATCH</Type>
         <SearchString>OK</SearchString>
         <ResourcePath>/health_check</ResourcePath>
         <RequestInterval>30</RequestInterval>
         <FailureThreshold>3</FailureThreshold>
      </HealthCheckConfig>
   </HealthCheck>
</CreateHealthCheckResponse>
        """

    def test_create_health_check_ip_address(self):
        self.set_http_response(status_code=201)
        hc = HealthCheck(ip_addr='74.125.228.81', port=443, hc_type='HTTPS_STR_MATCH', resource_path='/health_check', string_match='OK')
        hc_xml = hc.to_xml()
        self.assertFalse('<FullyQualifiedDomainName>' in hc_xml)
        self.assertTrue('<IPAddress>' in hc_xml)

        response = self.service_connection.create_health_check(hc)
        hc_resp = response['CreateHealthCheckResponse']['HealthCheck']['HealthCheckConfig']
        self.assertEqual(hc_resp['IPAddress'], '74.125.228.81')
        self.assertEqual(hc_resp['ResourcePath'], '/health_check')
        self.assertEqual(hc_resp['Type'], 'HTTPS_STR_MATCH')
        self.assertEqual(hc_resp['Port'], '443')
        self.assertEqual(hc_resp['ResourcePath'], '/health_check')
        self.assertEqual(hc_resp['SearchString'], 'OK')
        self.assertEqual(response['CreateHealthCheckResponse']['HealthCheck']['Id'], '34778cf8-e31e-4974-bad0-b108bd1623d3')

@attr(route53=True)
class TestGetCheckerIpRanges(AWSMockServiceTestCase):
    connection_class = Route53Connection

    def default_body(self):
        return b"""
<GetCheckerIpRangesResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
   <CheckerIpRanges>
      <member>54.183.255.128/26</member>
      <member>54.228.16.0/26</member>
      <member>54.232.40.64/26</member>
      <member>177.71.207.128/26</member>
      <member>176.34.159.192/26</member>
   </CheckerIpRanges>
</GetCheckerIpRangesResponse>
        """

    def test_get_checker_ip_ranges(self):
        self.set_http_response(status_code=200)
        response = self.service_connection.get_checker_ip_ranges()
        ip_ranges = response['GetCheckerIpRangesResponse']['CheckerIpRanges']

        self.assertEqual(len(ip_ranges), 5)
        self.assertIn('54.183.255.128/26', ip_ranges)
        self.assertIn('54.228.16.0/26', ip_ranges)
        self.assertIn('54.232.40.64/26', ip_ranges)
        self.assertIn('177.71.207.128/26', ip_ranges)
        self.assertIn('176.34.159.192/26', ip_ranges)

@attr(route53=True)
class TestCreateHealthCheckRoute53FQDN(AWSMockServiceTestCase):
    connection_class = Route53Connection

    def setUp(self):
        super(TestCreateHealthCheckRoute53FQDN, self).setUp()

    def default_body(self):
        return b"""
<CreateHealthCheckResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
   <HealthCheck>
      <Id>f9abfe10-8d2a-4bbd-8f35-796f0f8572f2</Id>
      <CallerReference>3246ac17-b651-4295-a5c8-c132a59693d7</CallerReference>
      <HealthCheckConfig>
         <Port>443</Port>
         <Type>HTTPS</Type>
         <ResourcePath>/health_check</ResourcePath>
         <FullyQualifiedDomainName>example.com</FullyQualifiedDomainName>
         <RequestInterval>30</RequestInterval>
         <FailureThreshold>3</FailureThreshold>
      </HealthCheckConfig>
   </HealthCheck>
</CreateHealthCheckResponse>
        """

    def test_create_health_check_fqdn(self):
        self.set_http_response(status_code=201)
        hc = HealthCheck(ip_addr='', port=443, hc_type='HTTPS', resource_path='/health_check', fqdn='example.com')
        hc_xml = hc.to_xml()
        self.assertTrue('<FullyQualifiedDomainName>' in hc_xml)
        self.assertFalse('<IPAddress>' in hc_xml)

        response = self.service_connection.create_health_check(hc)
        hc_resp = response['CreateHealthCheckResponse']['HealthCheck']['HealthCheckConfig']
        self.assertEqual(hc_resp['FullyQualifiedDomainName'], 'example.com')
        self.assertEqual(hc_resp['ResourcePath'], '/health_check')
        self.assertEqual(hc_resp['Type'], 'HTTPS')
        self.assertEqual(hc_resp['Port'], '443')
        self.assertEqual(hc_resp['ResourcePath'], '/health_check')
        self.assertEqual(response['CreateHealthCheckResponse']['HealthCheck']['Id'], 'f9abfe10-8d2a-4bbd-8f35-796f0f8572f2')

@attr(route53=True)
class TestChangeResourceRecordSetsRoute53(AWSMockServiceTestCase):
    connection_class = Route53Connection

    def setUp(self):
        super(TestChangeResourceRecordSetsRoute53, self).setUp()

    def default_body(self):
        return b"""
<ChangeResourceRecordSetsResponse xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
    <ChangeInfo>
        <Id>/change/C1111111111111</Id>
        <Status>PENDING</Status>
        <SubmittedAt>2014-05-05T10:11:12.123Z</SubmittedAt>
    </ChangeInfo>
</ChangeResourceRecordSetsResponse>
        """

    def test_record_commit(self):
        rrsets = ResourceRecordSets(self.service_connection)
        rrsets.add_change_record('CREATE', Record('vanilla.example.com', 'A', 60, ['1.2.3.4']))
        rrsets.add_change_record('CREATE', Record('alias.example.com', 'AAAA', alias_hosted_zone_id='Z123OTHER', alias_dns_name='target.other', alias_evaluate_target_health=True))
        rrsets.add_change_record('CREATE', Record('wrr.example.com', 'CNAME', 60, ['cname.target'], weight=10, identifier='weight-1'))
        rrsets.add_change_record('CREATE', Record('lbr.example.com', 'TXT', 60, ['text record'], region='us-west-2', identifier='region-1'))
        rrsets.add_change_record('CREATE', Record('failover.example.com', 'A', 60, ['2.2.2.2'], health_check='hc-1234', failover='PRIMARY', identifier='primary'))

        changes_xml = rrsets.to_xml()

        # the whitespacing doesn't match exactly, so we'll pretty print and drop all new lines
        # not the best, but
        actual_xml = re.sub(r"\s*[\r\n]+", "\n", xml.dom.minidom.parseString(changes_xml).toprettyxml())
        expected_xml = re.sub(r"\s*[\r\n]+", "\n", xml.dom.minidom.parseString(b"""
<ChangeResourceRecordSetsRequest xmlns="https://route53.amazonaws.com/doc/2013-04-01/">
    <ChangeBatch>
        <Comment>None</Comment>
        <Changes>
            <Change>
                <Action>CREATE</Action>
                <ResourceRecordSet>
                    <Name>vanilla.example.com</Name>
                    <Type>A</Type>
                    <TTL>60</TTL>
                    <ResourceRecords>
                        <ResourceRecord>
                            <Value>1.2.3.4</Value>
                        </ResourceRecord>
                    </ResourceRecords>
                </ResourceRecordSet>
            </Change>
            <Change>
                <Action>CREATE</Action>
                <ResourceRecordSet>
                    <Name>alias.example.com</Name>
                    <Type>AAAA</Type>
                    <AliasTarget>
                        <HostedZoneId>Z123OTHER</HostedZoneId>
                        <DNSName>target.other</DNSName>
                        <EvaluateTargetHealth>true</EvaluateTargetHealth>
                    </AliasTarget>
                </ResourceRecordSet>
            </Change>
            <Change>
                <Action>CREATE</Action>
                <ResourceRecordSet>
                    <Name>wrr.example.com</Name>
                    <Type>CNAME</Type>
                    <SetIdentifier>weight-1</SetIdentifier>
                    <Weight>10</Weight>
                    <TTL>60</TTL>
                    <ResourceRecords>
                        <ResourceRecord>
                            <Value>cname.target</Value>
                        </ResourceRecord>
                    </ResourceRecords>
                </ResourceRecordSet>
            </Change>
            <Change>
                <Action>CREATE</Action>
                <ResourceRecordSet>
                    <Name>lbr.example.com</Name>
                    <Type>TXT</Type>
                    <SetIdentifier>region-1</SetIdentifier>
                    <Region>us-west-2</Region>
                    <TTL>60</TTL>
                    <ResourceRecords>
                        <ResourceRecord>
                            <Value>text record</Value>
                        </ResourceRecord>
                    </ResourceRecords>
                </ResourceRecordSet>
            </Change>
            <Change>
                <Action>CREATE</Action>
                <ResourceRecordSet>
                    <Name>failover.example.com</Name>
                    <Type>A</Type>
                    <SetIdentifier>primary</SetIdentifier>
                    <Failover>PRIMARY</Failover>
                    <TTL>60</TTL>
                    <ResourceRecords>
                        <ResourceRecord>
                            <Value>2.2.2.2</Value>
                        </ResourceRecord>
                    </ResourceRecords>
                    <HealthCheckId>hc-1234</HealthCheckId>
                </ResourceRecordSet>
            </Change>
        </Changes>
    </ChangeBatch>
</ChangeResourceRecordSetsRequest>
        """).toprettyxml())

        # Note: the alias XML should not include the TTL, even if it's specified in the object model
        self.assertEqual(actual_xml, expected_xml)


text:
<?php

header('Location: http://preview.jsdares.com');