public abstract class Duration extends Object
Immutable representation of a time span as defined in the W3C XML Schema 1.0 specification.
A Duration object represents a period of Gregorian time, which consists of six fields (years, months, days, hours, minutes, and seconds) plus a sign (+/-) field.
The first five fields have non-negative (>=0) integers or null (which represents that the field is not set), and the seconds field has a non-negative decimal or null. A negative sign indicates a negative duration.
This class provides a number of methods that make it easy to use for the duration datatype of XML Schema 1.0 with the errata.
Duration objects only have partial order, where two values A and B maybe either:
For example, 30 days cannot be meaningfully compared to one month.
The compare(Duration duration)
method implements this
relationship.
See the isLongerThan(Duration)
method for details about
the order relationship among Duration
objects.
This class provides a set of basic arithmetic operations, such as addition, subtraction and multiplication. Because durations don't have total order, an operation could fail for some combinations of operations. For example, you cannot subtract 15 days from 1 month. See the javadoc of those methods for detailed conditions where this could happen.
Also, division of a duration by a number is not provided because
the Duration
class can only deal with finite precision
decimal numbers. For example, one cannot represent 1 sec divided by 3.
However, you could substitute a division by 3 with multiplying by numbers such as 0.3 or 0.333.
Because some operations of Duration
rely on Calendar
even though Duration
can hold very large or very small values,
some of the methods may not work correctly on such Duration
s.
The impacted methods document their dependency on Calendar
.
XMLGregorianCalendar.add(Duration)
| Constructor and Description |
|---|
Duration()
Default no-arg constructor.
|
| Modifier and Type | Method and Description |
|---|---|
abstract Duration |
add(Duration rhs)
Computes a new duration whose value is
this+rhs . |
abstract void |
addTo(Calendar calendar)
Adds this duration to a
Calendar object. |
void |
addTo(Date date)
Adds this duration to a
Date object. |
abstract int |
compare(Duration duration)
Partial order relation comparison with this
Duration instance. |
boolean |
equals(Object duration)
Checks if this duration object has the same duration
as another
Duration object. |
int |
getDays()
Obtains the value of the DAYS field as an integer value,
or 0 if not present.
|
abstract Number |
getField(DatatypeConstants.Field field)
Gets the value of a field.
|
int |
getHours()
Obtains the value of the HOURS field as an integer value,
or 0 if not present.
|
int |
getMinutes()
Obtains the value of the MINUTES field as an integer value,
or 0 if not present.
|
int |
getMonths()
Obtains the value of the MONTHS field as an integer value,
or 0 if not present.
|
int |
getSeconds()
Obtains the value of the SECONDS field as an integer value,
or 0 if not present.
|
abstract int |
getSign()
Returns the sign of this duration in -1,0, or 1.
|
long |
getTimeInMillis(Calendar startInstant)
Returns the length of the duration in milli-seconds.
|
long |
getTimeInMillis(Date startInstant)
Returns the length of the duration in milli-seconds.
|
QName |
getXMLSchemaType()
Return the name of the XML Schema date/time type that this instance
maps to.
|
int |
getYears()
Get the years value of this
Duration as an int or 0 if not present. |
abstract int |
hashCode()
Returns a hash code consistent with the definition of the equals method.
|
boolean |
isLongerThan(Duration duration)
Checks if this duration object is strictly longer than
another
Duration object. |
abstract boolean |
isSet(DatatypeConstants.Field field)
Checks if a field is set.
|
boolean |
isShorterThan(Duration duration)
Checks if this duration object is strictly shorter than
another
Duration object. |
abstract Duration |
multiply(BigDecimal factor)
Computes a new duration whose value is
factor times
longer than the value of this duration. |
Duration |
multiply(int factor)
Computes a new duration whose value is
factor times
longer than the value of this duration. |
abstract Duration |
negate()
Returns a new
Duration object whose
value is -this . |
abstract Duration |
normalizeWith(Calendar startTimeInstant)
Converts the years and months fields into the days field
by using a specific time instant as the reference point.
|
Duration |
subtract(Duration rhs)
Computes a new duration whose value is
this-rhs . |
String |
toString()
Returns a
String representation of this Duration Object . |
public Duration()
Note: Always use the DatatypeFactory
to
construct an instance of Duration
.
The constructor on this class cannot be guaranteed to
produce an object with a consistent state and may be
removed in the future.
public QName getXMLSchemaType()
Return the name of the XML Schema date/time type that this instance
maps to. Type is computed based on fields that are set,
i.e. isSet(DatatypeConstants.Field field)
== true
.
|
Required fields for XML Schema 1.0 Date/Time Datatypes. (timezone is optional for all date/time datatypes) |
||||||
|---|---|---|---|---|---|---|
| Datatype | year | month | day | hour | minute | second |
DatatypeConstants.DURATION |
X | X | X | X | X | X |
DatatypeConstants.DURATION_DAYTIME |
X | X | X | X | ||
DatatypeConstants.DURATION_YEARMONTH |
X | X |
DatatypeConstants.DURATION
,
DatatypeConstants.DURATION_DAYTIME
or
DatatypeConstants.DURATION_YEARMONTH
.IllegalStateException
- If the combination of set fields does not match one of the XML Schema date/time datatypes.public abstract int getSign()
public int getYears()
Get the years value of this Duration
as an int
or 0
if not present.
getYears()
is a convenience method for
getField(DatatypeConstants.YEARS)
.
As the return value is an int
, an incorrect value will be returned for Duration
s
with years that go beyond the range of an int
.
Use getField(DatatypeConstants.YEARS)
to avoid possible loss of precision.
int
, else return 0
.public int getMonths()
getYears()
except
that this method works on the MONTHS field.Duration
.public int getDays()
getYears()
except
that this method works on the DAYS field.Duration
.public int getHours()
getYears()
except
that this method works on the HOURS field.Duration
.public int getMinutes()
getYears()
except
that this method works on the MINUTES field.Duration
.public int getSeconds()
getYears()
except
that this method works on the SECONDS field.public long getTimeInMillis(Calendar startInstant)
Returns the length of the duration in milli-seconds.
If the seconds field carries more digits than milli-second order,
those will be simply discarded (or in other words, rounded to zero.)
For example, for any Calendar value x
,
new Duration("PT10.00099S").getTimeInMills(x) == 10000
.new Duration("-PT10.00099S").getTimeInMills(x) == -10000
.
Note that this method uses the addTo(Calendar)
method,
which may work incorrectly with Duration
objects with
very large values in its fields. See the addTo(Calendar)
method for details.
startInstant
- The length of a month/year varies. The startInstant
is
used to disambiguate this variance. Specifically, this method
returns the difference between startInstant
and
startInstant+duration
startInstant
and
startInstant
plus this Duration
NullPointerException
- if startInstant
parameter
is null.public long getTimeInMillis(Date startInstant)
Returns the length of the duration in milli-seconds.
If the seconds field carries more digits than milli-second order,
those will be simply discarded (or in other words, rounded to zero.)
For example, for any Date
value x
,
new Duration("PT10.00099S").getTimeInMills(x) == 10000
.new Duration("-PT10.00099S").getTimeInMills(x) == -10000
.
Note that this method uses the addTo(Date)
method,
which may work incorrectly with Duration
objects with
very large values in its fields. See the addTo(Date)
method for details.
startInstant
- The length of a month/year varies. The startInstant
is
used to disambiguate this variance. Specifically, this method
returns the difference between startInstant
and
startInstant+duration
.startInstant
and
startInstant
plus this Duration
NullPointerException
- If the startInstant parameter is null.getTimeInMillis(Calendar)
public abstract Number getField(DatatypeConstants.Field field)
Number
object.
In case of YEARS, MONTHS, DAYS, HOURS, and MINUTES, the returned
number will be a non-negative integer. In case of seconds,
the returned number may be a non-negative decimal value.field
- one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
MINUTES, or SECONDS.)Number
object that
represents its value. If it is not present, return null.
For YEARS, MONTHS, DAYS, HOURS, and MINUTES, this method
returns a BigInteger
object. For SECONDS, this
method returns a BigDecimal
.NullPointerException
- If the field
is null
.public abstract boolean isSet(DatatypeConstants.Field field)
field
- one of the six Field constants (YEARS,MONTHS,DAYS,HOURS,
MINUTES, or SECONDS.)NullPointerException
- If the field parameter is null.public abstract Duration add(Duration rhs)
Computes a new duration whose value is this+rhs
.
For example,
"1 day" + "-3 days" = "-2 days" "1 year" + "1 day" = "1 year and 1 day" "-(1 hour,50 minutes)" + "-20 minutes" = "-(1 hours,70 minutes)" "15 hours" + "-3 days" = "-(2 days,9 hours)" "1 year" + "-1 day" = IllegalStateException
Since there's no way to meaningfully subtract 1 day from 1 month,
there are cases where the operation fails in
IllegalStateException
.
Formally, the computation is defined as follows.
Firstly, we can assume that two Duration
s to be added
are both positive without losing generality (i.e.,
(-X)+Y=Y-X
, X+(-Y)=X-Y
,
(-X)+(-Y)=-(X+Y)
)
Addition of two positive Duration
s are simply defined as
field by field addition where missing fields are treated as 0.
A field of the resulting Duration
will be unset if and
only if respective fields of two input Duration
s are unset.
Note that lhs.add(rhs)
will be always successful if
lhs.signum()*rhs.signum()!=-1
or both of them are
normalized.
rhs
- Duration
to add to this Duration
NullPointerException
- If the rhs parameter is null.IllegalStateException
- If two durations cannot be meaningfully added. For
example, adding negative one day to one month causes
this exception.subtract(Duration)
public abstract void addTo(Calendar calendar)
Calendar
object.
Calls Calendar.add(int,int)
in the
order of YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, and MILLISECONDS
if those fields are present. Because the Calendar
class
uses int to hold values, there are cases where this method
won't work correctly (for example if values of fields
exceed the range of int.)
Also, since this duration class is a Gregorian duration, this
method will not work correctly if the given Calendar
object is based on some other calendar systems.
Any fractional parts of this Duration
object
beyond milliseconds will be simply ignored. For example, if
this duration is "P1.23456S", then 1 is added to SECONDS,
234 is added to MILLISECONDS, and the rest will be unused.
Note that because Calendar.add(int, int)
is using
int
, Duration
with values beyond the
range of int
in its fields
will cause overflow/underflow to the given Calendar
.
XMLGregorianCalendar.add(Duration)
provides the same
basic operation as this method while avoiding
the overflow/underflow issues.
calendar
- A calendar object whose value will be modified.NullPointerException
- if the calendar parameter is null.public void addTo(Date date)
Date
object.
The given date is first converted into
a GregorianCalendar
, then the duration
is added exactly like the addTo(Calendar)
method.
The updated time instant is then converted back into a
Date
object and used to update the given Date
object.
This somewhat redundant computation is necessary to unambiguously determine the duration of months and years.
date
- A date object whose value will be modified.NullPointerException
- if the date parameter is null.public Duration subtract(Duration rhs)
Computes a new duration whose value is this-rhs
.
For example:
"1 day" - "-3 days" = "4 days" "1 year" - "1 day" = IllegalStateException "-(1 hour,50 minutes)" - "-20 minutes" = "-(1hours,30 minutes)" "15 hours" - "-3 days" = "3 days and 15 hours" "1 year" - "-1 day" = "1 year and 1 day"
Since there's no way to meaningfully subtract 1 day from 1 month,
there are cases where the operation fails in IllegalStateException
.
Formally the computation is defined as follows.
First, we can assume that two Duration
s are both positive
without losing generality. (i.e.,
(-X)-Y=-(X+Y)
, X-(-Y)=X+Y
,
(-X)-(-Y)=-(X-Y)
)
Then two durations are subtracted field by field.
If the sign of any non-zero field F
is different from
the sign of the most significant field,
1 (if F
is negative) or -1 (otherwise)
will be borrowed from the next bigger unit of F
.
This process is repeated until all the non-zero fields have the same sign.
If a borrow occurs in the days field (in other words, if
the computation needs to borrow 1 or -1 month to compensate
days), then the computation fails by throwing an
IllegalStateException
.
rhs
- Duration
to subtract from this Duration
.Duration
created from subtracting rhs
from this Duration
.IllegalStateException
- If two durations cannot be meaningfully subtracted. For
example, subtracting one day from one month causes
this exception.NullPointerException
- If the rhs parameter is null.add(Duration)
public Duration multiply(int factor)
Computes a new duration whose value is factor
times
longer than the value of this duration.
This method is provided for the convenience. It is functionally equivalent to the following code:
multiply(new BigDecimal(String.valueOf(factor)))
factor
- Factor times longer of new Duration
to create.Duration
that is factor
times longer than this Duration
.multiply(BigDecimal)
public abstract Duration multiply(BigDecimal factor)
factor
times
longer than the value of this duration.
For example,
"P1M" (1 month) * "12" = "P12M" (12 months) "PT1M" (1 min) * "0.3" = "PT18S" (18 seconds) "P1M" (1 month) * "1.5" = IllegalStateException
Since the Duration
class is immutable, this method
doesn't change the value of this object. It simply computes
a new Duration object and returns it.
The operation will be performed field by field with the precision
of BigDecimal
. Since all the fields except seconds are
restricted to hold integers,
any fraction produced by the computation will be
carried down toward the next lower unit. For example,
if you multiply "P1D" (1 day) with "0.5", then it will be 0.5 day,
which will be carried down to "PT12H" (12 hours).
When fractions of month cannot be meaningfully carried down
to days, or year to months, this will cause an
IllegalStateException
to be thrown.
For example if you multiple one month by 0.5.
To avoid IllegalStateException
, use
the normalizeWith(Calendar)
method to remove the years
and months fields.
factor
- to multiply byDuration
objectIllegalStateException
- if operation produces fraction in
the months field.NullPointerException
- if the factor
parameter is
null
.public abstract Duration negate()
Duration
object whose
value is -this
.
Since the Duration
class is immutable, this method
doesn't change the value of this object. It simply computes
a new Duration object and returns it.
Duration
object.public abstract Duration normalizeWith(Calendar startTimeInstant)
Converts the years and months fields into the days field by using a specific time instant as the reference point.
For example, duration of one month normalizes to 31 days given the start time instance "July 8th 2003, 17:40:32".
Formally, the computation is done as follows:
Calendar
object
by using the Calendar.add(int,int)
methodNote that since the Calendar class uses int
to
hold the value of year and month, this method may produce
an unexpected result if this duration object holds
a very large value in the years or months fields.
startTimeInstant
- Calendar
reference point.Duration
of years and months of this Duration
as days.NullPointerException
- If the startTimeInstant parameter is null.public abstract int compare(Duration duration)
Partial order relation comparison with this Duration
instance.
Comparison result must be in accordance with W3C XML Schema 1.0 Part 2, Section <IP_ADDRESS>.2, Order relation on duration.
Return:
DatatypeConstants.LESSER
if this Duration
is shorter than duration
parameterDatatypeConstants.EQUAL
if this Duration
is equal to duration
parameterDatatypeConstants.GREATER
if this Duration
is longer than duration
parameterDatatypeConstants.INDETERMINATE
if a conclusive partial order relation cannot be determinedduration
- to comparethis
Duration
and duration
parameter as
DatatypeConstants.LESSER
, DatatypeConstants.EQUAL
, DatatypeConstants.GREATER
or DatatypeConstants.INDETERMINATE
.UnsupportedOperationException
- If the underlying implementation
cannot reasonably process the request, e.g. W3C XML Schema allows for
arbitrarily large/small/precise values, the request may be beyond the
implementations capability.NullPointerException
- if duration
is null
.isShorterThan(Duration)
,
isLongerThan(Duration)
public boolean isLongerThan(Duration duration)
Checks if this duration object is strictly longer than
another Duration
object.
Duration X is "longer" than Y if and only if X>Y as defined in the section <IP_ADDRESS> of the XML Schema 1.0 specification.
For example, "P1D" (one day) > "PT12H" (12 hours) and "P2Y" (two years) > "P23M" (23 months).
duration
- Duration
to test this Duration
against.UnsupportedOperationException
- If the underlying implementation
cannot reasonably process the request, e.g. W3C XML Schema allows for
arbitrarily large/small/precise values, the request may be beyond the
implementations capability.NullPointerException
- If duration
is null.isShorterThan(Duration)
,
compare(Duration duration)
public boolean isShorterThan(Duration duration)
Checks if this duration object is strictly shorter than
another Duration
object.
duration
- Duration
to test this Duration
against.true
if duration
parameter is shorter than this Duration
,
else false
.UnsupportedOperationException
- If the underlying implementation
cannot reasonably process the request, e.g. W3C XML Schema allows for
arbitrarily large/small/precise values, the request may be beyond the
implementations capability.NullPointerException
- if duration
is null.isLongerThan(Duration duration)
,
compare(Duration duration)
public boolean equals(Object duration)
Checks if this duration object has the same duration
as another Duration
object.
For example, "P1D" (1 day) is equal to "PT24H" (24 hours).
Duration X is equal to Y if and only if time instant t+X and t+Y are the same for all the test time instants specified in the section <IP_ADDRESS> of the XML Schema 1.0 specification.
Note that there are cases where two Duration
s are
"incomparable" to each other, like one month and 30 days.
For example,
!new Duration("P1M").isShorterThan(new Duration("P30D")) !new Duration("P1M").isLongerThan(new Duration("P30D")) !new Duration("P1M").equals(new Duration("P30D"))
equals
in class Object
duration
- The object to compare this Duration
against.true
if this duration is the same length as
duration
.
false
if duration
is null
,
is not a
Duration
object,
or its length is different from this duration.UnsupportedOperationException
- If the underlying implementation
cannot reasonably process the request, e.g. W3C XML Schema allows for
arbitrarily large/small/precise values, the request may be beyond the
implementations capability.compare(Duration duration)
public abstract int hashCode()
hashCode
in class Object
Object.hashCode()
public String toString()
Returns a String
representation of this Duration
Object
.
The result is formatted according to the XML Schema 1.0 spec and can be always parsed back later into the
equivalent Duration
Object
by DatatypeFactory.newDuration(String lexicalRepresentation)
.
Formally, the following holds for any Duration
Object
x:
new Duration(x.toString()).equals(x)
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2015, Oracle and/or its affiliates. All rights reserved.


Head-on Big Island crash leaves 1 woman dead, another critically injured
by HNN StaffHONOLULU, Hawaii (HawaiiNewsNow) - A 28-year-old Kailua-Kona woman was killed and another woman was critically injured Tuesday following a head-on crash on the Big Island.
Police have identified the woman who died as Shelby Hookahi.
Investigators said the crash happened about 5:50 a.m. when the 28-year-old woman, driving a 2018 Kia Optima sedan, crossed double solid yellow lines on Highway 11 and struck a 2010 Lexus SUV head-on.
The driver of the Lexus, a 65-year-old Kailua-Kona woman, was taken to Kona Community Hospital in critical condition. She was later taken to the Queen’s Medical Center in Honolulu for treatment.
The 28-year-old woman was also taken to the Kona Community Hospital, where she was pronounced dead. Police said she was not wearing her seatbelt at the time of the crash.
A 3-year-old girl in the Kia was taken to the hospital with minor injuries and released.
Police said they believe that speed and drugs were factors in the crash.
The traffic fatality is the 21st so far this year compared to 27 at the same time last year.
Copyright 2019 Hawaii News Now. All rights reserved.


Action Sheet - Basic
Basic
Alert from Action Sheet
Cancel Only
Custom CSS Class
Icons
No Backdrop Dismiss
Scrollable Options
Scroll Without Cancel
Custom Backdrop Opacity
Button data


Exynos 2100 Vs Snapdragon 888 - S21 Ultra Edition
Samsung Exynos 2100 Edition vs Qualcomm 888 Edition - Just for Samsung S21 Ultra
When do you compare two processors what will come to your mind?
is it specifications or benchmark
But today we will compare two mobile processor legends of the market with a live test
First thing - Why you buy a mobile phone?
If it is performance then you may need to choose snapdragon 888 - Because it has 3% - 7% Better Performance.
But if it is ai computering then exynos 2100 is better choice - Because has 1% - 3.5% better ai computering
Explained
Why choose snapdragon 888 for performance?
In starting both phones perform same but after some time of use Exynos 2100 edition become hotter than snapdragon 888 not much but a little bit this little difference does not affect your day to day life just a difference of 3°C to 7°C and in performance, there is also a little bit of difference like a difference of 3% to 5% that you can't notice in day to day use of mobile.
Why choose Exynos 2100 Edition for ai?
The ai difference between Exynos 2100 and snapdragon 888 is just 1% to 3.5% and this is also not very much the difference is very little that you can't notice in your day-to-day life.
If I want a Camera which is best?
Both have the same camera quality, sensor & optimization.
Which is recommended?
Both are recommended by any of these that available in your country.
Is it the best-andoried mobile?
Yes, Because it is an all-rounder | For example, mi 11 Ultra has a lower price and better performance but mi did not have good software | One Ui is the Best Android Software in the World.
Which one is better iPhone 12 pro max or S21 Ultra?
S21 Ultra has a little bit better perofrmance and display but both are best on their own.
Becase S21 Ultra is best andoried phone | Iphone 12 pro max is best IOS phone.
Average life of a flagship mobile?
- 2 to 3 years
Advice - [ We recommend you to buy Mid - Range Mobile | Mid - Range Mobile are most Value for money mobiles]
About Us - In Short
Why choose unknowntech.tk for tech information?
- We did not show ads | We did not do promotion | Our Ui is simple and clean
Who own unknowntech.tk?
- unknowntech.tk is under itsunknown.tk owns by Shivang Sharma.
I like to write tech articles can I join unknowntech?
- Yes, If you want to join unknowntech | Follow and message us on instagram our instagram idd is itsunknown.in.
Disclaimer
- You can copy this information for non-profitable use.
- But You cannot copy this information for profitable use if you want to copy it for profitable use you need to take permission from us | For permission mail us on<EMAIL_ADDRESS>and need to give royalty to us.
- The information we provide is not granted as 100% True.
- Do not take design before reading full information because half information is dangerous.
- This content is under unknowntech.
- May This information also have spelling mistake but it is checked by grammarly.
- We did not Show ads | We did not Take your information data.
[ Thanks for Reading ]


Yes: There is a person steering the boat likely to approach the dock.
Not sure: A space at a dock can be seen, but I am not sure if a boat is coming.
No: A boat is sailing on the sea. I don't expect it to dock.
Yes: A helicopter with the landing zone clearly seen. It is very likely to land.
No: This is getting the car unstuck from the snow, not parking the car.


* Vdbench status * The objective of this file is to contain easily parseable information about the current state of Vdbench. * This then can serve as an 'official' interface for any software monitoring Vdbench. * Each line of output will be immediately flushed to the file system, making its content accessible by any monitoring program. * The values below are all tab-delimited. 11/24/2020-17:24:51-IST Starting slaves 11/24/2020-17:24:51-IST Slave localhost-0 (pid 4852) connected to master 4824 11/24/2020-17:24:51-IST Slaves connected 11/24/2020-17:24:51-IST Query host configuration started 11/24/2020-17:24:52-IST Shutting down slaves 11/24/2020-17:24:52-IST Abort requested: Please check above failures


Space Age
Date of Birth
Female
Male
Enter
Current Date
Date of Birth
Life Expectancy
Age: Earth
Age: Mercury
Age: Venus
Age: Mars
Age: Jupiter


Active Record Validations¶ ↑
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:
-
How to use the built-in Active Record validation helpers.
-
How to create your own custom validation methods.
-
How to work with the error messages generated by the validation process.
Validations Overview¶ ↑
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.
Why Use Validations?¶ ↑
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:
-
Database constraints and/or stored procedures make the validation mechanisms database-dependent and can make testing and maintenance more difficult. However, if your database is used by other applications, it may be a good idea to use some constraints at the database level. Additionally, database-level validations can safely handle some things (such as uniqueness in heavily-used tables) that can be difficult to implement otherwise.
-
Client-side validations can be useful, but are generally unreliable if used alone. If they are implemented using JavaScript, they may be bypassed if JavaScript is turned off in the user's browser. However, if combined with other techniques, client-side validation can be a convenient way to provide users with immediate feedback as they use your site.
-
Controller-level validations can be tempting to use, but often become unwieldy and difficult to test and maintain. Whenever possible, it's a good idea to keep your controllers skinny, as it will make your application a pleasure to work with in the long run.
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.
When Does Validation Happen?¶ ↑
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:
$ bin/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
just
returns the object.
Skipping Validations¶ ↑
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.messages
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.messages # => {} >> p.valid? # => false >> p.errors.messages # => {name:["can't be blank"]} >> p = Person.create # => #<Person id: nil, name: nil> >> p.errors.messages # => {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.
Validation Helpers¶ ↑
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 :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: "%{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 allows letters" } end
Alternatively, you can require that the specified attribute does
not match the regular expression by using the
:without
option.
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.split(/\s+/) }, 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
.
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 one of the following
validations:
validates :boolean_field_name, presence: true validates :boolean_field_name, inclusion: { in: [true, false] } validates :boolean_field_name, exclusion: { in: [nil] }
By using one of these validations, you will ensure the value will NOT be
nil
which would result in a NULL
value in most
cases.
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 on both columns in your database. See the MySQL manual for more details about multiple column indexes.
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 GoodnessValidator < ActiveModel::Validator def validate(record) if record.first_name == "Evil" record.errors[:base] << "This person is evil" end end end class Person < ActiveRecord::Base validates_with GoodnessValidator 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 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 class Person < ActiveRecord::Base validates_with GoodnessValidator, fields: [:first_name, :last_name] 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[[:lower:]]/ 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.
Common Validation Options¶ ↑
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 end
Strict Validations¶ ↑
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
Conditional Validation¶ ↑
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.
Using a Symbol with :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
Using a String with :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
Using a Proc with :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
Grouping Conditional validations¶ ↑
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?
Combining Validation Conditions¶ ↑
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
.
Performing Custom Validations¶ ↑
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¶ ↑
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. These 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.
Custom Methods¶ ↑
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
(API)
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
Working with Validation Errors¶ ↑
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.messages # => {:name=>["can't be blank", "is too short (minimum is 3 characters)"]} person = Person.new(name: "John Doe") person.valid? # => true person.errors.messages # => {}
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
Displaying Validation Errors in Views¶ ↑
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 @article
, it looks like this:
<%Q if @article.errors.any? %Q< <div id="error_explanation"> <h2><%=<EMAIL_ADDRESS>"error") %> prohibited this article from being saved:</h2> <ul> <% @article.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="article_title" name="article[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.


THE FIFTH ELEMENT A film review by Eric G. Scharf Copyright 1997 Eric G. Scharf
"Buckaroo Banzai" with ten times the budget and one tenth the plot.
Despite several dire reviews and some wry personal criticisms, I felt obligated to go see this, the first "summer movie" of the season. And although I don't exactly regret seeing this movie, I do wish I had managed to pay only $3.75 for the privilege.
"The Fifth Element" is remniscent of "Buckaroo Banzai" in that it drops the audience straight into the action and rushes along without bothering to explain odd details. But where "Buckaroo Banzai" told an interesting (or at least novel) story with minimal reliance on special effects, "The Fifth Element" spends millions on effects to dress up what is essentially a drug-running plot from a "Miami Vice" episode. "The Fifth Element" makes exactly zero (or negative, if you count the opportunity cost of the film's underwriting) contribution to the field of science fiction cinema. Don't bother looking for any explication of the political, technological, or social developments of the 250 years that allegdly transpire between the present and the film's milieu; the cinematographer's chief inspiration for 22nd century Brooklyn seems to have been Super Mario Bros. The "President of the Federation" was inexplicably feckless; I've seen more grace under pressure (and better dialogue) from my local McDonalds night supervisor. When the director's vision of the ancient race of interstellar good-guy patrons turned out not to include the ability to stay a closing elevator door, I knew the film was in trouble.
"Buckaroo Banzai" was also a helluva lot funnier. The only (intentional) comic relief in "The Fifth Element" waits until two thirds of the way into its 122 minutes to show up in the form of a refugee from a cancelled UPN show, but who is supposed to be a DJ (apparently, the dominant form of mass media in the 22nd century will be radio). This might have been an opportunity for yet another satire of the media, but even that would have been preferable to the tiresome hysterics provided by this buffoon.
The vast majority of screen time is taken up with either mediocre car chases and gunfights or Milla Jovovich trying to duplicate Jodie Foster's shameless Oscar grab in "Nell". Note that this movie was directed by Luc Besson, the man who brought us "La Femme Nikita". Jovovich's character is supposed to be this "perfect human" (think the title character from "Species" with a heart (and an accent)), strong enough to rip through her "unbreakable" incubation chamber. She is even shown memorizing Earth's library of martial arts. So what does Besson do? He exempts her, alone among all the primary (and secondary) characters, from the Universal Action Hero Immunity to Automatic Weapons. During the penultimate fight scene, Jovovich is trapped in a ventilation shaft and fired on repeatedly. Note that we also don't get to see her get wounded, which is the only reason to wound a hero in an action movie. We simply don't see her again until Willis has (after letting the aforementioned DJ grab far more screen time than he deserves) dispatched the bad guys and comes back to rescue her. The washed-up Special Forces guy turned-cabbie is better in a fight than the interstellar female assassin/Avatar of Good. Right.
Saving graces: Gary Oldman as Joe Bob Briggs, the (not really) surprisingly impotent arms-dealing mastermind and Servant of Evil (everyone knows that the Mark of the Devil is secretions of Hershey's Chocolate Syrup on the forehead, right?). Eric Serra's eclectic soundtrack.
I almost forgot that Ian Holm is in this movie. I'm sure he'd rather I did.
Go see "Twelve Monkeys" instead. You'll come away with a much better feeling about Bruce Willis, science fiction, screenwriting, French cinema, and the future of humanity.
-- Eric G. Scharf<EMAIL_ADDRESS>http://www.seattleu.edu/~escharf/film/5thelement.html http://www.seattleu.edu/~escharf/film/ http://www.seattleu.edu/~escharf/
The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.
Please direct comments/criticisms of the review to relevant newsgroups.
Broken URLs inthe reviews are the responsibility of the author.
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
Related links: index of all rec.arts.movies.reviews reviews


a project submitted as part of my dissertation project. "A New Reality: Exposing Homelessness in Malta through Infographic Installations"
Part of Ctrl Z - a collective digital arts exhibition, held online
“paper bags.” is a series of installations based on Lisa’s experience of homelessness. The three installations display aspects of her personal experience, as a set of events led to her storing all her belongings in paper bags. The presentation of her individual narrative reflects the importance of the single story, exposing specific experiences as opposed to viewing the homeless merely as numbers.
These installations seek to encourage viewers to interact with the pieces in order to take action and fight the apathy and distance often associated with interacting with the homeless.
"self." features 5 papers bags with a distorted message, only visible from one vantage point.
"loss." presents a large paper bag structure where viewers crouch down in the dark to listen to the audio excerpts.
"abuse." showcases a number of verbatim phrases that depict fragments from Lisa’s experience, printed inside paper bags. It is up to the viewer to peer inside and piece together the narrative.


{% include head.html %}
{% include navigation.html %} {% include header.html %} {% include theshow.html %} {% include whatson.html %} {% include previous.html %} {% include sponsors.html %} {% include contact.html %} {% include footer.html %} {% include modals.html %} {% include js.html %}


Bayswater PS celebrates 125th anniversary at fete
by Kristie LimBAYSWATER Primary School will be going back to the future as part of its 125th anniversary celebrations.
The school’s P&C is holding a Back to the Future themed fete on November 24 from 10am to 3pm.
The fete will include a historical dress-up and photo booth, sideshow alley, old fashion games and a blender bike.
The City of Bayswater, Metronet, Bayswater Historical Society and Bayswater Men’s Shed will also be holding stalls.
Former student and father Nathan Setzinger, who was in the class of 1983, said it was a lovely connection to have his daughter Edith attend the school.
“There are more classrooms, there is a new art block, the buildings have changed and there is a new library,” he said.
“The format has changed a bit.
“My classroom used to be one big and long classroom and now it is split into two.”
Mr Setzinger, now a teacher at Cecil Andrews College, said playing marbles, getting into trouble and being with the principal in the quadrangle were among his childhood memories.


VeriFast Help > Error messages
Error message
Preciseness check failure: callee is not precise
Context
When checking the body of a precise predicate.
Cause
The body of a precise predicate mentions a non-precise predicate.
Notes
Suggested solutions
Suggested approaches:
- Change the callee to a precise predicate by placing a semicolon at the end of its parameters list.
- Change the predicate itself to a non-precise predicate by replacing the semicolon in the parameter list with a comma. Note that instance predicates are always precise and hence this solution does not apply to instance predicates.


Some text ayy lmao roflcopters
Current MA student and Japanese-English translator with a strong interest in contemporary Japan and a deep love of karaoke. Current MA student and Japanese-English translator with a strong interest in contemporary Japan and a deep love of karaoke. Current MA student and Japanese-English translator with a strong interest in contemporary Japan and a deep love of karaoke. Current MA student and Japanese-English translator with a strong interest in contemporary Japan and a deep love of karaoke. Current MA student and Japanese-English translator with a strong interest in contemporary Japan and a deep love of karaoke. Current MA student and Japanese-English translator with a strong interest in contemporary Japan and a deep love of karaoke.
Sheffield, UK
+44<PHONE_NUMBER>
myemail@something.co.uk


.NET Gadgeteer Intro
.NET Gadgeteer is a discontinued technology that was initiated by Microsoft Research and taken to production by GHI Electronics in the year 2011. .NET Gadgeteer had a great few year run, where it was loved for its plug-and-play mainboard and modules.
Tip
We will refer to .NET Gadgeteer as Gadgeteer throughout the rest of the documentation.
The core of .NET Gadgeteer is .NET Micro Framework (NETMF). Like Gadgeteer, NETMF is no longer evolved by Microsoft and left for the community. Learn more about NETMF
Sadly, and after 5 years of building modules and mainboards, GHI Electronics had to announce the EOL for Gadgeteer; however, most of the Gadgeteer hardware can still be used with TinyCLR OS.
External resources:
- Microsoft's .NET Gadgeteer website (down) http://www.gadgeteer.com/
- Microsoft's NETMF website (outdated) http://www.netmf.com/
Most of the Gadgeteer ecosystem is open-source:
- Microsoft's .NET Gadgeteer Core
- GHI Electronics' Software sources and Hardware design files
Socket Map
The magic of Gadgeteer is in its socket map
| Socket | Pin1 | Pin2 | Pin3 | Pin4 | Pin5 | Pin6 | Pin7 | Pin8 | Pin9 | Pin10 |
|---|---|---|---|---|---|---|---|---|---|---|
| A | +3.3V | +5V | AIN (G!) | AIN (G) | AIN | GPIO | [UN] | [UN] | [UN] | GND |
| B | +3.3V | +5V | LCD B0 | LCD B1 | LCD B2 | LCD B3 | LCD B4 | LCD ENABLE | LCD CLK | GND |
| C | +3.3V | +5V | GPIO! | CAN TD (G) | CAN RD (G) | GPIO | [UN] | [UN] | [UN] | GND |
| D | +3.3V | +5V | GPIO! | D- | D+ | GPIO | GPIO | [UN] | [UN] | GND |
| E | +3.3V | +5V | [UN] | LED1 (OPT) | LED2 (OPT) | TX D- | TX D+ | RX D- | RX D+ | GND |
| F | +3.3V | +5V | GPIO! | DAT0 | DAT1 | CMD | DAT2 | DAT3 | CLK | GND |
| G | +3.3V | +5V | LCD G0 | LCD G1 | LCD G2 | LCD G3 | LCD G4 | LCD G5 | LCD BACKLIGHT | GND |
| H | +3.3V | +5V | GPIO! | D- | D+ | [UN] | [UN] | [UN] | [UN] | GND |
| I | +3.3V | +5V | GPIO! | [UN] | [UN] | GPIO | [UN] | SDA | SCL | GND |
| K | +3.3V | +5V | GPIO! | TX (G) | RX (G) | RTS | CTS | [UN] | [UN] | GND |
| O | +3.3V | +5V | GPIO! | GPIO | AOUT | [UN] | [UN] | [UN] | [UN] | GND |
| P | +3.3V | +5V | GPIO! | [UN] | [UN] | GPIO | PWM (G) | PWM (G) | PWM | GND |
| R | +3.3V | +5V | LCD R0 | LCD R1 | LCD R2 | LCD R3 | LCD R4 | LCD VSYNC | LCD HSYNC | GND |
| S | +3.3V | +5V | GPIO! | GPIO | GPIO | CS | MOSI | MISO | SCK | GND |
| T | +3.3V | +5V | [UN] | YU | XL | YD | XR | [UN] | [UN] | GND |
| U | +3.3V | +5V | GPIO! | TX (G) | RX (G) | GPIO | [UN] | [UN] | [UN] | GND |
| X | +3.3V | +5V | GPIO! | GPIO | GPIO | [UN] | [UN] | [UN] | [UN] | GND |
| Y | +3.3V | +5V | GPIO! | GPIO | GPIO | GPIO | GPIO | GPIO | GPIO | GND |
| Z | +3.3V | +5V | [MS] | [MS] | [MS] | [MS] | [MS] | [MS] | [MS] | GND |
| * | +3.3V | +5V | GPIO! | GPIO | GPIO | [MS] | [MS] | [MS] | [MS] | GND |
| Symbol | Description |
|---|---|
| AIN | Analog input pin. |
| GPIO | A general-purpose digital input/output pin, operating at 3.3 volts. |
| (G) | In addition to another functionality, a pin that is also usable as a GPIO. |
| [UN] | Modules must not connect to this pin if using this socket type. Mainboards can support multiple socket types on one socket, as long as individual pin functionalities overlap in a compatible manner, so that a pin from one socket type can overlap with a [UN] pin of another. |
| ! | Interrupt-capable and software pull-up capable GPIO (the pull-up is switchable and in the range of 10,000 to 100,000 ohms). |
| +3.3V | Connection to the +3.3 V power net. |
| +5V | Connection to the +5 V power net. |
| GND | Connection the power ground net. |
Using .NET Gadgeteer
To use .NET Gadgeteer's legacy software, install:
- Visual Studio 20013 (community edition is also supported)
- Unzip and install netmfvs2013.vsix and MicroFramewrokSDK.msi from here
- Microsoft's Gadgeteer Core
- GHI Electronics' NETMF SDK. The latest is recommended.
The Gadgeteer for Beginners guide is a good starting point.
Tip
You can only use Visual Studio 2013, not a newer edition, unless you are using your Gadgeteer hardware with TinyCLR OS.
With TinyCLR OS
Most of the .NET Gadgeteer devices are still usable today, and with the latest technologies, thanks to efforts by GHI Electronics and the community.
It all started in this video!
This means you can still use all your beloved .NET Gadgeteer gear with TinyCLR OS.
The first step needed to use TinyCLR OS is to load the GHI Bootloader v2 onto your mainboard, then use that to load the TinyCLR OS firmware. Each mainboard product page includes the needed instructions. Once those are loaded, you can start blinking the debug LED, detailed in the next section.
Blinking the LED
Tip
If you have never used TinyCLR OS before, start here
This example will blink the debug LED. You only need to add a power module to your mainboard.
using System.Threading;
using GHIElectronics.TinyCLR.Devices.Gpio;
using GHIElectronics.TinyCLR.Pins;
class Program {
static void Main() {
var led = GpioController.GetDefault().OpenPin(FEZSpider.GpioPin.DebugLed);
led.SetDriveMode(GpioPinDriveMode.Output);
while(true) {
led.Write(GpioPinValue.High);
Thread.Sleep(200);
led.Write(GpioPinValue.Low);
Thread.Sleep(200);
}
}
}
Tip
The complete pin mapping is made available through GHIElectronics.TinyCLR.Pins
. You should not need to use any schematics.
Replace FEZSpider
with your mainboard's name.
Adding Gadgeteer Modules
You are now ready to start adding modules.


| Class | Description |
|---|---|
| LapTimer |
LapTimer provides stopwatch and lap timer support for LFS.
|
| LFS |
LFS Class is Line Follower Simulator main class that handles:
tracking the position and heading of a virtual robot based on user specified target speed and turn rate
managing robot acceleration and speed (drive and turn) subject to simulator maximums
generating the view of immediate surroundings of a robot
reading sensor values from user defined spot and line sensors
presentation of an image of the course with robot image and cookie crumb trail tracking progress of robot
implements interactive marker system allowing storing multiple robot start locations and headings on a course
managing list of contest courses with optional starting location and heading, also timer mode stopwatch or lap time
managing contest states and producing contest run report
|
| LineSensor |
Create linear array of spot sensors, no public constructor is defined for this class, LFS method createLineSensor() is used instead.
|
| Sensors |
Single instance of Sensors provides access to both spot and line sensor lists created by LFS for
the purpose of iterating over all defined sensors to acquire sensor intensity data from the robots
current location and heading on a line following course image.
|
| SpotSensor |
Create a spot sensor, no public constructor is defined for this class, LFS method createSpotSensor is used instead.
|
| UI |
simple GUI (documentation not complete)
|
| UIButton |
Button Class, instance of which includes all possible buttons -- not using descendant classes here.
|
| VP |
Very light-weight rectangular viewport for Course,Robot,Sensor and other views defined in screen absolute coordinates where the origin (0,0)
is located at upper-left corner of screen.
|
Processing Library lineFollowerSim by Ron Grant. Copyright (c) 2020


Manuals
We're currently updating the BOP Field Manual and Oyster Research Station protocols. The information below may change soon, but for now, you can keep following the Oyster Measurement Protocol and Field Manual below.
{{ $grid := $.bindings.manuals }} {{ $grid := htmlAddClass $grid ".flip-contents" "unit-lessons" }} {{ $grid := htmlAddClass $grid ".flip-entries" "card-deck" }} {{ $grid := htmlRemove $grid ".flip-list-header" }} {{ $grid := htmlAddClass $grid ".flip-entry" "card" }} {{ $grid := htmlAddClass $grid ".flip-entry-visual" "text-center" }} {{ $grid := htmlAddClass $grid ".flip-entry-thumb" "card-img-top" }} {{ $grid := htmlAddClass $grid ".flip-entry-thumb img" "w-100 img-cover preview rounded-top object-top" }} {{ $grid := htmlSetAttr $grid ".flip-entry-thumb img" "height" "220" }} {{ $grid := htmlAttrFindReplace $grid ".flip-entry-thumb img" "src" "s190" "s600" }} {{ $grid := htmlAddClass $grid ".flip-entry-title" "card-body font-weight-bold" }} {{ $grid := htmlRemove $grid ".flip-entry-last-modified" }} {{ $grid := htmlRemove $grid ".flip-entry-list-icon" }} {{ $grid := htmlRemove $grid "meta" }} {{ $grid := htmlRemove $grid "link" }} {{ $grid := htmlRemove $grid "script" }} {{ $grid := htmlSetAttr $grid "*[id]" "id" "" }} {{ $grid }}Datasheets
{{ $grid := $.bindings.datasheets }} {{ $grid := htmlAddClass $grid ".flip-contents" "unit-lessons" }} {{ $grid := htmlAddClass $grid ".flip-entries" "card-deck" }} {{ $grid := htmlRemove $grid ".flip-list-header" }} {{ $grid := htmlAddClass $grid ".flip-entry" "card" }} {{ $grid := htmlAddClass $grid ".flip-entry-visual" "text-center" }} {{ $grid := htmlAddClass $grid ".flip-entry-thumb" "card-img-top" }} {{ $grid := htmlAddClass $grid ".flip-entry-thumb img" "w-100 img-cover preview rounded-top object-top" }} {{ $grid := htmlSetAttr $grid ".flip-entry-thumb img" "height" "220" }} {{ $grid := htmlAttrFindReplace $grid ".flip-entry-thumb img" "src" "s190" "s600" }} {{ $grid := htmlAddClass $grid ".flip-entry-title" "card-body font-weight-bold" }} {{ $grid := htmlRemove $grid ".flip-entry-last-modified" }} {{ $grid := htmlRemove $grid ".flip-entry-list-icon" }} {{ $grid := htmlRemove $grid "meta" }} {{ $grid := htmlRemove $grid "link" }} {{ $grid := htmlRemove $grid "script" }} {{ $grid := htmlSetAttr $grid "*[id]" "id" "" }} {{ $grid }}Species ID Resources
The BOP Digital Platform's database contains information about the mobile and sessile organisms most commonly found in Oyster Research Stations. Each listing includes a link to the species' profile on iNaturalist, which includes multiple photos of the organism and a worldwide map of sightings by community scientists, along with more detailed information about the species.


The following two blocks should be identical, including overflow. (Force bidi: א)
aaa bbb ccc ddd eee
fff
ggg hhh iii
jjj
kkk lll mmm nnn ooo
aaa bbb ccc eee ddd
jjj iii hhh ggg fff
lll kkk mmm nnn ooo


--- layout: page title: About header-img: "img/about-bg.png" ---
Accomplished analytics technical expert and thought leader with valuable, hands-on experience in Data warehouse, Analytics and CRM technologies.


Previous perfect square and cube number smaller than number N
Perfect cube greater than a given number
Perfect square greater than given number
Least number to be added to or subtracted from N to make it a Perfect Cube
Least number to be added to or subtracted from N to make it a Perfect Square
Count numbers upto N which are both perfect square and perfect cube
Find minimum number to be divided to make a number a perfect square
Minimum divisor of a number to make the number perfect cube
Cube Free Numbers smaller than n
Number of times the largest Perfect Cube can be subtracted from N
Find minimum number to be multiplied to make a number a perfect square
Find minimum number to be divided to make a number a perfect cube
Find minimum number to be multiplied to make a number a perfect cube
Check if number formed by joining two Numbers is Perfect Cube
Difference between Sum of Cubes and Sum of First N Natural Numbers
Difference between Sum of Cubes and Sum of Squares of First N Natural Numbers
Minimum digits to remove to make a number Perfect Square
Find square root of number upto given precision
Difference between Sum of Squares and Sum of First N Natural Numbers
Count square and non-square numbers before n
Check whether a number can be represented by sum of two squares
Check whether a number can be represented by difference of two squares
Check whether a number can be represented by product of two squares
Check whether a number can be represented by sum of two cubes
Check whether a number can be represented by difference of two cubes


Get notifications about new releases in our mobile app.
$ 10 / monthEnjoy new epsodes on your laptop in browser with our web service, wich supports all the platforms.
$15 / monthWatch your favorite series at home on large screen with our TV application.
$20 / month


Triangle Tracker
Types of Triangle are:
- Equilateral Triangle
- Iscocele Triangle
- Scalene Triangle
- Equilateral is:
- A Triangle that has all sides equal
- Iscoceles is:
- A Triangle in which two sides have the same length
- Scalene is:
- A Triangle that has three unequal sides
HOW TO KNOW THE TYPE OF YOUR TRIANGLE
Please enter the length of three sides
By:UMUTESIWASE Yvette


---
layout: default
---
Reading Group - 2017 Fall Semester
Machine Learning - Matrix Analysis
Time & Location
4 pm every Sunday
Reference Books
Kevin P. Murphy. Machine Learning - A Probabilistic Perspective. MIT Press, 2012.
Christopher M. Bishop. Pattern Recognition and Machine Learning. Springer, 2013.
Zhang, Xian-Da. Matrix analysis and applications. Cambridge University Press, 2017.
Schedule & Notes
| Date |
Track |
Content |
Reference |
Notes |
{% for data in site.data.notes %}
| {{data.date}} |
{{data.track}} |
{{data.content}} |
{{data.reference}} |
{% if data.url %}
Note |
{% else %}
|
{% endif %}
{% endfor %}


Problem 1. English digit
Problem 2. Reverse number
Problem 3. Occurrences of word
Problem 4. Number of elements
Problem 5. Appearance count
Problem 6. Larger than neighbours
Problem 7. First larger than neighbours


Computer Science Topic: Blockchain
Blockchain
Cryptocurrency
Smart Contracts
Other Uses
--> citation for this site <--


Numbers 20:18
And Edom said unto him, Thou shalt not pass by me, lest I come out against thee with the sword.


News
Release for both iOS and Android with the Flutter framework
Google has released an interesting new mobile UI framework that allows you to release for both iOS and Android with one codebase. It's in beta, but looks very slick and has been in alpha for a while. I think it's worth playing around with. Sometimes a framework just fits how you think and if Flutter does that for you, it could be an incredible value.
Announcing Flutter beta 1: Build beautiful native apps by Seth Ladd
Swift
When you should encapsulate in Swift
John explains why encapsulation matters and the drawbacks of ignoring encapsulation. He illustrates how this works by giving an example of a user upgrading to the pro version of your app. By encapsulating, you can protect your app from bugs when you make UI changes, among other things.
When a few milliseconds can mean a lot more
This is a great post to help you fully understand DispatchQueues, how they work, and how to use them in your app. Bruno's post will also help you visualize what's happening when there is a large task on the main and other types of threads.
understanding how the CPU deals with concurrency is the key to writing good, fast code that does what you expected it to do
Sponsored
Can your crash reporting tool do this?
With a few free solutions out there (Crashlytics comes to mind), you might be wondering why you should pay for a bug reporting service.
Here's why you may want to try Instabug:
- allow users to draw on screenshots, blur sensitive data, and magnify
- give you a screen recording of user's steps until the bug was reported
- let you have a real-time conversation with users inside your app
Does what your using now do any of this? Sign up for a free Instabug account today and, if you love it, get an exclusive 15% discount for Indie iOS Focus Weekly readers by using this link and the code InstabugLovesFocus
Marketing
The top ad platforms for your app in 2018
I've been working with a client on app install campaigns the last couple weeks and have found out a lot of interesting info. It's still crazy high to buy app installs and your monetization strategy needs to be laser focused in order to get an acceptable return on investment. If you don't have good data on your free to paid subscription conversion rate, you need to get it! I've also learned just how important it is to know your user demographics so you can choose which platforms will give you the best results.
PS: Ignore the title saying it's for 2017. The post was updated just this week but the title was not updated. Here's a tip for the bloggers out there. Don't put a date in the title of posts! Update them each year and they will always be evergreen.
Tutorials
How to remind users your app is still on their phone
Nice tutorial on implementing remote push notifications. This post will take you through all the steps necessary to set these up and spam your users all day give your users the updates they want. As Deyan says, “This is how you remind users about the fact that they have your app installed on their phones”.
iOS remote push notifications in a nutshell by Deyan Aleksandrov
Xcode
Demystifying the "Debug Executable" checkbox in the scheme editor
Besides getting to the bottom of what the "Debug executable" checkbox in the scheme editor actually does, this post shows some good debugging techniques in general. This "feature" is not well documented and I would propose that the link to it in Apple documents just forwards to this post. 😆
Xcode: using the “Debug executable” checkbox to step through app release versions by Andrew Jaffee
How to access Xcode's unofficial performance tests
If you thought Xcode's performance tests were lacking, check out this post from Daniel Jalkut where he dives deep and finds out there's actually more you can do. Though they are private and Apple officially wouldn't say you could use them, I would agree with Daniel and give this a try.
Don't let merge conflicts keep your from trying storyboards
If merge conflicts or fear of them has kept your team from using storyboards, take a look at this post from Joe Keeley, CTO at MartianCraft. Even if you don't end up using storyboards, it's good to know that the conflicts can be minimized when you get on a project that uses them.
Third-Party Libraries
Enjoy automatic sync between state and UI with this approach
Bending Spoons developed Tempura to make over twenty apps. They have over 10 million active users and they've decided to share their approach to app building with everyone. Definitely worth a look!
Tempura from Bending Spoons
Jobs
Don't let the Monster eat you, the best iOS jobs are on Hired
Hired is the place where companies look for iOS developers. Find 3500+ great tech companies on Hired who will compete to hire you. It's free. Try it out today!
Muru Inc is hiring an iOS Mobile Application Developer
With your technical expertise, you will build the first ever mobile software to deliver the full suite of medical information needed by paramedics in the field.
Career
How to effectively raise your freelance rate
Raising rates is a common thing freelance developers stress over. The longer you put it off, the more money you lose and the harder it is to get your rate to where it should be. Plus, there's uncertainty over how to approach current or long-time clients. Can they get a different rate? Should they? Graeme gives a few tips along with some key advice on why it's not so bad to lose clients.
The main thing I took away from this post was that if you consistently raise your rates, it keeps you where you should be and minimizes the effect on current clients.
How to raise your prices by Graeme Caldwell of CreativeBloq
Comment
Welcome! There's quite a bit going on in the iOS community and I've found a few great links this week. I try to mix it up, so I have some marketing and career stuff in there for you too, including how to increase your freelance rate to make more money.💰
I have big plans for a reader survey next week. I'm planning on giving away two $25 Amazon gift certificates to two lucky entries. I want to get some good feedback from all of you, so try to take time next week to answer a few questions about Indie iOS Focus Weekly. Hey, you might win $25 too. I'm announcing it today to hold my feet to the fire and finish the survey for next weeks issue. It's a good motivation tool. 💪
Also, thanks to everyone who replied to the newsletter last week. I appreciate the feedback and look forward to getting more next week. On to the links!
@cdbeshore | Support on Patreon


APIss2¶
-
class
noesis.models.
NetworkModel
(model, *args)¶ This class implements the interface for network models, allowing to instantiate a network given a network formation model.
Parameters: - model (string) – Network formation model used to generate the network. Currently supported models are ‘ErdosRenyi’, ‘BarabasiAlbert’, ‘WattsStrogatz’, ‘Gilbert’, ‘PriceCitation’, ‘AnchoredRandom’, ‘ConnectedRandom’, ‘Complete’, ‘BinaryTree’, ‘Hypercube’, ‘Isolate’, ‘Mesh’, ‘Ring’, ‘Star’, ‘Tandem’, and ‘Toroidal’.
- args (parameters) – Parameters the for network formation model. These parameters are specific for each network formation model and more details are provided in NOESIS documentation.
-
class
noesis.network.
Network
(**kargs)¶ This class implements the interface for networks, providing methods to query and manipulate network nodes and links.
-
add_link
(source, target)¶ Add a directed link to the network.
Parameters: - source (integer) – Index of the source node.
- target (integer) – Index of the target node.
-
add_link2
(source, target)¶ Add an undirected link to the network.
Parameters: - source (integer) – Index of the source node.
- target (integer) – Index of the target node.
-
add_node
()¶ Add a node to the network.
Returns: index – Index of the added node. Return type: integer
-
contains_link
(source, target)¶ Check if the network contains a link.
Parameters: - source (integer) – Index of the source node.
- target (integer) – Index of the target node.
Returns: is_contained – True if the network contains the link, False otherwise.
Return type: boolean
-
contains_node
(node)¶ Check if the network contains a node.
Parameters: node (integer) – Index of the node to check. Returns: is_contained – True if the network contains the node, False otherwise. Return type: boolean
-
degree
(node)¶ Get the degree of a given node in the network.
Parameters: node (integer) – Index of the node from which to obtain the degree. Returns: degree – Degree of the node. Return type: integer
-
in_degree
(node)¶ Get the in-degree of a given node in the network.
Parameters: node (integer) – Index of the node from which to obtain the in-degree. Returns: degree – In-degree of the node. Return type: integer
-
in_links
(node)¶ Get in-links for a given node in the network.
Parameters: node (integer) – Index of the node from which to obtain in-links. Returns: links – List of indices of nodes with links to the specified node. Return type: list of integers
-
is_directed
()¶ Check if a network is directed.
Returns: is_directed – True if the network is directed, False otherwise. Return type: bool
-
links
()¶ Get the number of links in the network.
Returns: link_count – Number of links in the network. Return type: integer
-
nodes
()¶ Get the number of nodes in the network.
Returns: node_count – Number of nodes in the network. Return type: integer
-
out_degree
(node)¶ Get the out-degree of a given node in the network.
Parameters: node (integer) – Index of the node from which to obtain the out-degree. Returns: degree – Out-degree of the node. Return type: integer
-
out_links
(node)¶ Get out-links for a given node in the network.
Parameters: node (integer) – Index of the node from which to obtain out-links. Returns: links – List of indices of nodes with links from the specified node. Return type: list of integers
-
remove_link
(source, target)¶ Remove a directed link from the network.
Parameters: - source (integer) – Index of the source node.
- target (integer) – Index of the target node.
-
remove_link2
(source, target)¶ Remove an undirected link from the network.
Parameters: - source (integer) – Index of the source node.
- target (integer) – Index of the target node.
-
remove_node
(node)¶ Remove a given node from the network.
Parameters: node (integer) – Index of the node to remove.
-
set_directed
(directed)¶ Set network if network is directed or undirected.
Parameters: directed (boolean) – True to set the network as directed, False otherwise.
-