This guide teaches you how to validate the state of objects before they go into the database using Active Record’s validations feature.
After reading this guide, you will know:
Here’s an example of a very simple validation:
class Person < ActiveRecord::Base validates :name, presence: true end Person.create(name: "John Doe").valid? # => true Person.create(name: nil).valid? # => false
As you can see, our validation lets us know that our Person
is not valid
without a name
attribute. The second Person
will not be persisted to the
database.
Before we dig into more details, let’s talk about how validations fit into the big picture of your application.
Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address. Model-level validations are the best way to ensure that only valid data is saved into your database. They are database agnostic, cannot be bypassed by end users, and are convenient to test and maintain. Rails makes them easy to use, provides built-in helpers for common needs, and allows you to create your own validation methods as well.
There are several other ways to validate data before it is saved into your database, including native database constraints, client-side validations, controller-level validations. Here’s a summary of the pros and cons:
Choose these in certain, specific cases. It’s the opinion of the Rails team that model-level validations are the most appropriate in most circumstances.
There are two kinds of Active Record objects: those that correspond to a row
inside your database and those that do not. When you create a fresh object, for
example using the new
method, that object does not belong to the database
yet. Once you call save
upon that object it will be saved into the
appropriate database table. Active Record uses the new_record?
instance
method to determine whether an object is already in the database or not.
Consider the following simple Active Record class:
class Person < ActiveRecord::Base end
We can see how it works by looking at some rails console
output:
$ rails console >> p = Person.new(name: "John Doe") => #<Person id: nil, name: "John Doe", created_at: nil, updated_at: nil> >> p.new_record? => true >> p.save => true >> p.new_record? => false
Creating and saving a new record will send an SQL INSERT
operation to the
database. Updating an existing record will send an SQL UPDATE
operation
instead. Validations are typically run before these commands are sent to the
database. If any validations fail, the object will be marked as invalid and
Active Record will not perform the INSERT
or UPDATE
operation. This avoids
storing an invalid object in the database. You can choose to have specific
validations run when an object is created, saved, or updated.
CAUTION: There are many ways to change the state of an object in the database. Some methods will trigger validations, but some will not. This means that it’s possible to save an object in the database in an invalid state if you aren’t careful.
The following methods trigger validations, and will save the object to the database only if the object is valid:
create
create!
save
save!
update
update!
The bang versions (e.g. save!
) raise an exception if the record is invalid.
The non-bang versions don’t: save
and update
return false
,
create
and update
just return the objects.
The following methods skip validations, and will save the object to the database regardless of its validity. They should be used with caution.
decrement!
decrement_counter
increment!
increment_counter
toggle!
touch
update_all
update_attribute
update_column
update_columns
update_counters
Note that save
also has the ability to skip validations if passed validate:
false
as argument. This technique should be used with caution.
save(validate: false)
valid?
and invalid?
To verify whether or not an object is valid, Rails uses the valid?
method.
You can also use this method on your own. valid?
triggers your validations
and returns true if no errors were found in the object, and false otherwise.
As you saw above:
class Person < ActiveRecord::Base validates :name, presence: true end Person.create(name: "John Doe").valid? # => true Person.create(name: nil).valid? # => false
After Active Record has performed validations, any errors found can be accessed
through the errors
instance method, which returns a collection of errors. By
definition, an object is valid if this collection is empty after running
validations.
Note that an object instantiated with new
will not report errors even if it’s
technically invalid, because validations are not run when using new
.
class Person < ActiveRecord::Base validates :name, presence: true end >> p = Person.new #=> #<Person id: nil, name: nil> >> p.errors #=> {} >> p.valid? #=> false >> p.errors #=> {name:["can't be blank"]} >> p = Person.create #=> #<Person id: nil, name: nil> >> p.errors #=> {name:["can't be blank"]} >> p.save #=> false >> p.save! #=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank >> Person.create! #=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
invalid?
is simply the inverse of valid?
. It triggers your validations,
returning true if any errors were found in the object, and false otherwise.
errors[]
To verify whether or not a particular attribute of an object is valid, you can
use errors[:attribute]
. It returns an array of all the errors for
:attribute
. If there are no errors on the specified attribute, an empty array
is returned.
This method is only useful after validations have been run, because it only
inspects the errors collection and does not trigger validations itself. It’s
different from the ActiveRecord::Base#invalid?
method explained above because
it doesn’t verify the validity of the object as a whole. It only checks to see
whether there are errors found on an individual attribute of the object.
class Person < ActiveRecord::Base validates :name, presence: true end >> Person.new.errors[:name].any? # => false >> Person.create.errors[:name].any? # => true
We’ll cover validation errors in greater depth in the Working with Validation Errors section. For now, let’s turn to the built-in validation helpers that Rails provides by default.
Active Record offers many pre-defined validation helpers that you can use
directly inside your class definitions. These helpers provide common validation
rules. Every time a validation fails, an error message is added to the object’s
errors
collection, and this message is associated with the attribute being
validated.
Each helper accepts an arbitrary number of attribute names, so with a single line of code you can add the same kind of validation to several attributes.
All of them accept the :on
and :message
options, which define when the
validation should be run and what message should be added to the errors
collection if it fails, respectively. The :on
option takes one of the values
:save
(the default), :create
or :update
. There is a default error
message for each one of the validation helpers. These messages are used when
the :message
option isn’t specified. Let’s take a look at each one of the
available helpers.
acceptance
This method validates that a checkbox on the user interface was checked when a form was submitted. This is typically used when the user needs to agree to your application’s terms of service, confirm reading some text, or any similar concept. This validation is very specific to web applications and this ‘acceptance’ does not need to be recorded anywhere in your database (if you don’t have a field for it, the helper will just create a virtual attribute).
class Person < ActiveRecord::Base validates :terms_of_service, acceptance: true end
The default error message for this helper is “must be accepted”.
It can receive an :accept
option, which determines the value that will be
considered acceptance. It defaults to “1” and can be easily changed.
class Person < ActiveRecord::Base validates :terms_of_service, acceptance: { accept: 'yes' } end
validates_associated
You should use this helper when your model has associations with other models
and they also need to be validated. When you try to save your object, valid?
will be called upon each one of the associated objects.
class Library < ActiveRecord::Base has_many :books validates_associated :books end
This validation will work with all of the association types.
CAUTION: Don’t use validates_associated
on both ends of your associations.
They would call each other in an infinite loop.
The default error message for validates_associated
is “is invalid”. Note
that each associated object will contain its own errors
collection; errors do
not bubble up to the calling model.
confirmation
You should use this helper when you have two text fields that should receive exactly the same content. For example, you may want to confirm an email address or a password. This validation creates a virtual attribute whose name is the name of the field that has to be confirmed with “_confirmation” appended.
class Person < ActiveRecord::Base validates :email, confirmation: true end
In your view template you could use something like
<%= text_field :person, :email %> <%= text_field :person, :email_confirmation %>
This check is performed only if email_confirmation
is not nil
. To require
confirmation, make sure to add a presence check for the confirmation attribute
(we’ll take a look at presence
later on this guide):
class Person < ActiveRecord::Base validates :email, confirmation: true validates :email_confirmation, presence: true end
The default error message for this helper is “doesn’t match confirmation”.
exclusion
This helper validates that the attributes’ values are not included in a given set. In fact, this set can be any enumerable object.
class Account < ActiveRecord::Base validates :subdomain, exclusion: { in: %w(www us ca jp), message: "Subdomain %{value} is reserved." } end
The exclusion
helper has an option :in
that receives the set of values that
will not be accepted for the validated attributes. The :in
option has an
alias called :within
that you can use for the same purpose, if you’d like to.
This example uses the :message
option to show how you can include the
attribute’s value.
The default error message is “is reserved”.
format
This helper validates the attributes’ values by testing whether they match a
given regular expression, which is specified using the :with
option.
class Product < ActiveRecord::Base validates :legacy_code, format: { with: /\A[a-zA-Z]+\z/, message: "Only letters allowed" } end
The default error message is “is invalid”.
inclusion
This helper validates that the attributes’ values are included in a given set. In fact, this set can be any enumerable object.
class Coffee < ActiveRecord::Base validates :size, inclusion: { in: %w(small medium large), message: "%{value} is not a valid size" } end
The inclusion
helper has an option :in
that receives the set of values that
will be accepted. The :in
option has an alias called :within
that you can
use for the same purpose, if you’d like to. The previous example uses the
:message
option to show how you can include the attribute’s value.
The default error message for this helper is “is not included in the list”.
length
This helper validates the length of the attributes’ values. It provides a variety of options, so you can specify length constraints in different ways:
class Person < ActiveRecord::Base validates :name, length: { minimum: 2 } validates :bio, length: { maximum: 500 } validates :password, length: { in: 6..20 } validates :registration_number, length: { is: 6 } end
The possible length constraint options are:
:minimum
- The attribute cannot have less than the specified length.:maximum
- The attribute cannot have more than the specified length.:in
(or :within
) - The attribute length must be included in a given
interval. The value for this option must be a range.:is
- The attribute length must be equal to the given value.The default error messages depend on the type of length validation being
performed. You can personalize these messages using the :wrong_length
,
:too_long
, and :too_short
options and %{count}
as a placeholder for the
number corresponding to the length constraint being used. You can still use the
:message
option to specify an error message.
class Person < ActiveRecord::Base validates :bio, length: { maximum: 1000, too_long: "%{count} characters is the maximum allowed" } end
This helper counts characters by default, but you can split the value in a
different way using the :tokenizer
option:
class Essay < ActiveRecord::Base validates :content, length: { minimum: 300, maximum: 400, tokenizer: lambda { |str| str.scan(/\w+/) }, too_short: "must have at least %{count} words", too_long: "must have at most %{count} words" } end
Note that the default error messages are plural (e.g., “is too short (minimum
is %{count} characters)”). For this reason, when :minimum
is 1 you should
provide a personalized message or use presence: true
instead. When
:in
or :within
have a lower limit of 1, you should either provide a
personalized message or call presence
prior to length
.
The size
helper is an alias for length
.
numericality
This helper validates that your attributes have only numeric values. By
default, it will match an optional sign followed by an integral or floating
point number. To specify that only integral numbers are allowed set
:only_integer
to true.
If you set :only_integer
to true
, then it will use the
/\A[+-]?\d+\Z/
regular expression to validate the attribute’s value. Otherwise, it will try to
convert the value to a number using Float
.
WARNING. Note that the regular expression above allows a trailing newline character.
class Player < ActiveRecord::Base validates :points, numericality: true validates :games_played, numericality: { only_integer: true } end
Besides :only_integer
, this helper also accepts the following options to add
constraints to acceptable values:
:greater_than
- Specifies the value must be greater than the supplied
value. The default error message for this option is “must be greater than
%{count}”.:greater_than_or_equal_to
- Specifies the value must be greater than or
equal to the supplied value. The default error message for this option is
“must be greater than or equal to %{count}”.:equal_to
- Specifies the value must be equal to the supplied value. The
default error message for this option is “must be equal to %{count}”.:less_than
- Specifies the value must be less than the supplied value. The
default error message for this option is “must be less than %{count}”.:less_than_or_equal_to
- Specifies the value must be less than or equal the
supplied value. The default error message for this option is “must be less
than or equal to %{count}”.:odd
- Specifies the value must be an odd number if set to true. The
default error message for this option is “must be odd”.:even
- Specifies the value must be an even number if set to true. The
default error message for this option is “must be even”.The default error message is “is not a number”.
presence
This helper validates that the specified attributes are not empty. It uses the
blank?
method to check if the value is either nil
or a blank string, that
is, a string that is either empty or consists of whitespace.
class Person < ActiveRecord::Base validates :name, :login, :email, presence: true end
If you want to be sure that an association is present, you’ll need to test whether the associated object itself is present, and not the foreign key used to map the association.
class LineItem < ActiveRecord::Base belongs_to :order validates :order, presence: true end
In order to validate associated records whose presence is required, you must
specify the :inverse_of
option for the association:
class Order < ActiveRecord::Base has_many :line_items, inverse_of: :order end
If you validate the presence of an object associated via a has_one
or
has_many
relationship, it will check that the object is neither blank?
nor
marked_for_destruction?
.
Since false.blank?
is true, if you want to validate the presence of a boolean
field you should use validates :field_name, inclusion: { in: [true, false] }
.
The default error message is “can’t be empty”.
absence
This helper validates that the specified attributes are absent. It uses the
present?
method to check if the value is not either nil or a blank string, that
is, a string that is either empty or consists of whitespace.
class Person < ActiveRecord::Base validates :name, :login, :email, absence: true end
If you want to be sure that an association is absent, you’ll need to test whether the associated object itself is absent, and not the foreign key used to map the association.
class LineItem < ActiveRecord::Base belongs_to :order validates :order, absence: true end
In order to validate associated records whose absence is required, you must
specify the :inverse_of
option for the association:
class Order < ActiveRecord::Base has_many :line_items, inverse_of: :order end
If you validate the absence of an object associated via a has_one
or
has_many
relationship, it will check that the object is neither present?
nor
marked_for_destruction?
.
Since false.present?
is false, if you want to validate the absence of a boolean
field you should use validates :field_name, exclusion: { in: [true, false] }
.
The default error message is “must be blank”.
uniqueness
This helper validates that the attribute’s value is unique right before the object gets saved. It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create a unique index in your database.
class Account < ActiveRecord::Base validates :email, uniqueness: true end
The validation happens by performing an SQL query into the model’s table, searching for an existing record with the same value in that attribute.
There is a :scope
option that you can use to specify other attributes that
are used to limit the uniqueness check:
class Holiday < ActiveRecord::Base validates :name, uniqueness: { scope: :year, message: "should happen once per year" } end
There is also a :case_sensitive
option that you can use to define whether the
uniqueness constraint will be case sensitive or not. This option defaults to
true.
class Person < ActiveRecord::Base validates :name, uniqueness: { case_sensitive: false } end
WARNING. Note that some databases are configured to perform case-insensitive searches anyway.
The default error message is “has already been taken”.
validates_with
This helper passes the record to a separate class for validation.
class Person < ActiveRecord::Base validates_with GoodnessValidator end class GoodnessValidator < ActiveModel::Validator def validate(record) if record.first_name == "Evil" record.errors[:base] << "This person is evil" end end end
NOTE: Errors added to record.errors[:base]
relate to the state of the record
as a whole, and not to a specific attribute.
The validates_with
helper takes a class, or a list of classes to use for
validation. There is no default error message for validates_with
. You must
manually add errors to the record’s errors collection in the validator class.
To implement the validate method, you must have a record
parameter defined,
which is the record to be validated.
Like all other validations, validates_with
takes the :if
, :unless
and
:on
options. If you pass any other options, it will send those options to the
validator class as options
:
class Person < ActiveRecord::Base validates_with GoodnessValidator, fields: [:first_name, :last_name] end class GoodnessValidator < ActiveModel::Validator def validate(record) if options[:fields].any?{|field| record.send(field) == "Evil" } record.errors[:base] << "This person is evil" end end end
Note that the validator will be initialized only once for the whole application life cycle, and not on each validation run, so be careful about using instance variables inside it.
If your validator is complex enough that you want instance variables, you can easily use a plain old Ruby object instead:
class Person < ActiveRecord::Base validate do |person| GoodnessValidator.new(person).validate end end class GoodnessValidator def initialize(person) @person = person end def validate if some_complex_condition_involving_ivars_and_private_methods? @person.errors[:base] << "This person is evil" end end # … end
validates_each
This helper validates attributes against a block. It doesn’t have a predefined
validation function. You should create one using a block, and every attribute
passed to validates_each
will be tested against it. In the following example,
we don’t want names and surnames to begin with lower case.
class Person < ActiveRecord::Base validates_each :name, :surname do |record, attr, value| record.errors.add(attr, 'must start with upper case') if value =~ /\A[a-z]/ end end
The block receives the record, the attribute’s name and the attribute’s value. You can do anything you like to check for valid data within the block. If your validation fails, you should add an error message to the model, therefore making it invalid.
These are common validation options:
:allow_nil
The :allow_nil
option skips the validation when the value being validated is
nil
.
class Coffee < ActiveRecord::Base validates :size, inclusion: { in: %w(small medium large), message: "%{value} is not a valid size" }, allow_nil: true end
:allow_blank
The :allow_blank
option is similar to the :allow_nil
option. This option
will let validation pass if the attribute’s value is blank?
, like nil
or an
empty string for example.
class Topic < ActiveRecord::Base validates :title, length: { is: 5 }, allow_blank: true end Topic.create("title" => "").valid? # => true Topic.create("title" => nil).valid? # => true
:message
As you’ve already seen, the :message
option lets you specify the message that
will be added to the errors
collection when validation fails. When this
option is not used, Active Record will use the respective default error message
for each validation helper.
:on
The :on
option lets you specify when the validation should happen. The
default behavior for all the built-in validation helpers is to be run on save
(both when you’re creating a new record and when you’re updating it). If you
want to change it, you can use on: :create
to run the validation only when a
new record is created or on: :update
to run the validation only when a record
is updated.
class Person < ActiveRecord::Base # it will be possible to update email with a duplicated value validates :email, uniqueness: true, on: :create # it will be possible to create the record with a non-numerical age validates :age, numericality: true, on: :update # the default (validates on both create and update) validates :name, presence: true, on: :save end
The last line is in review state and as of now, it is not running in any version of Rails 3.2.x as discussed in this issue
You can also specify validations to be strict and raise
ActiveModel::StrictValidationFailed
when the object is invalid.
class Person < ActiveRecord::Base validates :name, presence: { strict: true } end Person.new.valid? # => ActiveModel::StrictValidationFailed: Name can't be blank
There is also an ability to pass custom exception to :strict
option
class Person < ActiveRecord::Base validates :token, presence: true, uniqueness: true, strict: TokenGenerationException end Person.new.valid? # => TokenGenerationException: Token can't be blank
Sometimes it will make sense to validate an object only when a given predicate
is satisfied. You can do that by using the :if
and :unless
options, which
can take a symbol, a string, a Proc
or an Array
. You may use the :if
option when you want to specify when the validation should happen. If you
want to specify when the validation should not happen, then you may use the
:unless
option.
:if
and :unless
You can associate the :if
and :unless
options with a symbol corresponding
to the name of a method that will get called right before validation happens.
This is the most commonly used option.
class Order < ActiveRecord::Base validates :card_number, presence: true, if: :paid_with_card? def paid_with_card? payment_type == "card" end end
:if
and :unless
You can also use a string that will be evaluated using eval
and needs to
contain valid Ruby code. You should use this option only when the string
represents a really short condition.
class Person < ActiveRecord::Base validates :surname, presence: true, if: "name.nil?" end
:if
and :unless
Finally, it’s possible to associate :if
and :unless
with a Proc
object
which will be called. Using a Proc
object gives you the ability to write an
inline condition instead of a separate method. This option is best suited for
one-liners.
class Account < ActiveRecord::Base validates :password, confirmation: true, unless: Proc.new { |a| a.password.blank? } end
Sometimes it is useful to have multiple validations use one condition, it can
be easily achieved using with_options
.
class User < ActiveRecord::Base with_options if: :is_admin? do |admin| admin.validates :password, length: { minimum: 10 } admin.validates :email, presence: true end end
All validations inside of with_options
block will have automatically passed
the condition if: :is_admin?
On the other hand, when multiple conditions define whether or not a validation
should happen, an Array
can be used. Moreover, you can apply both :if
and
:unless
to the same validation.
class Computer < ActiveRecord::Base validates :mouse, presence: true, if: ["market.retail?", :desktop?] unless: Proc.new { |c| c.trackpad.present? } end
The validation only runs when all the :if
conditions and none of the
:unless
conditions are evaluated to true
.
When the built-in validation helpers are not enough for your needs, you can write your own validators or validation methods as you prefer.
Custom validators are classes that extend ActiveModel::Validator
. These
classes must implement a validate
method which takes a record as an argument
and performs the validation on it. The custom validator is called using the
validates_with
method.
class MyValidator < ActiveModel::Validator def validate(record) unless record.name.starts_with? 'X' record.errors[:name] << 'Need a name starting with X please!' end end end class Person include ActiveModel::Validations validates_with MyValidator end
The easiest way to add custom validators for validating individual attributes
is with the convenient ActiveModel::EachValidator
. In this case, the custom
validator class must implement a validate_each
method which takes three
arguments: record, attribute and value which correspond to the instance, the
attribute to be validated and the value of the attribute in the passed
instance.
class EmailValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i record.errors[attribute] << (options[:message] || "is not an email") end end end class Person < ActiveRecord::Base validates :email, presence: true, email: true end
As shown in the example, you can also combine standard validations with your own custom validators.
You can also create methods that verify the state of your models and add
messages to the errors
collection when they are invalid. You must then
register these methods by using the validate
class method, passing in the
symbols for the validation methods’ names.
You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered.
class Invoice < ActiveRecord::Base validate :expiration_date_cannot_be_in_the_past, :discount_cannot_be_greater_than_total_value def expiration_date_cannot_be_in_the_past if expiration_date.present? && expiration_date < Date.today errors.add(:expiration_date, "can't be in the past") end end def discount_cannot_be_greater_than_total_value if discount > total_value errors.add(:discount, "can't be greater than total value") end end end
By default such validations will run every time you call valid?
. It is also
possible to control when to run these custom validations by giving an :on
option to the validate
method, with either: :create
or :update
.
class Invoice < ActiveRecord::Base validate :active_customer, on: :create def active_customer errors.add(:customer_id, "is not active") unless customer.active? end end
In addition to the valid?
and invalid?
methods covered earlier, Rails provides a number of methods for working with the errors
collection and inquiring about the validity of objects.
The following is a list of the most commonly used methods. Please refer to the ActiveModel::Errors
documentation for a list of all the available methods.
errors
Returns an instance of the class ActiveModel::Errors
containing all errors. Each key is the attribute name and the value is an array of strings with all errors.
class Person < ActiveRecord::Base validates :name, presence: true, length: { minimum: 3 } end person = Person.new person.valid? # => false person.errors # => {:name=>["can't be blank", "is too short (minimum is 3 characters)"]} person = Person.new(name: "John Doe") person.valid? # => true person.errors # => []
errors[]
errors[]
is used when you want to check the error messages for a specific attribute. It returns an array of strings with all error messages for the given attribute, each string with one error message. If there are no errors related to the attribute, it returns an empty array.
class Person < ActiveRecord::Base validates :name, presence: true, length: { minimum: 3 } end person = Person.new(name: "John Doe") person.valid? # => true person.errors[:name] # => [] person = Person.new(name: "JD") person.valid? # => false person.errors[:name] # => ["is too short (minimum is 3 characters)"] person = Person.new person.valid? # => false person.errors[:name] # => ["can't be blank", "is too short (minimum is 3 characters)"]
errors.add
The add
method lets you manually add messages that are related to particular attributes. You can use the errors.full_messages
or errors.to_a
methods to view the messages in the form they might be displayed to a user. Those particular messages get the attribute name prepended (and capitalized). add
receives the name of the attribute you want to add the message to, and the message itself.
class Person < ActiveRecord::Base def a_method_used_for_validation_purposes errors.add(:name, "cannot contain the characters !@#%*()_-+=") end end person = Person.create(name: "!@#") person.errors[:name] # => ["cannot contain the characters !@#%*()_-+="] person.errors.full_messages # => ["Name cannot contain the characters !@#%*()_-+="]
Another way to do this is using []=
setter
class Person < ActiveRecord::Base def a_method_used_for_validation_purposes errors[:name] = "cannot contain the characters !@#%*()_-+=" end end person = Person.create(name: "!@#") person.errors[:name] # => ["cannot contain the characters !@#%*()_-+="] person.errors.to_a # => ["Name cannot contain the characters !@#%*()_-+="]
errors[:base]
You can add error messages that are related to the object’s state as a whole, instead of being related to a specific attribute. You can use this method when you want to say that the object is invalid, no matter the values of its attributes. Since errors[:base]
is an array, you can simply add a string to it and it will be used as an error message.
class Person < ActiveRecord::Base def a_method_used_for_validation_purposes errors[:base] << "This person is invalid because ..." end end
errors.clear
The clear
method is used when you intentionally want to clear all the messages in the errors
collection. Of course, calling errors.clear
upon an invalid object won’t actually make it valid: the errors
collection will now be empty, but the next time you call valid?
or any method that tries to save this object to the database, the validations will run again. If any of the validations fail, the errors
collection will be filled again.
class Person < ActiveRecord::Base validates :name, presence: true, length: { minimum: 3 } end person = Person.new person.valid? # => false person.errors[:name] # => ["can't be blank", "is too short (minimum is 3 characters)"] person.errors.clear person.errors.empty? # => true p.save # => false p.errors[:name] # => ["can't be blank", "is too short (minimum is 3 characters)"]
errors.size
The size
method returns the total number of error messages for the object.
class Person < ActiveRecord::Base validates :name, presence: true, length: { minimum: 3 } end person = Person.new person.valid? # => false person.errors.size # => 2 person = Person.new(name: "Andrea", email<EMAIL_ADDRESS>person.valid? # => true person.errors.size # => 0
Once you’ve created a model and added validations, if that model is created via a web form, you probably want to display an error message when one of the validations fail.
Because every application handles this kind of thing differently, Rails does
not include any view helpers to help you generate these messages directly.
However, due to the rich number of methods Rails gives you to interact with
validations in general, it’s fairly easy to build your own. In addition, when
generating a scaffold, Rails will put some ERB into the _form.html.erb
that
it generates that displays the full list of errors on that model.
Assuming we have a model that’s been saved in an instance variable named
@post
, it looks like this:
<% if @post.errors.any? %> <div id="error_explanation"> <h2><%=<EMAIL_ADDRESS>"error") %> prohibited this post from being saved:</h2> <ul> <% @post.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %>
Furthermore, if you use the Rails form helpers to generate your forms, when
a validation error occurs on a field, it will generate an extra <div>
around
the entry.
<div class="field_with_errors">
<input id="post_title" name="post[title]" size="30" type="text" value="">
</div>
You can then style this div however you’d like. The default scaffold that Rails generates, for example, adds this CSS rule:
.field_with_errors {
padding: 2px;
background-color: red;
display: table;
}
This means that any field with an error ends up with a 2 pixel red border.


--- layout: archive title: Zulip Chat Archive permalink: /stream/113488-general/topic/of_as_true.20proofs.html ---
I'm trying to build up a mental model of the efficiency of using decidable predicates to construct proofs in tactics..
Let's say I have a decidable predicate P : nat -> Prop
with an instance h : decidable_pred P
, and a concrete value x : nat
in a tactic.
I can match on h x
within the tactic monad (which I think is using the VM), and see if the prop is true or false.
However, I'd also like to have an expression for the proof of P x
. I seem to be able to do that via an expression like @of_as_true _ (h x) trivial
, but I think this results in the elaborator needing to reduce h x
to whnf. I think of this as slower than the VM, since among other things nat will have a unary representation.
Is the above correct, and is so is there some way like reflection to have the VM (or the compiler in Lean 4) run h x
and efficiently construct the needed proof?
No, you can't directly produce a "fast" kernel proof from a "fast" VM function. For many common operations on nat
, norm_num
will produce efficient kernel proofs using VM evaluation to guide the construction, but the method is generally completely different than what the decidable instance does
Good to know I'm not missing something. I think it would be useful to have some way to write a verified decision procedure in logic mode, and then be able to use it to discharge proof obligations in tactic mode.
For similar reasons, I started down the path of building up has_reflect
instances for datatypes in proofs (e.g., has_reflect (and P Q)
), but it's (1) a lot of work, and (2) still unclear how to support for some properties. Specifically, I have decidable (\forall (x : fin n), P x)
, but I'm struck on has_reflect (\forall (x : fin n), P x)
.
hm, that's an interesting use of has_reflect
. Usually we don't use has_reflect
for propositions, what's the goal here?
I think what you want is actually decidable
, or at least semidecidable
(where semidecidable p
is basically option p
)
but you are limited by the same things as decidable
proofs
The idea for that use was to get the VM to produce the proof object using the decidable instance, then call has_reflect.reflect
to construct the appropriate expression.
decidable instances don't have proof objects
they put all the computation in the kernel
I'm referring to the proof object p
that is the argument to decidable.is_true p
You could infer decidable p
, normalize it to is_true h
and return h
, but this is going to be almost as slow as kernel computing it
you are "elaborator computing" it in this case
I think I haven't been clear. I use the tactic decidable_tac
below that uses uses the elaborator fairly often. As a work around to get more use of the VM, I was hoping to be able to use both decidable
and has_reflect
instances to get something a bit more efficient in the decidable_reflected
tactic below:
meta def decidable_tac : tactic unit := do tgt ← tactic.target, tactic.apply ((`(@of_as_true) : expr) tgt), tactic.exact `(trivial) meta def decidable_reflected (P:Prop) [h:decidable P] [g:has_reflect P] : tactic unit := do match h with | decidable.is_true p := tactic.exact (g p) | decidable.is_false q := tactic.fail "Prop false" end
Unfortunately, I can't actually write the necessary has_reflect
instances. It seems like I would need some more support within Lean (perhaps constants that auto generated reflect instances for propositions).
You can't write has_reflect
instances for many propositions
like or
A has_reflect
instance is a function that produces an expression that is a proof of p
, provided p
is in fact true
So decidable p
implies has_reflect p
because you can evaluate the decidable instance and take the proof out
Yep, I got and
and true
and thought this would work, then got stuck with forall. I tried or
while writing up the example, and got the error about only being able to return a value of type P
.
If you know one or the other of the propositions is decidable, you can reflect an or
but really decidable is the one you want, it's closed under all the operations
Here was my attempt at or
, but I can't match on the or value due to proof irrelevance:
meta instance or.reflect (P Q : Prop) [reflected P] [reflected Q] [hp:has_reflect P] [hq:reflected Q] : has_reflect (P ∨ Q) | (or.inl p) := `(or.inl).subst (hp p) | (or.inr q) := `(or.inr).subst (hq q)
exactly
In a tactic, a proof value isn't very useful. It's only going to help avoid some code paths that weren't going to be exercised anyway
Interesting and
did not complain even though it looks like it recurses:
meta instance and.reflect (P Q : Prop) [reflected P] [reflected Q] [hp:has_reflect P] [hq:has_reflect Q] : has_reflect (P ∧ Q) | ⟨p,q⟩ := (`(and.intro).subst (hp p)).subst (hq q)
and
has large elimination because it only has one constructor
The proof value is needed just so I can discharge theorems I'm proving.
so if you have a function p -> expr
coming from your has reflect instance, you could just as well have a function producing option expr
with no proof preconditions
So when you are writing a has_reflect instance you are just constructing a proof from nothing. Sometimes that's easy, like and
, sometimes that requires backtracking like or
, and sometimes it's really hard
How are you supposed to use decidable_reflected
?
nothing says what P
is
it seems like it's mixing meta levels, and that's why you need has_reflect
decidable_tac
is the same as exact_dec_trivial
afaict
Let me work on an example. Is exact_dec_trivial
in Lean standard library or mathlib?
It's in mathlib, but it's literally exact dec_trivial
which is core only
I forget why I didn't just use exact dec_trivial
-- I may not have known about it, I've used that tactic for a while now.
note that dec_trivial
is notation for of_as_true (by trivial)
; the tactic is there I think to stage the elaboration
Okay, so I think I understand now what you are trying to do. You need a combination of decidable
and has_reflect
that produces exprs rather than proof values. You can automatically construct one by reflecting a decidable instance, but you can also produce much smarter proofs for nats and such
That's right. I want proof search to run within the VM (or compiler in Lean 4), then either I can reflect on the generated proof, or maybe just have some magic constant that pretends to do it for me (say a safe version of sorry
).
(edit, apparently I can't spell)
@Joe Hendrix Here's an example of what I mean. Unfortunately I had to fight lean somewhat to write the instance, possibly the ergonomics of instance writing needs work.
@[class] meta inductive reflect_decidable (p : Prop) | is_true (h : p) : /-reflected h-/ expr → reflect_decidable | is_false (h : ¬ p) : /-reflected h-/ expr → reflect_decidable open reflect_decidable meta instance {p q : Prop} [reflected p] [reflected q] : ∀ [reflect_decidable p] [reflect_decidable q], reflect_decidable (p ∨ q) | (is_true h e) _ := is_true (or.inl h) (expr.app<EMAIL_ADDRESS>p q) e) | _ (is_true h e) := is_true (or.inr h) (expr.app<EMAIL_ADDRESS>p q) e) | (is_false h₁ e₁) (is_false h₂ e₂) := is_false (not_or h₁ h₂) (expr.mk_app `(@not_or p q) [e₁, e₂]) meta instance : reflect_decidable true := is_true trivial `(trivial) open tactic meta def by_reflection : tactic unit := do tgt ← target, let ty := `(reflect_decidable %%tgt), inst ← mk_instance ty, is_true _ e ← @tactic.eval_expr (reflect_decidable true) (by delta reflected; exact ty) inst, exact e def ex : true ∨ true := by by_reflection #print ex -- or.inl trivial
That would kind of work. One downside is that reflect_decidable
is meta. I'm interested in trying to write provably correct decision procedures, not just proof producing. I'll try this approach in the short term though.
it has to be meta, because it's creating expr
s
this is a limitation of lean 3 tactic framework
You could create objects that are like expr
but not meta, and then post process at the end, but that would add some extra overhead
Last updated: Apr 24 2020 at 19:02 UTC


CS109A Introduction to Data Science
Standard Section 5: Logistic Regression, Multiple Logistic Regression, and KNN-classification¶
Harvard University
Fall 2019
Instructors: Pavlos Protopapas, Kevin Rader, and Chris Tanner
Section Leaders: Marios Mattheakis, Abhimanyu (Abhi) Vasishth, Robbert (Rob) Struyven
In this section we will be covering Linear Regression, KNN-Classification, and Logistic Regression on the famous iris dataset.
Specifically, we will:
- Import data and data exploration.
- Fit a linear regression model for classification, understand drawbacks, and interpret results.
- Fit a simple logistic regression model for classification, compare performance, and interpret results.
- Visualize Predictions and Decision boundaries.
- Fit a higher order polynomial logistic regression model for classification, compare performance, plot decision boundaries, and interpret results.
- Fit a higher order polynomial logistic regression model for classification with different regularization parameters C ( [10000, 100, 1] )
- Optional: Fit a KNN-classification model for classification, plot decision boundaries, and interpret results.
- Optional Homework Tip: Pipeline building to sequentially apply a list of transforms (e.g. scaling, polynomial feature creation) and a final estimator.
For this section we will be using the following packages:
# Data and Stats packages
import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.api import OLS
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import LinearRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
# Visualization packages
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
# Aesthetic settings
from IPython.display import display
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 500)
import warnings
warnings.filterwarnings("ignore")
1. Import data and data exploration.¶
dataset = datasets.load_iris()
dataset.keys()
What our the target and features?¶
print(dataset.target_names)
print(dataset.feature_names)
As we can see, the response variable (y) is the flower type, it has 3 classes:
- setosa
- versicolor
- virginica
The 4 predictor variables are flower characteristics (x):
- 'sepal length (cm)'
- 'sepal width (cm)'
- 'petal length (cm)'
- 'petal width (cm)'
X = pd.DataFrame(data=dataset.data, columns=dataset.feature_names)
y = pd.DataFrame(data=dataset.target, columns=['species'])
print(X.shape)
print(y.shape)
display(X.head())
display(X.describe())
display(y.head())
display(y.describe())
Explore Data¶
Check which variables have high correlations and distinctive patterns with the response.
Any patterns worth mentioning?
full_df = pd.concat([X,y], axis=1)
full_df.head()
sns.pairplot(full_df)
plt.show()
Are the features sepal/petal length and width uniformally distributed or do you observe some clusters of data points?
What do you expect? Let's add color according to our response variable: 'species' = flower species.
sns.pairplot(full_df, hue='species')
plt.show()
Some features like 'petal length' and 'petal width' do have very high correlations and distinctive patterns with the response variable 'flower species'. When we would use these features for predicting the flower species, the classification wouldn't be very difficult. Certain ranges of 'petal length' and 'petal width' are very much correlated with a specific flower species and they are almost seperating our classes perfectly.
Just for illustration purposes we will continue to use only 'sepal width (cm)' and 'sepal length (cm)'. We are making the problem harder for ourselves by only using 'weaker' or less-discriminative features.
X = X[['sepal width (cm)', 'sepal length (cm)']]
Train-Test Split¶
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
print(X_train.shape)
print(y_train.shape)
print(X_test.shape)
print(y_test.shape)
2. Fit a linear regression model for classification, understand drawbacks, and interpret results.¶
model_linear_sklearn = LinearRegression()
#Add constant to x_train and x_test
X_train_cst = sm.add_constant(X_train)
X_test_cst = sm.add_constant(X_test)
#Training
model_linear_sklearn.fit(X_train_cst, y_train)
#Predict
y_pred_train = model_linear_sklearn.predict(X_train_cst)
y_pred_test = model_linear_sklearn.predict(X_test_cst)
#Performance Evaluation
train_score = accuracy_score(y_train, y_pred_train)*100
test_score = accuracy_score(y_test, y_pred_test)*100
print("Training Set Accuracy:",str(train_score)+'%')
print("Testing Set Accuracy:",str(test_score)+'%')
Why do we get this error? Something is wrong with y_train and y_pred_train...
y_train[:5]
y_pred_train[:5]
The fact that our linear regression is outputting continuous predicstions is one of the major drawbacks of linear regression for classification. We can solve this in two manners:
- simply rounding our prediction by using
np.round())
and converting it to an int data type with.astype(int)
- or use a modified algorithm that has bounded outputs (more about Logistic Regression later)
np.round(y_pred_train[:5])
np.round(y_pred_train[:5]).astype(int)
model_linear_sklearn = LinearRegression()
#Add constant to x_train and x_test
X_train_cst = sm.add_constant(X_train)
X_test_cst = sm.add_constant(X_test)
#Training
model_linear_sklearn.fit(X_train_cst, y_train)
#Predict
y_pred_train = np.round(model_linear_sklearn.predict(X_train_cst)).astype(int)
y_pred_test = np.round(model_linear_sklearn.predict(X_test_cst)).astype(int)
#Performance Evaluation
train_score = accuracy_score(y_train, y_pred_train)*100
test_score = accuracy_score(y_test, y_pred_test)*100
print("Training Set Accuracy:",str(train_score)+'%')
print("Testing Set Accuracy:",str(test_score)+'%')
Get Performance by Class (Lookup Confusion Matrix)¶
- Each row of the matrix represents the instances in an actual class
- Each column represents the instances in a predicted class (or vice versa)
- The name stems from the fact that it makes it easy to see if the system is confusing two classes (i.e. commonly mislabeling one as another).
confusion_matrix_linear = pd.crosstab( y_test.values.flatten(),
y_pred_test.flatten(),
rownames=['Actual Class'],
colnames=['Predicted Class'])
display(confusion_matrix_linear)
How many classes do we have in our y_test and in our y_pred_test? Why do we have 4 different predicted classes?
Can we use Linear Regression for classification?
Four Assumptions of Linear Regression:
- Linearity: Our dependent variable Y is a linear combination of the explanatory variables X (and the error terms)
- Observations are independent of one another
- I.I.D error terms that are Normally Distributed ~ $N(0,\sigma^2)$
- Design matrix X is Full Rank.
Suppose we have a binary outcome variable. Can we use Linear Regression?
Then we will have the following problems:
- The error terms are heteroskedastic
- $\epsilon$ is not normally distributed because Y takes on only two values
- The predicted probabilities can be greater than 1 or less than 0
Datasets where linear regression is problematic:
- Binary response data where there are only two outcomes (yes/no, 0/1, etc.)
- Categorical or Ordinal Data of any type, where the outcome is one of a number of discrete (possibly ordered) classes
- Count data in which the outcome is restricted to non-negative integers.
- Continuous data in which the noise is not normally distributed
Generalized Linear Models (GLMs), of which Logistic regression is a specific type, to the resque: Logistic regression is most useful for binary response and categorical data.
3. Fit a simple logistic regression model for classification, compare performance, plot decision boundaries, and interpret results.¶
The logistic regression formula:
$$\hat{p}= \dfrac{e^{w^T x}}{1+e^{w^T x}}$$This is equivalent to:
$$\hat{p}= \dfrac{1}{1+e^{-w^T x}}$$#Training
model_logistic = LogisticRegression(C=100).fit(X_train_cst, y_train)
#Predict
y_pred_train = model_logistic.predict(X_train_cst)
y_pred_test = model_logistic.predict(X_test_cst)
#Performance Evaluation
train_score = accuracy_score(y_train, y_pred_train)*100
test_score = accuracy_score(y_test, y_pred_test)*100
print("Training Set Accuracy:",str(train_score)+'%')
print("Testing Set Accuracy:",str(test_score)+'%')
Let's compare logistic regression against linear regression predictions¶
- We fix X_train['sepal width (cm)'] to its mean value.
- ```x_1 = X_train['sepal width (cm)']````
x_1_range = np.ones_like(x_2_range)*x_1.mean()
- We varie X_train['sepal length (cm)'] from its minimum to its maximum and look how the predicted class evolves.
x_2 = X_train['sepal length (cm)']
x_2_min, x_2_max = x_2.min(), x_2.max()+0.3
x_2_range = np.arange(x_2_min, x_2_max, 0.003)
# Making our input features (x_2 varying, x_1 constat = mean of x_1)
x_1 = X_train['sepal width (cm)']
x_2 = X_train['sepal length (cm)']
x_2_min, x_2_max = x_2.min()-0.1, x_2.max()+0.3
x_2_range = np.arange(x_2_min, x_2_max, 0.003)
x_constant = np.ones_like(x_2_range)
x_1_range = np.ones_like(x_2_range)*x_1.mean()
# Construct our input features
X_with_varying_x_2 = np.stack([x_constant.ravel(),
x_1_range.ravel() ,
x_2_range.ravel() ], axis = 1)
# Make linear Predictions
prediction_linear = model_linear_sklearn.predict(X_with_varying_x_2)
# Make logistic Predictions
prediction_proba = model_logistic.predict_proba(X_with_varying_x_2)
prediction_thresholded = model_logistic.predict(X_with_varying_x_2)
f,ax = plt.subplots(1,2, figsize=(14,6))
# Plot Linear Predictions
ax[0].plot(x_2_range, prediction_linear, label= 'Predicted Output (raw = continuous)')
ax[0].plot(x_2_range, np.round(prediction_linear), label= 'Predicted Class (round = integer)')
ax[0].legend()
ax[0].set_title('Linear Regression: raw output and rounded output.')
ax[0].set_ylim((-0.1,3.1))
ax[0].set_xlabel('sepal length (cm)')
# Plot Logistic Predictions
ax[1].plot(x_2_range, prediction_proba[:,0], label= 'Class 0')
ax[1].plot(x_2_range, prediction_proba[:,1], label= 'Class 1')
ax[1].plot(x_2_range, prediction_proba[:,2], label= 'Class 2')
ax[1].plot(x_2_range,prediction_thresholded, label= 'Predicted Class')
ax[1].legend()
ax[1].set_title('Logistic Regression: Predict_Proba Output per Class and the Predicted Class')
ax[1].set_xlabel('sepal length (cm)')
ax[1].set_ylim((-0.1,3.1))
plt.show()
How does our Logistic Regression come up with mutiple class predictions?¶
- Each class $y_i$ has a sigmoid function that tries to predict the probability of the tested input belonging to that specific class $y_i$.
- In our case when we have 3 classes, thus we have 3 sigmoid functions (the blue, orange and green line in the right figure).
LogisticRegression().predict_proba(...)
: returns probability estimates $P(y_i|x)$ for each $y_i$. In our case.predict_proba(...)
returns 3 values (one for each class). In the figure we observe that :- we have a high probability of predicting Class 0 in regions with low 'sepal length' values (left).
- we have a high probability of predicting Class 1 in regions with medium 'sepal length' regions (middle).
- have a high probability of predicting Class 2 in regions with high 'sepal length' regions (right).
LogisticRegression().predict(...)
: returns 1 value: the predicted class label. The class with the highest probability given by.predict_proba(...)
is exactly the predicted class output of.predict(...)
- In the figure our final prediction is the red line.
Get Performance by Class (Lookup Confusion Matrix)¶
confusion_matrix_logistic = pd.crosstab( y_test.values.flatten(),
y_pred_test.flatten(),
rownames=['Actual Class'],
colnames=['Predicted Class'])
display(confusion_matrix_logistic)
Let's compare the confusion matrix of our linear model to the confusion matrix of our logistic regression model:
print('######################################')
print('Confusion Matrix Linear Regression:')
display(confusion_matrix_linear)
print('\n######################################')
print('Confusion Matrix Logistic Regression:')
display(confusion_matrix_logistic)
print('######################################')
Now we do observe that the logistic regression has the correct number of predicted classes.
4. Visualize Predictions and Decision boundaries.¶
What are decision boundaries:
- In general, a pattern classifier carves up (or tesselates or partitions) the feature space into volumes called decision regions.
- All feature vectors in a decision region are assigned to the same category.
X_train.head()
def plot_points(ax):
for i, y_class in enumerate(set(y_train.values.flatten())):
index = (y_train == y_class).values
ax.scatter(X_train[index]['sepal width (cm)'],
X_train[index]['sepal length (cm)'],
c=colors[i],
s=65,
edgecolor='w',
label=names[i])
f, ax = plt.subplots(1, 1, figsize=(6,6))
colors = ["red", "green","blue"]
names = dataset.target_names
plot_points(ax)
ax.legend(bbox_to_anchor=(1, 1), loc='upper left', ncol=1)
ax.set_title('Classes of Flowers')
ax.set_ylabel('sepal length (cm)')
ax.set_xlabel('sepal width (cm)')
plt.show()
Plotting the decision boundary: by using the following functions:
np.meshgrid(..)
: 'constructing a grid': np.meshgrid() returns coordinate matrices from coordinate vectors.plt.contourf(..)
: contourf draws filled contours.
x_1 = X_train['sepal width (cm)']
x_2 = X_train['sepal length (cm)']
# Just for illustration purposes we use a margin of 0.2 to the
# left, right, top and bottum of our minimal and maximal points.
# This way our minimal and maximal points won't lie exactly
# on the axis.
x_1_min, x_1_max = x_1.min() - 0.2, x_1.max() + 0.2
x_2_min, x_2_max = x_2.min() - 0.2, x_2.max() + 0.2
xx_1, xx_2 = np.meshgrid(np.arange(x_1_min, x_1_max, 0.003),
np.arange(x_2_min, x_2_max, 0.003))
# Plotting decision regions
f, ax = plt.subplots(1, 1, figsize=(6, 6))
X_mesh = sm.add_constant(np.stack((xx_1.ravel(), xx_2.ravel()),axis=1))
Z = model_logistic.predict(X_mesh)
Z = Z.reshape(xx_1.shape)
ax.contourf(xx_1, xx_2, Z, alpha=0.5, colors=colors, levels=2)
plot_points(ax)
ax.legend(bbox_to_anchor=(1, 1), loc='upper left', ncol=1)
ax.set_title('Classes of Flowers')
ax.set_ylabel('sepal length (cm)')
ax.set_xlabel('sepal width (cm)')
plt.show()
Why are the decision boundaries of this Logistic Regression linear?
Imagine the simple case where we have only a 2 class classification problem: The logistic regression formula can be written as:
$$\hat{p}= \dfrac{e^{w^T x}}{1+e^{w^T x}}$$This is equivalent to:
$$\hat{p}= \dfrac{1}{1+e^{-w^T x}}$$We have x_1 (sepal width), x_2 (sepal length), and our intercept (constant =1)
$$\hat{p}= \dfrac{1}{1+e^{-(w_0 *1 + w_1 *x_1 + w_2* x_2)}}$$Since we don't use multiple higher order polynomial features like $x_1^2, x_2^2$, our logistic model only depends on the first order simple features $x_1$ and $x_2$.
What do we have to do to find the the decision boundary?
The decision boundaries are exactly at the position where our algorithm "hesitates" when predicting which class to classify. The output probability of our sigmoid (or softmax) is exactly 0.5. Solving our sigmoid function for $p=0.5$:
$$\hat{p}= \dfrac{1}{1+e^{-w^T x}} = 0.5 = \dfrac{1}{1+1} $$$$ e^{-w^T x} = 1$$$$ -w^T x = 0$$$$ w^T x = 0$$$$ w_0*1 + w_1 *x_1 + w_2 *1x_2 = 0$$When we only use two predictor features this constraint of $p=0.5$ results in a linear system; thus we observe a linear decision boundary.
In our case when we have three classes.
5. Fit a higher order polynomial logistic regression model for classification, compare performance, plot decision boundaries, and interpret results.¶
X_train_cst.head()
X_train_poly_cst=X_train_cst.copy()
X_train_poly_cst['sepal width (cm)^2'] = X_train_cst['sepal width (cm)']**2
X_train_poly_cst['sepal length (cm)^2'] = X_train_cst['sepal length (cm)']**2
X_test_poly_cst=X_test_cst.copy()
X_test_poly_cst['sepal width (cm)^2'] = X_test_poly_cst['sepal width (cm)']**2
X_test_poly_cst['sepal length (cm)^2'] = X_test_poly_cst['sepal length (cm)']**2
X_test_poly_cst.head()
#Training
model_logistic_poly = LogisticRegression(C=10000).fit(X_train_poly_cst, y_train)
#Predict
y_pred_train = model_logistic_poly.predict(X_train_poly_cst)
y_pred_test = model_logistic_poly.predict(X_test_poly_cst)
#Performance Evaluation
train_score = accuracy_score(y_train, y_pred_train)*100
test_score = accuracy_score(y_test, y_pred_test)*100
print("Training Set Accuracy:",str(train_score)+'%')
print("Testing Set Accuracy:",str(test_score)+'%')
Our test performance is decreasing, what might be happening?
- How would you test if this is happening?
- How would you inhibit this phenomenon from happening?
# Plotting decision regions
f, ax = plt.subplots(1, 1, figsize=(6, 6))
X_mesh_poly = sm.add_constant(np.stack((xx_1.ravel(), xx_2.ravel(), xx_1.ravel()**2,xx_2.ravel()**2),axis=1))
Z = model_logistic_poly.predict(X_mesh_poly)
Z = Z.reshape(xx_1.shape)
ax.contourf(xx_1, xx_2, Z, alpha=0.5, colors=colors, levels=2)
plot_points(ax)
ax.legend(bbox_to_anchor=(1, 1), loc='upper left', ncol=1)
ax.set_title('Classes of Flowers')
ax.set_ylabel('sepal length (cm)')
ax.set_xlabel('sepal width (cm)')
plt.show()
What do you observe regarding the form of the decision boundaries? Does this make sense?
$$\hat{p}= \dfrac{e^{w^T x}}{1+e^{w^T x}}$$This is equivalent to:
$$\hat{p}= \dfrac{1}{1+e^{-w^T x}}$$Now we use $x_1$ (sepal width), $x_2$ (sepal length), an intercept (constant =1), PLUS two higher order terms while making predictions:
- $x_1^2$ = (sepal_width)^2
- $x_2^2$ = (sepal_length)^2
Now solving for $p=0.5$ results in an equation also dependent on $x_1^2$ and $x_2^2$: thus we observe non-linear decision boundaries.
6. Fit a higher order polynomial logistic regression model for classification with different regularization parameters C ( [10000, 100, 1] )¶
f, ax = plt.subplots(1, 3, figsize=(6*3, 6))
model_logistics =[]
model_logistics_test_accs_scores =[]
model_logistics_train_accs_scores =[]
for test, C in enumerate([10000, 100, 1]):
model_logistics.append(LogisticRegression(C=C).fit(X_train_poly_cst, y_train))
y_pred_train = model_logistics[test].predict(X_train_poly_cst)
y_pred_test = model_logistics[test].predict(X_test_poly_cst)
model_logistics_train_accs_scores.append(accuracy_score(y_train, y_pred_train)*100)
model_logistics_test_accs_scores.append(accuracy_score(y_test, y_pred_test)*100)
Z = model_logistics[test].predict(X_mesh_poly)
Z = Z.reshape(xx_1.shape)
ax[test].contourf(xx_1, xx_2, Z, alpha=0.5, colors=colors, levels=2)
plot_points(ax[test])
ax[test].legend(loc='upper left', ncol=1)
ax[test].set_title('Classes of Flowers, with C = '+ str(C))
ax[test].set_ylabel('sepal length (cm)')
ax[test].set_xlabel('sepal width (cm)')
plt.show()
What do you observe?
- How are the decision boundaries looking?
- What happens when the regularization term C changes?
- You may want to look at the documentation of sklearn.linear.LogisticRegression():
# To get the documentation uncomment and run the following command:
# LogisticRegression?
What do expect regarding the evolution of the norm of the coefficients of our models when the regularizatoin term C changes?
Our list contains all 3 models with different values for C (take a look at the first parameter within brackets)
model_logistics
for test, model in enumerate(model_logistics):
print('\nRegularization parameter : \tC = {}'.format(model.C))
print("Training Set Accuracy : \t{}".format(model_logistics_train_accs_scores[test])+'%')
print("Testing Set Accuracy : \t\t{}".format(model_logistics_test_accs_scores[test])+'%')
print('Mean absolute coeficient : \t{:0.2f}'.format(np.mean(np.abs(model.coef_))))
Interpretation of Results: What happens when our Regularization Parameter decreases?
The amount of regularizaiton increases. This results in:
- The Training Set Accuracy decreasing a little bit (not much of a problem)
- The Test Set Accuracy decreasing a little bit (better generalization!)
- Our size of coefficents decreases on average.
END OF STANDARD SECTION
Optional: Fit a KNN-classification model for classification, plot decision boundaries, and interpret results.¶
#Training
model_KNN_classifier = KNeighborsClassifier(n_neighbors=1).fit(X_train_cst, y_train)
#Predict
y_pred_train = model_KNN_classifier.predict(X_train_cst)
y_pred_test = model_KNN_classifier.predict(X_test_cst)
#Performance Evaluation
train_score = accuracy_score(y_train, y_pred_train)*100
test_score = accuracy_score(y_test, y_pred_test)*100
print("Training Set Accuracy:",str(train_score)+'%')
print("Testing Set Accuracy:",str(test_score)+'%')
The fact we have a big gap of performance between the test and training set means we are overfitting, and can be explained by using "n_neighbors=1".
Based on your knowledge of KNN-regression can you guess how the decision boundary of the KNN-classification will look when using "n_neighbors=1"?
# Plotting decision regions
f, ax = plt.subplots(1, 1, figsize=(6, 6))
Z = model_KNN_classifier.predict(X_mesh)
Z = Z.reshape(xx_1.shape)
ax.contourf(xx_1, xx_2, Z, alpha=0.5, colors=colors, levels=2)
plot_points(ax)
ax.legend(bbox_to_anchor=(1, 1), loc='upper left', ncol=1)
ax.set_title('Classes of Flowers')
ax.set_ylabel('sepal length (cm)')
ax.set_xlabel('sepal width (cm)')
plt.show()
8. Optional Homework Tip: Pipeline building to sequentially apply a list of transforms (e.g. scaling, polynomial feature creation) and a final estimator.¶
Instead of manually building our polynomial features which might take a lot of lines of code we can use a pipeline to sequentially create polynomials before fitting our logistic regression. Scaling can also be done inside the make_pipeline
.
Previously we did:
X_train_poly_cst=X_train_cst.copy()
X_train_poly_cst['sepal width (cm)^2'] = X_train_cst['sepal width (cm)']**2
X_train_poly_cst['sepal length (cm)^2'] = X_train_cst['sepal length (cm)']**2
X_test_poly_cst=X_test_cst.copy()
X_test_poly_cst['sepal width (cm)^2'] = X_test_poly_cst['sepal width (cm)']**2
X_test_poly_cst['sepal length (cm)^2'] = X_test_poly_cst['sepal length (cm)']**2
Now it is a one-liner:
make_pipeline(PolynomialFeatures(degree=2), LogisticRegression())
# your code here
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures
polynomial_logreg_estimator = make_pipeline(
PolynomialFeatures(degree=2, include_bias=False),
LogisticRegression())
#Training
polynomial_logreg_estimator.fit(X_train_poly_cst, y_train)
#Predict
y_pred_train = polynomial_logreg_estimator.predict(X_train_poly_cst)
y_pred_test = polynomial_logreg_estimator.predict(X_test_poly_cst)
#Performance Evaluation
train_score = accuracy_score(y_train, y_pred_train)*100
test_score = accuracy_score(y_test, y_pred_test)*100
print("Training Set Accuracy:",str(train_score)+'%')
print("Testing Set Accuracy:",str(test_score)+'%')


WANT TO BUY
COOL STUFF FROM BEST BUY?
Aloha Electronics xxx xxxxx xxxxx xxxxx
xxx xxxxx xxx
WE GOT STUFF
Close
Stay upated on our latest product releases, be first to find out about upcoming sales,
And get free device tips from our blog. Unsubscribe at any time.


Date and time formats are specified by date and time pattern
strings.
Within date and time pattern strings, unquoted letters from
'A'
to 'Z'
and from 'a'
to
'z'
are interpreted as pattern letters representing the
components of a date or time string.
Text can be quoted using single quotes ('
) to avoid
interpretation.
"''"
represents a single quote.
All other characters are not interpreted; they're simply copied into the
output string during formatting or matched against the input string
during parsing.
The following pattern letters are defined (all other characters from
'A'
to 'Z'
and from 'a'
to
'z'
are reserved):
Pattern letters are usually repeated, as their number determines the exact presentation:
Letter Date or Time Component Presentation Examples G
Era designator Text AD
y
Year Year 1996
;96
Y
Week year Year 2009
;09
M
Month in year (context sensitive) Month July
;Jul
;07
L
Month in year (standalone form) Month July
;Jul
;07
w
Week in year Number 27
W
Week in month Number 2
D
Day in year Number 189
d
Day in month Number 10
F
Day of week in month Number 2
E
Day name in week Text Tuesday
;Tue
u
Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
a
Am/pm marker Text PM
H
Hour in day (0-23) Number 0
k
Hour in day (1-24) Number 24
K
Hour in am/pm (0-11) Number 0
h
Hour in am/pm (1-12) Number 12
m
Minute in hour Number 30
s
Second in minute Number 55
S
Millisecond Number 978
z
Time zone General time zone Pacific Standard Time
;PST
;GMT-08:00
Z
Time zone RFC 822 time zone -0800
X
Time zone ISO 8601 time zone -08
;-0800
;-08:00
Calendar
is the Gregorian
calendar, the following rules are applied.SimpleDateFormat
must interpret the abbreviated year
relative to some century. It does this by adjusting dates to be
within 80 years before and 20 years after the time the SimpleDateFormat
instance is created. For example, using a pattern of "MM/dd/yy" and a
SimpleDateFormat
instance created on Jan 1, 1997, the string
"01/11/12" would be interpreted as Jan 11, 2012 while the string "05/04/64"
would be interpreted as May 4, 1964.
During parsing, only strings consisting of exactly two digits, as defined by
Character.isDigit(char)
, will be parsed into the default century.
Any other numeric string, such as a one digit string, a three or more digit
string, or a two digit string that isn't all digits (for example, "-1"), is
interpreted literally. So "01/02/3" or "01/02/003" are parsed, using the
same pattern, as Jan 2, 3 AD. Likewise, "01/02/-3" is parsed as Jan 2, 4 BC.
'Y'
is specified and the calendar doesn't support any week
years, the calendar year ('y'
) is used instead. The
support of week years can be tested with a call to getCalendar()
.isWeekDateSupported()
.DateFormatSymbols
has been set
explicitly with constructor SimpleDateFormat(String,
DateFormatSymbols)
or method setDateFormatSymbols(DateFormatSymbols)
, the month names given by
the DateFormatSymbols
are used.GMTOffsetTimeZone:Hours must be between 0 and 23, and Minutes must be between 00 and 59. The format is locale independent and digits must be taken from the Basic Latin block of the Unicode standard.GMT
Sign Hours:
Minutes Sign: one of+ -
Hours: Digit Digit Digit Minutes: Digit Digit Digit: one of0 1 2 3 4 5 6 7 8 9
For parsing, RFC 822 time zones are also
accepted.
RFC822TimeZone: Sign TwoDigitHours Minutes TwoDigitHours: Digit DigitTwoDigitHours must be between 00 and 23. Other definitions are as for general time zones.
For parsing, general time zones are also accepted.
ISO8601TimeZone: OneLetterISO8601TimeZone TwoLetterISO8601TimeZone ThreeLetterISO8601TimeZone OneLetterISO8601TimeZone: Sign TwoDigitHoursOther definitions are as for general time zones or RFC 822 time zones.Z
TwoLetterISO8601TimeZone: Sign TwoDigitHours MinutesZ
ThreeLetterISO8601TimeZone: Sign TwoDigitHours:
MinutesZ
For formatting, if the offset value from GMT is 0, "Z"
is
produced. If the number of pattern letters is 1, any fraction of an hour
is ignored. For example, if the pattern is "X"
and the time zone is
"GMT+05:30"
, "+05"
is produced.
For parsing, "Z"
is parsed as the UTC time zone designator.
General time zones are not accepted.
If the number of pattern letters is 4 or more, IllegalArgumentException
is thrown when constructing a SimpleDateFormat
or applying a
pattern.
SimpleDateFormat
also supports localized date and time
pattern strings. In these strings, the pattern letters described above
may be replaced with other, locale dependent, pattern letters.
SimpleDateFormat
does not deal with the localization of text
other than the pattern letters; that's up to the client of the class.
Date and Time Pattern Result yyyy.MM.dd G 'at' HH:mm:ss
2001.07.04 AD at 12:08:56 PDT
EEE, MMM d, ''yy
Wed, Jul 4, '01
h:mm a
12:08 PM
hh 'o''clock' a, zzzz
12 o'clock PM, Pacific Daylight Time
K:mm a, z
0:08 PM, PDT
yyyyy.MMMMM.dd GGG hh:mm aaa
02001.July.04 AD 12:08 PM
EEE, d MMM yyyy HH:mm:ss Z
Wed, 4 Jul 2001 12:08:56 -0700
yyMMddHHmmssZ
010704120856-0700
yyyy-MM-dd'T'HH:mm:ss.SSSZ
2001-07-04T12:08:56.235-0700
yyyy-MM-dd'T'HH:mm:ss.SSSXXX
2001-07-04T12:08:56.235-07:00
YYYY-'W'ww-u
2001-W27-3


| vec_list_cast {vctrs} | R Documentation |
This is a function for developers to use when extending vctrs. It casts
a list to a more specific vectoring type, keeping the length constant.
It does this by discarding (with a warning), any elements after the 1.
It is called from vec_cast.XYZ.list()
methods to preserve symmetry with
vec_cast.list.XYZ()
.
vec_list_cast(x, to, ..., x_arg = "", to_arg = "")
x |
A list |
to |
Type to coerce to |
... |
These dots are for future extensions and must be empty. |
See vignette("s3-vector")
for details.


Loop.Coop
Open Source
Interactive 3D
sound-sculptures
Oom is under development
Check out this experiment


BLOG
Posted by Admin in General | 10 Comments
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap.Lorem Ipsum has been the industry's standard dummy text ever since the 1500.
ReadmorePosted by Admin in General | 10 Comments
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap.Lorem Ipsum has been the industry's standard dummy text ever since the 1500.
ReadmorePosted by Admin in General | 10 Comments
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500. Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap.Lorem Ipsum has been the industry's standard dummy text ever since the 1500.
Readmore


| Package | com.whirled |
| Class | public class FurniControl |
| Inheritance | FurniControl EntityControl AbstractControl flash.events.EventDispatcher |
| Subclasses | BackdropControl, PropControl, ToyControl |
| Method | Defined by | ||
|---|---|---|---|
|
FurniControl(disp:DisplayObject)
Create a furni interface.
| FurniControl | ||
|
addEventListener(type:String, listener:Function, useCapture:Boolean = false, priority:int = 0, useWeakReference:Boolean = false):void
Registers an event listener.
| AbstractControl | ||
|
canManageRoom(memberId:int = 0):Boolean
Returns true if the local client has management privileges in the current room.
| EntityControl | ||
|
clearPopup():void
Clear any showing popup.
| EntityControl | ||
|
doBatch(fn:Function, ... args):void
Execute the specified function as a batch of commands that will be sent to the server
together.
| AbstractControl | ||
|
getCamera(index:String = null):Camera
Access the local user's camera.
| EntityControl | ||
|
getDefaultDataPack():ByteArray
Get the default datapack for this entity, or null if there is none defined.
| EntityControl | ||
|
getEntityIds(type:String = null):Array
Enumerates the ids of all entities in this room.
| EntityControl | ||
|
getEntityProperty(key:String, entityId:String = null):Object
Looks up and returns the specified property for the specified entity.
| EntityControl | ||
|
getEnvironment():String
Get the "environment" in which this entity is presently running.
| EntityControl | ||
|
getInstanceId():int
Get the id of the viewer that is viewing this instance.
| EntityControl | ||
|
getLogicalLocation():Array
Returns our current logical location in the scene.
| EntityControl | ||
|
getMemories():Object
Return an associative hash of all the memories.
| EntityControl | ||
|
getMemory(key:String, defval:Object = null):Object
Returns the value associated with the supplied key in this item's memory.
| EntityControl | ||
|
getMicrophone(index:int = -1):Microphone
Access the local user's microphone.
| EntityControl | ||
|
getMusicId3():Object
Get the id3 metadata of the currently playing music.
| EntityControl | ||
|
getMusicOwnerId():int
Get the playerId of the owner of the currently playing music, aka the player who added it
to the playlist, or 0 if there is no music currently playing.
| EntityControl | ||
|
getMyEntityId():String
Returns the Whirled-wide unique ID of this copy of the entity.
| EntityControl | ||
|
getPixelLocation():Array
Returns our current location in the scene, in pixel coordinates.
| EntityControl | ||
|
getRoomBounds():Array
Get the room's bounds in pixels.
| EntityControl | ||
|
getViewerName(id:int = 0):String
Get the non-unique display name of the user viewing a particular instance.
| EntityControl | ||
|
hasControl():Boolean
Detects whether this client is in control.
| EntityControl | ||
|
isConnected():Boolean
Are we connected and running inside the whirled environment, or has someone just
loaded up our SWF by itself?
| AbstractControl | ||
|
registerCustomConfig(func:Function):void
Register a function used for generating a custom config panel.
| EntityControl | ||
|
registerPropertyProvider(func:Function):void
Registers a function that provides custom entity properties.
| EntityControl | ||
|
removeEventListener(type:String, listener:Function, useCapture:Boolean = false):void
Unregisters an event listener.
| AbstractControl | ||
|
sendMessage(name:String, arg:Object = null):void
Send a message to other instances of this entity, resulting in a MESSAGE_RECEIVED event.
| EntityControl | ||
|
sendSignal(name:String, arg:Object = null):void
Send a message to all instances of all entities in this instance's current room,
resulting in a SIGNAL_RECEIVED event.
| EntityControl | ||
|
setHotSpot(x:Number, y:Number, height:Number):void
Set the layout "hotspot" for your item, specified as pixels relative to (0, 0) the top-left
coordinate.
| EntityControl | ||
|
setMemory(key:String, value:Object, callback:Function = null):void
Requests that this item's memory be updated with the supplied key/value pair.
| EntityControl | ||
|
setTickInterval(interval:Number):void
Configures the interval on which this item is "ticked" in milliseconds.
| EntityControl | ||
|
showPage(token:String):Boolean
Shows the Whirled page identified by the supplied token.
| FurniControl | ||
|
showPopup(title:String, panel:DisplayObject, width:Number, height:Number, backgroundColor:uint = 0xFFFFFF, backgroundAlpha:Number = 1.0):Boolean
Show a popup to the current user in the whirled.
| EntityControl | ||
|
triggerAction(name:String, arg:Object = null):void
Triggers an action on this scene object.
| EntityControl |
| Event | Summary | Defined by | ||
|---|---|---|---|---|
| Dispatched when the instance in control sends a trigger action to all instances. | EntityControl | |||
| Dispatched to entities when they overhear chatter in the room. | EntityControl | |||
| Dispatched when this instance gains control. | EntityControl | |||
| Dispatched when an entity enters the room. | EntityControl | |||
| Dispatched when an entity leaves the room. | EntityControl | |||
| Dispatched when an entity in the room (other than the listening entity) changes location. | EntityControl | |||
| Dispatched when the local user unhovers the mouse from this sprite. | FurniControl | |||
| Dispatched when the local user hovers the mouse over this sprite. | FurniControl | |||
| Dispatched when the instance in control updates the memory of this digital item. | EntityControl | |||
| Dispatched when any instance sends a message to all instances. | EntityControl | |||
| Dispatched when id3 data is found in the currently playing song. | EntityControl | |||
| Dispatched when music starts playing in the room. | EntityControl | |||
| Dispatched when music stops playing in the room. | EntityControl | |||
| Dispatched when any entity or AVR game sends a message to all other entities. | EntityControl | |||
| Dispatched once per tick, only when this instance has control and only if tick interval is registered. | EntityControl | |||
| Event.UNLOAD Dispatched when the SWF using this control has been unloaded. | AbstractControl |
| Constant | Defined by | ||
|---|---|---|---|
| BODY_ENTERED : String = "bodyEntered" [static] An action triggered when someone arrives at the location at which
this furniture is placed, if this piece of furniture is a doorway.
| FurniControl | ||
| BODY_LEFT : String = "bodyLeft" [static] An action triggered when someone leaves via this piece of doorway
furniture.
| FurniControl | ||
| ENV_ROOM : String = "room" [static] A constant returned by getEnvironment() to indicate that this entity is
being viewed in a room.
| EntityControl | ||
| ENV_SHOP : String = "shop" [static] A constant returned by getEnvironment() to indicate that this entity is
being viewed in the shop.
| EntityControl | ||
| ENV_VIEWER : String = "viewer" [static] A constant returned by getEnvironment() to indicate that this entity is
being viewed in the "viewer": memories may be set and read, but they will not be saved.
| EntityControl | ||
| PROP_DIMENSIONS : String = "std:dimensions" [static] The entity pixel dimensions (an Array [width, height]).
| EntityControl | ||
| PROP_HOTSPOT : String = "std:hotspot" [static] The entity's hot spot (an Array [x, y]).
| EntityControl | ||
| PROP_LOCATION_LOGICAL : String = "std:location_logical" [static]
The entity's location in logical coordinates (an Array [ x, y, z ]).
| EntityControl | ||
| PROP_LOCATION_PIXEL : String = "std:location_pixel" [static]
The entity's location in pixel coordinates (an Array [ x, y, z ]).
| EntityControl | ||
| PROP_MEMBER_ID : String = "std:member_id" [static]
The unique Whirled player ID (int) of the wearer of the avatar, or the owner of the pet.
| EntityControl | ||
| PROP_MOVE_SPEED : String = "std:move_speed" [static] The current movement speed of an actor (Number).
| EntityControl | ||
| PROP_NAME : String = "std:name" [static]
The non-unique display name of the entity (a String).
| EntityControl | ||
| PROP_ORIENTATION : String = "std:orientation" [static]
The entity facing direction (a Number).
| EntityControl | ||
| PROP_TYPE : String = "std:type" [static]
The type of the entity, TYPE_AVATAR, TYPE_PET or TYPE_FURNI.
| EntityControl | ||
| TYPE_AVATAR : String = "avatar" [static] The type of avatar entities.
| EntityControl | ||
| TYPE_FURNI : String = "furni" [static] The type of furniture entities.
| EntityControl | ||
| TYPE_PET : String = "pet" [static] The type of pet entities.
| EntityControl |
| FurniControl | () | constructor |
public function FurniControl(disp:DisplayObject)
Create a furni interface. The display object is your piece of furni.
Parametersdisp:DisplayObject |
| showPage | () | method |
public function showPage(token:String):Boolean
Shows the Whirled page identified by the supplied token.
Parameterstoken:String — the token that identifies the page to be shown. This is not the full
URL, just the part after http://www.whirled.com/#. For example: passing "me" would show the
Me page. Passing "shop-l_5_343" would show the shop page for the Kawaii Knight avatar.
|
Boolean — true if the page was shown, false if it could not be shown for some reason.
|
| hoverOut | event |
com.whirled.ControlEvent
com.whirled.ControlEvent.HOVER_OVER
Dispatched when the local user unhovers the mouse from this sprite. Note that normal MouseEvents are blocked when this sprite has "action", like it is a doorway. If you want the doorway to react to the mouse being over it then you should listen for this event.
An event type dispatched to Furniture and Toys when the mouse is leaves them. Note that the normal MouseEvents will be blocked if the furniture has an action, so this is necessary to make doorways that react to mouse hovering. name - unused value - unused
| hoverOver | event |
com.whirled.ControlEvent
com.whirled.ControlEvent.HOVER_OVER
Dispatched when the local user hovers the mouse over this sprite. Note that normal MouseEvents are blocked when this sprite has "action", like it is a doorway. If you want the doorway to react to the mouse being over it then you should listen for this event.
An event type dispatched to Furniture and Toys when the mouse is over them. Note that the normal MouseEvents will be blocked if the furniture has an action, so this is necessary to make doorways that react to mouse hovering. name - unused value - unused
| BODY_ENTERED | constant |
public static const BODY_ENTERED:String = "bodyEntered"
An action triggered when someone arrives at the location at which this furniture is placed, if this piece of furniture is a doorway.
This will arrive via an ACTION_TRIGGERED event with the name property set to BODY_ENTERED.
| BODY_LEFT | constant |
public static const BODY_LEFT:String = "bodyLeft"
An action triggered when someone leaves via this piece of doorway furniture.
This will arrive via an ACTION_TRIGGERED event with the name property set to BODY_LEFT.


Harry Morton, son of Hard Rock Cafe co-founder, dies at 38
by Stefanie Dazio, The Associated PressLOS ANGELES -- Harry Morton, a restaurant mogul who was the son of the Hard Rock Cafe chain co-founder and grandson of the Morton's The Steakhouse founder, has died. He was 38.
Pink Taco, a restaurant business Morton founded and previously owned, confirmed his death in a statement Sunday. Specifics about the circumstances surrounding Morton's death were not immediately available.
Morton was also an owner of the Viper Room nightclub in West Hollywood and had been romantically linked to several celebrities, including Lindsay Lohan and Demi Moore.
"Harry was a visionary and restaurateur ahead of his time, and his contributions, both professionally to our brand and personally to those he worked with, were numerous," Pink Taco said in its statement.
Morton's father, Peter, co-founded the Hard Rock Cafe chain and his grandfather, Arnie, founded Morton's The Steakhouse.
Harry Morton served as vice-president of development of the Hard Rock chain after working summers at the Hard Rock Hotel in Las Vegas, The Los Angeles Times previously reported.
The Hard Rock chain did not immediately have a comment Sunday.


--- layout: post title: no title date: '2017-03-16T10:30:40+01:00' categories: - Illustration picture_url: https://film-Storyboards.tumblr.com/post/158476362157 ---


403
Go to home page{% extends "base.html" %} {% block title %}Additional Permissions Required{% endblock %} {% block page_title %}You don't appear to have the proper permissions to access this page.{% endblock page_title %} {% block content %}
403
Go to home page


Dashboard
Cases
Hospitalised
{{hosp}}
Cases about people that are undergoing treatment at hospitals
Cases
Infected
{{infected}}
Cases about people that have been infected
Cases
Recovered
{{recovered}}
Cases about people that have recovered from the disease
outbreak(s)
Cases
that have Died
{{death}}
Cases about people that died from the disease(s)
Number of {% if disease %} {{disease}} {% endif %} Cases {% if location %} for {{location}} {% endif %}
{% if disease %}
{% if location %}
{% else %}
{% endif %}
{% else %}
{% endif %}


Polling for by-election in LA-3 constituency of Mirpur underway
by News DeskPolling for the by-election in LA-3 constituency of Mirpur is underway and will continue till five in the evening.
According to the AJK Election Commission, a total number of voters in the constituency are fifty-nine thousand four hundred and ninety-four out of which twenty-seven thousand and four are women.
One hundred and nineteen polling stations have been set up out of which sixty-one have been declared sensitive.
SSP Mirpur Raja Irfan Saleem told our Mirpur correspondent Ali Akhtar Saleem that two thousand and seven hundred police personnel will perform to maintain law and order situation.
Pakistan Tehreek-e-Insaf’s AJK President Barrister Sultan Mehmood Choudhary and Pakistan Muslim League-Nawaz’s Suhaib Saeed are major contestants.


Achilles Shoes
Dashboard
HR
Manage users
Departments
CRM
New Clients
All Clients
Orders
New Orders
All Orders
Outsourcing
Suppliers
Delivery Company
Warehouse
Warehouse Places
Products
Reports
Accounting
Discounts
Chiping Fees
Invoices
Returneds
Reasons
Returned Products
en
ar
Username
profile
logout
Voucher
Date
Amount Percentage
Amount Fixed
Generate Barcode
Generate Barcode
Submit
All Vouchers
Search
Filter By
Name
Phone
Username
Department
Search
No.
From -
To
percentage
fixed
Action
1
25/25/2019
25/25/2019
25%
25%
«
‹
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
14
18
›
»


Penny-fyt
Home
About
Discover
Sign Up
Login
John Doe
more_vert
View Profile
Reload Account
Log Out
Change profile image
file_upload
Save
John Doe
0 ¢
add
0
following
0
followers
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User
User


Covid-19 Navigator Prototype
The visual map dynamically generates a visualization of Covid-19 Navigator Artifacts.
One navigates through the map by clicking on the label of an object. The map then dynamically redraws itself with that object as the center of the display. A text box in the upper right corner lists the objects that are related to the selected node.
The shapes have the following usage:
- The rectangle is simply the root of the diagram
- The squares are Intended Audience
- The triangles are Care Settings
- The orange circles are Care Processes
- The stars are Subjects
- The ellipses are Asset Types
- The pink circles are Assets
Additional navigation features:
- Position the mouse on an object shape (not its text label) to drag the object along the canvas. This is useful to uncover objects that are covered by other objects if the map gets cluttered.
- Click and hold the mouse on the background to drag the entire canvas.
- Use the scroll button on the mouse or the browser's "zoom" feature to zoom the canvas in and out.
- Use the browser's "find" function to search for a particular text label on the canvas. Remember that text may not be visible on the canvas (may require zooming out), or can become covered by other objects and appears in the text box in the upper right corner as well.
- There is a node list report.


§505-2 Index of liens. When a notice of such tax lien is recorded, the registrar shall forthwith cause the same to be indexed in the general indexes of the bureau of conveyances. [L 1931, c 220, §2; RL 1935, §5191; RL 1945, §12791; RL 1955, §346-2; am L 1966, c 33, §10; HRS §505-2]


- wait(int) - Static method in class ij.IJ
-
Delays 'msecs' milliseconds.
- WAIT - Static variable in interface ij.macro.MacroConstants
-
- WAIT_FOR_USER - Static variable in interface ij.macro.MacroConstants
-
- WaitForUserDialog - Class in ij.gui
-
This is a non-modal dialog box used to ask the user to perform some task
while a macro or plugin is running.
- WaitForUserDialog(String, String) - Constructor for class ij.gui.WaitForUserDialog
-
- WaitForUserDialog(String) - Constructor for class ij.gui.WaitForUserDialog
-
- WAND - Static variable in class ij.gui.Toolbar
-
- Wand - Class in ij.gui
-
This class implements ImageJ's wand (tracing) tool.
- Wand(ImageProcessor) - Constructor for class ij.gui.Wand
-
Constructs a Wand object from an ImageProcessor.
- WandToolOptions - Class in ij.plugin
-
This plugin implements the Edit/Options/Wand Tool command.
- WandToolOptions() - Constructor for class ij.plugin.WandToolOptions
-
- wasCanceled() - Method in class ij.gui.GenericDialog
-
Returns true if the user clicked on "Cancel".
- wasError() - Method in class ij.macro.Interpreter
-
- wasOKed() - Method in class ij.gui.GenericDialog
-
Returns true if the user has clicked on "OK" or a macro is running.
- weightedColor - Static variable in class ij.Prefs
-
Color to grayscale conversion is weighted (0.299, 0.587, 0.114) if the variable is true.
- weights - Variable in class ij.process.DownsizeTable
-
For each source point, weights for adding it to the destination point
given in the corresponding element of 'indices'
- west(ImageProcessor) - Method in class ij.plugin.filter.Shadows
-
- WHILE - Static variable in interface ij.macro.MacroConstants
-
- whiteIsZero - Variable in class ij.io.FileInfo
-
- width - Variable in class ij.io.FileInfo
-
- WIDTH_KEY - Static variable in class ij.gui.Arrow
-
- WIDTH_KEY - Static variable in class ij.text.TextWindow
-
- WIDTHD - Static variable in class ij.io.RoiDecoder
-
- WildcardMatch - Class in ij.util
-
This class allows for simple wildcard pattern matching.
- WildcardMatch() - Constructor for class ij.util.WildcardMatch
-
- WildcardMatch(char, char) - Constructor for class ij.util.WildcardMatch
-
- WINDOW_MENU_ITEMS - Static variable in class ij.Menus
-
- windowActivated(WindowEvent) - Method in class ij.gui.GenericDialog
-
- windowActivated(WindowEvent) - Method in class ij.gui.ImageWindow
-
- windowActivated(WindowEvent) - Method in class ij.gui.MessageDialog
-
- windowActivated(WindowEvent) - Method in class ij.gui.YesNoCancelDialog
-
- windowActivated(WindowEvent) - Method in class ij.ImageJ
-
- windowActivated(WindowEvent) - Method in class ij.macro.FunctionFinder
-
- windowActivated(WindowEvent) - Method in class ij.plugin.CommandFinder
-
- windowActivated(WindowEvent) - Method in class ij.plugin.frame.ColorThresholder
-
- windowActivated(WindowEvent) - Method in class ij.plugin.frame.ContrastAdjuster
-
- windowActivated(WindowEvent) - Method in class ij.plugin.frame.Editor
-
Override windowActivated in PlugInFrame to
prevent Mac menu bar from being installed.
- windowActivated(WindowEvent) - Method in class ij.plugin.frame.LineWidthAdjuster
-
- windowActivated(WindowEvent) - Method in class ij.plugin.frame.PlugInDialog
-
- windowActivated(WindowEvent) - Method in class ij.plugin.frame.PlugInFrame
-
- windowActivated(WindowEvent) - Method in class ij.plugin.frame.RoiManager
-
- windowActivated(WindowEvent) - Method in class ij.plugin.frame.ThresholdAdjuster
-
- windowActivated(WindowEvent) - Method in class ij.plugin.Orthogonal_Views
-
- windowClosed(WindowEvent) - Method in class ij.gui.GenericDialog
-
- windowClosed(WindowEvent) - Method in class ij.gui.ImageWindow
-
- windowClosed(WindowEvent) - Method in class ij.gui.MessageDialog
-
- windowClosed(WindowEvent) - Method in class ij.gui.YesNoCancelDialog
-
- windowClosed(WindowEvent) - Method in class ij.ImageJ
-
- windowClosed(WindowEvent) - Method in class ij.macro.FunctionFinder
-
- windowClosed(WindowEvent) - Method in class ij.plugin.CommandFinder
-
- windowClosed(WindowEvent) - Method in class ij.plugin.frame.PlugInDialog
-
- windowClosed(WindowEvent) - Method in class ij.plugin.frame.PlugInFrame
-
- windowClosed(WindowEvent) - Method in class ij.plugin.Orthogonal_Views
-
- windowClosing(WindowEvent) - Method in class ij.gui.GenericDialog
-
- windowClosing(WindowEvent) - Method in class ij.gui.ImageWindow
-
- windowClosing(WindowEvent) - Method in class ij.gui.MessageDialog
-
- windowClosing(WindowEvent) - Method in class ij.gui.NonBlockingGenericDialog
-
- windowClosing(WindowEvent) - Method in class ij.gui.YesNoCancelDialog
-
- windowClosing(WindowEvent) - Method in class ij.ImageJ
-
- windowClosing(WindowEvent) - Method in class ij.macro.FunctionFinder
-
- windowClosing(WindowEvent) - Method in class ij.plugin.CommandFinder
-
- windowClosing(WindowEvent) - Method in class ij.plugin.frame.PlugInDialog
-
- windowClosing(WindowEvent) - Method in class ij.plugin.frame.PlugInFrame
-
- windowClosing(WindowEvent) - Method in class ij.plugin.frame.SyncWindows
-
Override parent windowClosing method to clean up synchronized
resources on exit.
- windowClosing(WindowEvent) - Method in class ij.plugin.Orthogonal_Views
-
- windowDeactivated(WindowEvent) - Method in class ij.gui.GenericDialog
-
- windowDeactivated(WindowEvent) - Method in class ij.gui.ImageWindow
-
- windowDeactivated(WindowEvent) - Method in class ij.gui.MessageDialog
-
- windowDeactivated(WindowEvent) - Method in class ij.gui.YesNoCancelDialog
-
- windowDeactivated(WindowEvent) - Method in class ij.ImageJ
-
- windowDeactivated(WindowEvent) - Method in class ij.macro.FunctionFinder
-
- windowDeactivated(WindowEvent) - Method in class ij.plugin.CommandFinder
-
- windowDeactivated(WindowEvent) - Method in class ij.plugin.frame.PlugInDialog
-
- windowDeactivated(WindowEvent) - Method in class ij.plugin.frame.PlugInFrame
-
- windowDeactivated(WindowEvent) - Method in class ij.plugin.Orthogonal_Views
-
- windowDeiconified(WindowEvent) - Method in class ij.gui.GenericDialog
-
- windowDeiconified(WindowEvent) - Method in class ij.gui.ImageWindow
-
- windowDeiconified(WindowEvent) - Method in class ij.gui.MessageDialog
-
- windowDeiconified(WindowEvent) - Method in class ij.gui.YesNoCancelDialog
-
- windowDeiconified(WindowEvent) - Method in class ij.ImageJ
-
- windowDeiconified(WindowEvent) - Method in class ij.macro.FunctionFinder
-
- windowDeiconified(WindowEvent) - Method in class ij.plugin.CommandFinder
-
- windowDeiconified(WindowEvent) - Method in class ij.plugin.frame.PlugInDialog
-
- windowDeiconified(WindowEvent) - Method in class ij.plugin.frame.PlugInFrame
-
- windowDeiconified(WindowEvent) - Method in class ij.plugin.Orthogonal_Views
-
- windowIconified(WindowEvent) - Method in class ij.gui.GenericDialog
-
- windowIconified(WindowEvent) - Method in class ij.gui.ImageWindow
-
- windowIconified(WindowEvent) - Method in class ij.gui.MessageDialog
-
- windowIconified(WindowEvent) - Method in class ij.gui.YesNoCancelDialog
-
- windowIconified(WindowEvent) - Method in class ij.ImageJ
-
- windowIconified(WindowEvent) - Method in class ij.macro.FunctionFinder
-
- windowIconified(WindowEvent) - Method in class ij.plugin.CommandFinder
-
- windowIconified(WindowEvent) - Method in class ij.plugin.frame.PlugInDialog
-
- windowIconified(WindowEvent) - Method in class ij.plugin.frame.PlugInFrame
-
- windowIconified(WindowEvent) - Method in class ij.plugin.Orthogonal_Views
-
- WindowManager - Class in ij
-
This class consists of static methods used to manage ImageJ's windows.
- windowOpened(WindowEvent) - Method in class ij.gui.GenericDialog
-
- windowOpened(WindowEvent) - Method in class ij.gui.ImageWindow
-
- windowOpened(WindowEvent) - Method in class ij.gui.MessageDialog
-
- windowOpened(WindowEvent) - Method in class ij.gui.YesNoCancelDialog
-
- windowOpened(WindowEvent) - Method in class ij.ImageJ
-
- windowOpened(WindowEvent) - Method in class ij.macro.FunctionFinder
-
- windowOpened(WindowEvent) - Method in class ij.plugin.CommandFinder
-
- windowOpened(WindowEvent) - Method in class ij.plugin.frame.PlugInDialog
-
- windowOpened(WindowEvent) - Method in class ij.plugin.frame.PlugInFrame
-
- windowOpened(WindowEvent) - Method in class ij.plugin.Orthogonal_Views
-
- WindowOrganizer - Class in ij.plugin
-
- WindowOrganizer() - Constructor for class ij.plugin.WindowOrganizer
-
- windowStateChanged(WindowEvent) - Method in class ij.gui.ImageWindow
-
- WORD - Static variable in interface ij.macro.MacroConstants
-
- write(String) - Static method in class ij.IJ
-
Deprecated.
replaced by IJ.log(), ResultsTable.setResult() and TextWindow.append().
There are examples at
http://imagej.nih.gov/ij/plugins/sine-cosine.html
- write(OutputStream) - Method in class ij.io.ImageWriter
-
Writes the image to the specified OutputStream.
- write(byte[]) - Method in class ij.io.LogStream
-
- write(byte[], int, int) - Method in class ij.io.LogStream
-
- write(int) - Method in class ij.io.LogStream
-
- write(Roi) - Method in class ij.io.RoiEncoder
-
Save the Roi to the file of stream.
- write(DataOutputStream) - Method in class ij.io.TextEncoder
-
Saves the image as a tab-delimited text file.
- write(OutputStream) - Method in class ij.io.TiffEncoder
-
Saves the image as a TIFF file.
- write(DataOutputStream) - Method in class ij.io.TiffEncoder
-
- WRITE - Static variable in interface ij.macro.MacroConstants
-
- writeImage(ImagePlus, String, int, int) - Method in class ij.plugin.filter.AVI_Writer
-
Writes an ImagePlus (stack) as AVI file.
- writeImage(ImagePlus, String, int) - Method in class ij.plugin.PNG_Writer
-
- Writer - Class in ij.plugin.filter
-
This plugin saves an image in tiff, gif, jpeg, bmp, png, text or raw format.
- Writer() - Constructor for class ij.plugin.filter.Writer
-