A Guided Nature Meditation
This is a guided meditation that I created while walking on a farm. The surroundings of crops and the sun inspired me to see the relation with our food and the energy it provides us.
Meditation Spots to Enhance Your Practice
Why you want a meditation space of your ownWhere do you like to meditate? The beauty of mediation is that it can be practiced anywhere. Frequent meditators create a meditation space where they have a dedicated space for their practice.
Improve Your Life by Breathing
We take the act of breathing for granted. We do it every minute of our lives without giving it a single thought. Breathing gives us vital oxygen and removes unwanted waste form our bodies. Breathing is related to your emotional state
Learn These Meditations to Spark Innovation
We are living in a knowledge based economy where we depend on creating innovative solutions. How can we improve our ability to innovate and be creative? Meditation can help you spark your creativity and help solve a problem that has been eating away at you brain for days.
How to Sink Into Yourself
I often stay in my head when I am at work, I almost forget that I am attached to my body. When our heads are always in the clouds we are not rooted into ourselves and one small incident can push us into disharmony.
What happens when you fall out of your meditation practice?
Life sometimes gets in our way. We might fall off our meditation practice and that is ok. At least we are aware that we are not meditating and we have to get back into our practice. I will tell you my experience of falling out of my mediation practice and trying to get back into it.
Is Your Brain Trying to Hold You Back?
How do athletes cultivate the mental toughness to achieve greatness? How are they able to dig deep inside themselves and find the energy when most people would just give up?
Beat the Freezing Cold With Meditation!
With record breaking snowfall this year I am trying every way to stay warm. The brutal cold reminded me of a video I saw of monks being able to heat their bodies and actually cause a cold wet blanket to steam.
Can Brain Sensing Devices Really Help you Meditate?
 Brain sensing technology has become relatively cheap allowing regular people to dive into their brain data.
How to NOT fall asleep during your next meditation session
Remember that time when you tried meditating and had everything perfect, you set aside 10 minutes of quite time in a comfy chair and closed your eyes. However, 2 minutes into your meditation you start to snore and fall asleep.
8 Reasons why you should practice Mindfulness
Mindfulness is becoming very popular, but what really is mindfulness and how can it benefit you? You can think of mindfulness as being fully aware of the present moment.


| |
Create a hardware interrupt.
-
Description:
-
This API is used to configure a hardware interrupt and register a hardware interrupt handling function.
-
注意:
-
- The hardware interrupt module is usable only when the configuration item for hardware interrupt tailoring is enabled.
- Hardware interrupt number value range: [OS_USER_HWI_MIN,OS_USER_HWI_MAX]. The value range applicable for a Cortex-A7 platform is [32,95].
- OS_HWI_MAX_NUM specifies the maximum number of interrupts that can be created.
- Before executing an interrupt on a platform, refer to the chip manual of the platform.
-
参数:
-
|
参数名称 |
描述 |
|
uwHwiNum |
[IN] Type::HWI_HANDLE_T: hardware interrupt number. The value range applicable for a Cortex-A7 platform is [32,95]. |
|
usHwiPrio |
[IN] Type::HWI_PRIOR_T: hardware interrupt priority. Ignore this parameter temporarily. |
|
usMode |
[IN] Type::HWI_MODE_T: hardware interrupt mode. Ignore this parameter temporarily. |
|
pfnHandler |
[IN] Type::HWI_PROC_FUNC: interrupt handler used when a hardware interrupt is triggered. |
|
uwArg |
[IN] Type::HWI_ARG_T: input parameter of the interrupt handler used when a hardware interrupt is triggered. |
-
返回值:
-
-
Dependency:
-
- los_hwi.h: the header file that contains the API declaration.
-
参见:
-
None.
-
自从:
-
Huawei LiteOS V100R001C00
|


Master of Science (M.S.) in Software Engineering of Distributed Systems with skills in distributed systems, parallel computing and general IT. I have a lot of experience with object-oriented programming languages, mainly Java. My knowledge also extends to mobile app-development, C, Python and Linux.


|
__mocks__/MockAppService.ts
|
class |
MockAppService |
0 %
(0/1)
|
|
__mocks__/MockAuthService.ts
|
class |
MockAuthService |
0 %
(0/1)
|
|
src/app/+examples/examples.component.ts
|
component |
ExamplesComponent |
0 %
(0/3)
|
|
src/app/+examples/examples/forms-playground/forms-playground.component.ts
|
component |
FormsPlaygroundComponent |
0 %
(0/6)
|
|
src/app/+examples/examples/shop/customers/customers.component.ts
|
component |
CustomersComponent |
0 %
(0/5)
|
|
src/app/+examples/examples/shop/products/products.component.ts
|
component |
ProductsComponent |
0 %
(0/8)
|
|
src/app/+examples/examples/shop/shop.component.ts
|
component |
ShopComponent |
0 %
(0/1)
|
|
src/app/+examples/examples/shop/shop.routes.ts
|
variable |
routes |
0 %
(0/1)
|
|
src/app/+examples/examples/signalr/chat/chat.component.ts
|
component |
ChatComponent |
0 %
(0/8)
|
|
src/app/+examples/examples/signalr/move-shape/draggable.directive.ts
|
directive |
DraggableDirective |
0 %
(0/7)
|
|
src/app/+examples/examples/signalr/move-shape/move-shape.component.ts
|
component |
MoveShapeComponent |
0 %
(0/5)
|
|
src/app/+examples/examples/signalr/signalr.component.ts
|
component |
SignalrComponent |
0 %
(0/1)
|
|
src/app/+examples/examples/signalr/signalr.routes.ts
|
variable |
routes |
0 %
(0/1)
|
|
src/app/api-client.ts
|
class |
ApplicationDataViewModel |
0 %
(0/9)
|
|
src/app/api-client.ts
|
class |
CategoriesListVm |
0 %
(0/7)
|
|
src/app/api-client.ts
|
class |
CategoryDto |
0 %
(0/9)
|
|
src/app/api-client.ts
|
class |
CreateCustomerCommand |
0 %
(0/16)
|
|
src/app/api-client.ts
|
class |
CreateProductCommand |
0 %
(0/10)
|
|
src/app/api-client.ts
|
class |
CulturesDisplayViewModel |
0 %
(0/8)
|
|
src/app/api-client.ts
|
class |
CustomerDetailVm |
0 %
(0/16)
|
|
src/app/api-client.ts
|
class |
CustomerLookupDto |
0 %
(0/7)
|
|
src/app/api-client.ts
|
class |
CustomersListVm |
0 %
(0/6)
|
|
src/app/api-client.ts
|
class |
EmployeeDetailVm |
0 %
(0/23)
|
|
src/app/api-client.ts
|
class |
EmployeeLookupDto |
0 %
(0/9)
|
|
src/app/api-client.ts
|
class |
EmployeeTerritoryDto |
0 %
(0/8)
|
|
src/app/api-client.ts
|
class |
EnvironmentInformation |
0 %
(0/12)
|
|
src/app/api-client.ts
|
class |
ProblemDetails |
0 %
(0/11)
|
|
src/app/api-client.ts
|
class |
ProductDetailVm |
0 %
(0/15)
|
|
src/app/api-client.ts
|
class |
ProductDto |
0 %
(0/13)
|
|
src/app/api-client.ts
|
class |
ProductsListVm |
0 %
(0/7)
|
|
src/app/api-client.ts
|
class |
SwaggerException |
0 %
(0/9)
|
|
src/app/api-client.ts
|
class |
UpdateCustomerCommand |
0 %
(0/16)
|
|
src/app/api-client.ts
|
class |
UpdateProductCommand |
0 %
(0/11)
|
|
src/app/api-client.ts
|
class |
UpsertCategoryCommand |
0 %
(0/9)
|
|
src/app/api-client.ts
|
class |
UpsertEmployeeCommand |
0 %
(0/22)
|
|
src/app/api-client.ts
|
injectable |
AppClient |
0 %
(0/9)
|
|
src/app/api-client.ts
|
injectable |
CategoriesClient |
0 %
(0/11)
|
|
src/app/api-client.ts
|
injectable |
CustomersClient |
0 %
(0/15)
|
|
src/app/api-client.ts
|
injectable |
EmployeesClient |
0 %
(0/13)
|
|
src/app/api-client.ts
|
injectable |
ProductsClient |
0 %
(0/17)
|
|
src/app/api-client.ts
|
interface |
FileResponse |
0 %
(0/5)
|
|
src/app/api-client.ts
|
interface |
IAppClient |
0 %
(0/3)
|
|
src/app/api-client.ts
|
interface |
IApplicationDataViewModel |
0 %
(0/5)
|
|
src/app/api-client.ts
|
interface |
ICategoriesClient |
0 %
(0/4)
|
|
src/app/api-client.ts
|
interface |
ICategoriesListVm |
0 %
(0/3)
|
|
src/app/api-client.ts
|
interface |
ICategoryDto |
0 %
(0/5)
|
|
src/app/api-client.ts
|
interface |
ICreateCustomerCommand |
0 %
(0/12)
|
|
src/app/api-client.ts
|
interface |
ICreateProductCommand |
0 %
(0/6)
|
|
src/app/api-client.ts
|
interface |
ICulturesDisplayViewModel |
0 %
(0/4)
|
|
src/app/api-client.ts
|
interface |
ICustomerDetailVm |
0 %
(0/12)
|
|
src/app/api-client.ts
|
interface |
ICustomerLookupDto |
0 %
(0/3)
|
|
src/app/api-client.ts
|
interface |
ICustomersClient |
0 %
(0/6)
|
|
src/app/api-client.ts
|
interface |
ICustomersListVm |
0 %
(0/2)
|
|
src/app/api-client.ts
|
interface |
IEmployeeDetailVm |
0 %
(0/19)
|
|
src/app/api-client.ts
|
interface |
IEmployeeLookupDto |
0 %
(0/5)
|
|
src/app/api-client.ts
|
interface |
IEmployeesClient |
0 %
(0/5)
|
|
src/app/api-client.ts
|
interface |
IEmployeeTerritoryDto |
0 %
(0/4)
|
|
src/app/api-client.ts
|
interface |
IEnvironmentInformation |
0 %
(0/8)
|
|
src/app/api-client.ts
|
interface |
IProblemDetails |
0 %
(0/7)
|
|
src/app/api-client.ts
|
interface |
IProductDetailVm |
0 %
(0/11)
|
|
src/app/api-client.ts
|
interface |
IProductDto |
0 %
(0/9)
|
|
src/app/api-client.ts
|
interface |
IProductsClient |
0 %
(0/7)
|
|
src/app/api-client.ts
|
interface |
IProductsListVm |
0 %
(0/3)
|
|
src/app/api-client.ts
|
interface |
IUpdateCustomerCommand |
0 %
(0/12)
|
|
src/app/api-client.ts
|
interface |
IUpdateProductCommand |
0 %
(0/7)
|
|
src/app/api-client.ts
|
interface |
IUpsertCategoryCommand |
0 %
(0/5)
|
|
src/app/api-client.ts
|
interface |
IUpsertEmployeeCommand |
0 %
(0/18)
|
|
src/app/api-client.ts
|
function |
blobToText |
0 %
(0/1)
|
|
src/app/api-client.ts
|
function |
throwException |
0 %
(0/1)
|
|
src/app/api-client.ts
|
variable |
API_BASE_URL |
0 %
(0/1)
|
|
src/app/app.component.ts
|
component |
AppComponent |
0 %
(0/5)
|
|
src/app/components/footer/footer.component.ts
|
component |
FooterComponent |
0 %
(0/1)
|
|
src/app/components/header/header.component.ts
|
component |
HeaderComponent |
0 %
(0/6)
|
|
src/app/components/privacy/privacy.component.ts
|
component |
PrivacyComponent |
0 %
(0/1)
|
|
src/app/home/home.component.ts
|
component |
HomeComponent |
0 %
(0/1)
|
|
src/app/models.ts
|
interface |
Field |
0 %
(0/2)
|
|
src/app/models.ts
|
interface |
IEnableAuthenticatorModel |
0 %
(0/4)
|
|
src/app/models.ts
|
interface |
IFieldConfig |
0 %
(0/11)
|
|
src/app/models.ts
|
interface |
IModalOptions |
0 %
(0/4)
|
|
src/app/models.ts
|
interface |
IOption |
0 %
(0/4)
|
|
src/app/models.ts
|
interface |
ISocialLogins |
0 %
(0/5)
|
|
src/app/models.ts
|
interface |
ITwoFactorModel |
0 %
(0/4)
|
|
src/app/models.ts
|
interface |
KeyValuePair |
0 %
(0/3)
|
|
src/app/models.ts
|
variable |
COOKIES |
0 %
(0/1)
|
|
src/app/router.animations.ts
|
variable |
routerTransition |
0 %
(0/1)
|
|
src/app/shared/components/accordion/accordion.component.ts
|
component |
AccordionComponent |
0 %
(0/4)
|
|
src/app/shared/components/card-deck/card-deck.component.ts
|
component |
CardDeckComponent |
0 %
(0/13)
|
|
src/app/shared/components/card/card.component.ts
|
component |
CardComponent |
0 %
(0/10)
|
|
src/app/shared/components/forms/components/field-base/field-base.ts
|
injectable |
FieldBaseComponent |
0 %
(0/6)
|
|
src/app/shared/components/forms/components/form-button-group/form-button-group.component.ts
|
component |
FormButtonGroupComponent |
0 %
(0/6)
|
|
src/app/shared/components/forms/components/form-button/form-button.component.ts
|
component |
FormButtonComponent |
0 %
(0/5)
|
|
src/app/shared/components/forms/components/form-checkbox-list/form-checkbox-list.component.ts
|
component |
FormCheckboxListComponent |
0 %
(0/5)
|
|
src/app/shared/components/forms/components/form-checkbox/form-checkbox.component.ts
|
component |
FormCheckboxComponent |
0 %
(0/5)
|
|
src/app/shared/components/forms/components/form-date/form-date.component.ts
|
component |
FormDateComponent |
0 %
(0/5)
|
|
src/app/shared/components/forms/components/form-field-error/form-field-error.component.ts
|
component |
FormFieldErrorComponent |
0 %
(0/7)
|
|
src/app/shared/components/forms/components/form-file-path/form-file-path.component.ts
|
component |
FormFilePathComponent |
0 %
(0/5)
|
|
src/app/shared/components/forms/components/form-file/file-input.directive.ts
|
directive |
AppFileInputDirective |
0 %
(0/11)
|
|
src/app/shared/components/forms/components/form-file/file-input.directive.ts
|
variable |
APP_FILE_INPUT_ACCESSOR |
0 %
(0/1)
|
|
src/app/shared/components/forms/components/form-file/form-file.component.ts
|
component |
FormFileComponent |
0 %
(0/5)
|
|
src/app/shared/components/forms/components/form-input-group/form-input-group.component.ts
|
component |
FormInputGroupComponent |
0 %
(0/5)
|
|
src/app/shared/components/forms/components/form-input/form-input.component.ts
|
component |
FormInputComponent |
0 %
(0/5)
|
|
src/app/shared/components/forms/components/form-radio-list/form-radio-list.component.ts
|
component |
FormRadioListComponent |
0 %
(0/5)
|
|
src/app/shared/components/forms/components/form-select/form-select.component.ts
|
component |
FormSelectComponent |
0 %
(0/6)
|
|
src/app/shared/components/forms/components/form-textarea/form-textarea.component.ts
|
component |
FormTextareaComponent |
0 %
(0/5)
|
|
src/app/shared/components/forms/components/form-time/form-time.component.ts
|
component |
FormTimeComponent |
0 %
(0/5)
|
|
src/app/shared/components/forms/components/form/form.component.ts
|
component |
AppFormComponent |
0 %
(0/17)
|
|
src/app/shared/components/forms/directives/field-color-validation.directive.ts
|
directive |
FieldColorValidationDirective |
0 %
(0/4)
|
|
src/app/shared/components/forms/directives/form-field.directive.ts
|
directive |
FormFieldDirective |
0 %
(0/6)
|
|
src/app/shared/components/forms/directives/form-field.directive.ts
|
variable |
components |
0 %
(0/1)
|
|
src/app/shared/components/forms/forms.service.ts
|
injectable |
FormsService |
0 %
(0/26)
|
|
src/app/shared/components/grid/components/date-filter/date-filter.component.ts
|
component |
DateFilterComponent |
0 %
(0/8)
|
|
src/app/shared/components/grid/components/dropdown-filter/dropdown-filter.component.ts
|
component |
DropdownFloatingFilterComponent |
0 %
(0/8)
|
|
src/app/shared/components/grid/components/dropdown-filter/dropdown-filter.component.ts
|
interface |
DropdownFloatingFilterParams |
0 %
(0/3)
|
|
src/app/shared/components/grid/grid.component.ts
|
component |
GridComponent |
0 %
(0/17)
|
|
src/app/shared/components/grid/renderers/action-button/action-button.component.ts
|
component |
ActionButtonComponent |
0 %
(0/7)
|
|
src/app/shared/components/grid/renderers/action-buttons/action-buttons.component.ts
|
component |
ActionButtonsComponent |
0 %
(0/6)
|
|
src/app/shared/components/image-resizer/image-resizer.component.ts
|
component |
ImageResizerComponent |
0 %
(0/18)
|
|
src/app/shared/components/list/list.component.ts
|
component |
ListComponent |
0 %
(0/5)
|
|
src/app/shared/components/loading/loading.component.ts
|
component |
LoadingComponent |
0 %
(0/5)
|
|
src/app/shared/components/login-menu/login-menu.component.ts
|
component |
LoginMenuComponent |
0 %
(0/5)
|
|
src/app/shared/components/login/login.component.ts
|
component |
LoginComponent |
0 %
(0/11)
|
|
src/app/shared/components/login/login.component.ts
|
interface |
INavigationState |
0 %
(0/2)
|
|
src/app/shared/components/logout/logout.component.ts
|
component |
LogoutComponent |
0 %
(0/8)
|
|
src/app/shared/components/logout/logout.component.ts
|
interface |
INavigationState |
0 %
(0/2)
|
|
src/app/shared/components/modal/modal-template.directive.ts
|
directive |
ModalTemplateDirective |
50 %
(1/2)
|
|
src/app/shared/components/modal/modal.component.ts
|
component |
ModalComponent |
20 %
(1/5)
|
|
src/app/shared/components/page-heading/page-heading.component.ts
|
component |
PageHeadingComponent |
0 %
(0/3)
|
|
src/app/shared/components/search-input/search-input.component.ts
|
component |
SearchInputComponent |
0 %
(0/19)
|
|
src/app/shared/components/toast/toast.comonent.ts
|
component |
ToastComponent |
0 %
(0/4)
|
|
src/app/shared/components/toggle-switch/toggle-switch.component.ts
|
component |
ToggleSwitchComponent |
0 %
(0/8)
|
|
src/app/shared/components/typeahead/typeahead.component.ts
|
component |
TypeaheadComponent |
0 %
(0/6)
|
|
src/app/shared/constants/auth.constants.ts
|
interface |
ApplicationPathsType |
0 %
(0/21)
|
|
src/app/shared/constants/auth.constants.ts
|
variable |
ApplicationName |
0 %
(0/1)
|
|
src/app/shared/constants/auth.constants.ts
|
variable |
applicationPaths |
0 %
(0/1)
|
|
src/app/shared/constants/auth.constants.ts
|
variable |
ApplicationPaths |
0 %
(0/1)
|
|
src/app/shared/constants/auth.constants.ts
|
variable |
LoginActions |
0 %
(0/1)
|
|
src/app/shared/constants/auth.constants.ts
|
variable |
LogoutActions |
0 %
(0/1)
|
|
src/app/shared/constants/auth.constants.ts
|
variable |
QueryParameterNames |
0 %
(0/1)
|
|
src/app/shared/constants/auth.constants.ts
|
variable |
ReturnUrlType |
0 %
(0/1)
|
|
src/app/shared/models/accordion.ts
|
interface |
IAccordionItem |
0 %
(0/3)
|
|
src/app/shared/models/auth.ts
|
interface |
ForgotPassword |
0 %
(0/2)
|
|
src/app/shared/models/auth.ts
|
interface |
ResetPasswordToken |
0 %
(0/5)
|
|
src/app/shared/models/card.ts
|
interface |
ICard |
0 %
(0/5)
|
|
src/app/shared/models/card.ts
|
interface |
ICardEvent |
0 %
(0/3)
|
|
src/app/shared/models/forms.ts
|
interface |
Field |
0 %
(0/2)
|
|
src/app/shared/models/forms.ts
|
interface |
FieldOption |
0 %
(0/4)
|
|
src/app/shared/models/forms.ts
|
interface |
IFieldConfig |
0 %
(0/20)
|
|
src/app/shared/models/grid.ts
|
interface |
GridColumn |
0 %
(0/14)
|
|
src/app/shared/models/list.ts
|
interface |
IListItem |
0 %
(0/3)
|
|
src/app/shared/models/modal.ts
|
interface |
ModalOptions |
0 %
(0/13)
|
|
src/app/shared/models/nav.ts
|
interface |
NavItem |
0 %
(0/8)
|
|
src/app/shared/models/nav.ts
|
interface |
PageNav |
0 %
(0/3)
|
|
src/app/shared/pipes/group-by.pipe.ts
|
pipe |
GroupByPipe |
0 %
(0/1)
|
|
src/app/shared/pipes/safe.pipe.ts
|
pipe |
SafePipe |
0 %
(0/1)
|
|
src/app/shared/pipes/translate.pipe.ts
|
injectable |
TranslatePipe |
0 %
(0/3)
|
|
src/app/shared/pipes/translate.pipe.ts
|
pipe |
TranslatePipe |
0 %
(0/1)
|
|
src/app/shared/pipes/uppercase.pipe.ts
|
pipe |
UppercasePipe |
0 %
(0/1)
|
|
src/app/shared/services/app.service.ts
|
injectable |
AppService |
0 %
(0/3)
|
|
src/app/shared/services/app.service.ts
|
variable |
APP_DATA_KEY |
0 %
(0/1)
|
|
src/app/shared/services/authorize.service.ts
|
injectable |
AuthorizeService |
0 %
(0/19)
|
|
src/app/shared/services/authorize.service.ts
|
interface |
FailureAuthenticationResult |
0 %
(0/3)
|
|
src/app/shared/services/authorize.service.ts
|
interface |
IUser |
0 %
(0/3)
|
|
src/app/shared/services/authorize.service.ts
|
interface |
RedirectAuthenticationResult |
0 %
(0/2)
|
|
src/app/shared/services/authorize.service.ts
|
interface |
SuccessAuthenticationResult |
0 %
(0/3)
|
|
src/app/shared/services/config.service.ts
|
injectable |
ConfigService |
0 %
(0/4)
|
|
src/app/shared/services/custom-date-adapter.service.ts
|
injectable |
CustomNgbDateNativeUTCAdapter |
0 %
(0/3)
|
|
src/app/shared/services/custom-date-formatter.service.ts
|
injectable |
CustomDateFormatter |
0 %
(0/3)
|
|
src/app/shared/services/custom-date-formatter.service.ts
|
function |
isNumber |
0 %
(0/1)
|
|
src/app/shared/services/custom-date-formatter.service.ts
|
function |
padNumber |
0 %
(0/1)
|
|
src/app/shared/services/custom-date-formatter.service.ts
|
function |
toInteger |
0 %
(0/1)
|
|
src/app/shared/services/data.service.ts
|
injectable |
DataService |
0 %
(0/9)
|
|
src/app/shared/services/global-error.service.ts
|
injectable |
GlobalErrorHandler |
0 %
(0/4)
|
|
src/app/shared/services/guards/authorize.guard.ts
|
guard |
AuthorizeGuard |
0 %
(0/4)
|
|
src/app/shared/services/interceptors/auth.interceptor.ts
|
interceptor |
AuthInterceptor |
0 %
(0/3)
|
|
src/app/shared/services/interceptors/jwt.interceptor.ts
|
interceptor |
JwtInterceptor |
0 %
(0/5)
|
|
src/app/shared/services/interceptors/loading.interceptor.ts
|
interceptor |
LoadingInterceptor |
0 %
(0/5)
|
|
src/app/shared/services/interceptors/timing.interceptor.ts
|
interceptor |
TimingInterceptor |
0 %
(0/3)
|
|
src/app/shared/services/jwt-decode/jwthelper.service.ts
|
class |
JwtHelperService |
0 %
(0/8)
|
|
src/app/shared/services/loading.service.ts
|
injectable |
LoadingService |
0 %
(0/4)
|
|
src/app/shared/services/modal-state.service.ts
|
injectable |
ModalStateService |
100 %
(4/4)
|
|
src/app/shared/services/modal.service.ts
|
injectable |
ModalService |
50 %
(3/6)
|
|
src/app/shared/services/toast.service.ts
|
injectable |
ToastService |
0 %
(0/8)
|
|
src/app/shared/services/utils.service.ts
|
injectable |
UtilsService |
0 %
(0/5)
|
|
src/app/shared/shared.module.ts
|
function |
appServiceFactory |
0 %
(0/1)
|
|
src/environments/environment.prod.ts
|
variable |
environment |
0 %
(0/1)
|
|
src/environments/environment.ts
|
variable |
environment |
0 %
(0/1)
|
|
src/jestGlobalMocks.ts
|
variable |
mock |
0 %
(0/1)
|
|
src/main.ts
|
function |
getBaseUrl |
0 %
(0/1)
|
|
src/main.ts
|
variable |
providers |
0 %
(0/1)
|


map Class
A "class" defining a map with recommended restaurants
Constructor
map
()
Item Index
Methods
Properties
Methods
addEventListener
()
Listens to a showButton's click event
addEventListener
()
Listens to a hideButton's click event
clearMarkers
()
Hides the markers on the map
createMapMarker
(
-
placeData
Creates markers and infoWindows for each of the locations, sets map's center and bounds and animates the marker when clicked
Parameters:
-
placeData
ObjectThe filtered place recommended by Foursquare that matches markers and infoWindows which is going to be rendered on Google Maps
pinPoster
(
-
locations
Creates an instance of Google Maps Places
Parameters:
-
locations
ObjectThe filtered place recommended by Foursquare that matches markers and infoWindows which is going to be rendered on Google Maps
setAllMap
(
-
map
Updates the map
Parameters:
-
map
Object
showMarkers
()
Shows the markers on the map
Properties
OK denotes the success of the request
Unknown
Retrieves the result of the query for each of the locations
Sub-properties:
-
results
Objectquery results from Google Maps Places


{% filter markdown %}
# About P7PP
P7PP, codename `web-pp`, is a Web port of [`alfred-pp`][alfred-pp], a
workflow for [Alfred][alfred] on Mac OS X which allows one to quickly go on a
teacher's page using a few keystrokes. Data is fetched from the Web only once,
and then stored locally.
This implementation allows anyone to use `pp`. It works exactly the same way as
the original one.
[alfred-pp]: https://github.com/bfontaine/alfred-pp#readme
[alfred]: http://www.alfredapp.com/
## How to use it
Start typing a teacher's name in the box. It'll suggest you some names. The
first one is highlighted by default, and you can move using up and down arrows.
Press enter to open the selected teacher's personal page.
Additionally, pressing ctrl and enter at the same time
opens the page in a new tab instead of using the current one (you can use
shift if you prefer, or cmd on OS X). Press
tab to replace your input with the selected teacher's name.
You can also use the good ol' mouse, but the goal is to save your time, this is
why the box has already the focus when you open P7PP.
See more on the [wiki][].
[wiki]: https://github.com/bfontaine/web-pp/wiki
## How it works
The application is written in Python (using Flask and Gunicorn), and uses Redis
to store some info. Every night around 4AM, it fetches LIAFA, PPS and Gallium
member lists, extract some info from them (at least each name and webpage URL),
and store them locally. It also performs some lexical transformations to
facilitate search operations later.
When you go on the app, it serves you the most up to date people list and the
all the code it needs. The search is done on the client side to avoid
unecessary requests.
The JavaScript code uses [AngularJS][ng] for the suggestions rendering and
[Mousetrap][mt] for keyboard shortcuts. All the code is agressively compressed
to speed up loading time.
Everything is available on [GitHub][ppgh].
[ng]: https://angularjs.org/
[mt]: http://craig.is/killing/mice
[ppgh]: https://github.com/bfontaine/web-pp
## Who did that?
Hi! I'm [Baptiste Fontaine][bf], currently doing a M.Sc. in Computer Science at
Paris Diderot University. I wrote `alfred-pp` for my personal usage, and
[someone][jch] suggested me to adapt the code and put it online for everybody.
Here is it ;)
[bf]: http://bfontaine.net
[jch]: http://www.pps.univ-paris-diderot.fr/~jch/
[gh]: https://github.com/bfontaine
## More Help
Someone's missing? You have more questions? Drop me an email, I usually respond
under a few days.
{% endfilter %}


These templates are not finished articles, they are just a starting point skeleton template using the default Tailwind CSS styling (served via the CDN) - which you can turn into your own creation.
Simple skeleton/boilerplate template to copy/paste into your editor
Admin template to use for Admin theme, dashboard, or web application
Blog homepage in style of the default Casper theme for Ghost
Blog post template in style of the default Casper theme for Ghost
Minimal monochrome blog post template, with a splash of colour
Hero section - two columns for large screens and two rows for small screens
Basic template with sidebar which becomes fixed bottom menu
Basic template with container for content and fixed header
Basic template with container for content and toggle buttom responsive menu
Advertisment
A versatile homepage template
Ross McNeil / digizu.co.uk
An online store homepage template


State Statistics
Select a State
Total Population
{{formatPopulation(totalPopulation)}}
Gender Statistics
Age Statistics
Ethnicity Statistics
Weight Statistics
Height Statistics
Waist Statistics
BMI Statistics
Waist to Height Statistics
Heart Rate Statistics
Cholesterol Statistics
Blood Presure Statistics


General Settings
Favorites
Logout
General Account Settings
Firstname
Lastname
Email
Location
Country
Change Password
Current Password
New Password
Confirm Password


{% extends 'video_games/base.html' %} {% block content %}
Are you sure you want to delete the Video Game "{{ game.game_name }}"?


--- title: Error 404 Not Found permalink: 404.html layout: content.njk ogtype: website eleventyExcludeFromCollections: true ---


|
My Project
|
A shape is used for collision detection. You can create a shape however you like. Shapes used for simulation in World are created automatically when a Fixture is created. Shapes may encapsulate a one or more child shapes. More...
Public Member Functions | |
| abstract Shape | Clone () |
| Clone the concrete shape More... | |
| abstract bool | TestPoint (ref Transform transform, ref Vector2 point) |
| Test a point for containment in this shape. Note: This only works for convex shapes.  More... | |
| abstract void | ComputeAABB (out AABB aabb, ref Transform transform, int childIndex) |
| Given a transform, compute the associated axis aligned bounding box for a child shape. More... | |
| abstract float | ComputeSubmergedArea (ref Vector2 normal, float offset, ref Transform xf, out Vector2 sc) |
| Used for the buoyancy controller More... | |
Public Attributes | |
| MassData | MassData |
| Contains the properties of the shape such as: More... | |
Protected Member Functions | |
| Shape (float density) | |
| abstract void | ComputeProperties () |
| Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid. More... | |
Properties | |
| ShapeType | ShapeType [get, set] |
| Get the type of this shape. More... | |
| abstract int | ChildCount [get] |
| Get the number of child primitives. More... | |
| float | Density [get, set] |
| Gets or sets the density. Changing the density causes a recalculation of shape properties. More... | |
| float | Radius [get, set] |
| Radius of the Shape Changing the radius causes a recalculation of shape properties. More... | |
A shape is used for collision detection. You can create a shape however you like. Shapes used for simulation in World are created automatically when a Fixture is created. Shapes may encapsulate a one or more child shapes.
|
pure virtual |
Clone the concrete shape
Implemented in tainicom.Aether.Physics2D.Collision.Shapes.PolygonShape, tainicom.Aether.Physics2D.Collision.Shapes.EdgeShape, tainicom.Aether.Physics2D.Collision.Shapes.CircleShape, and tainicom.Aether.Physics2D.Collision.Shapes.ChainShape.
|
pure virtual |
Given a transform, compute the associated axis aligned bounding box for a child shape.
| aabb | The aabb results. |
| transform | The world transform of the shape. |
| childIndex | The child shape index. |
Implemented in tainicom.Aether.Physics2D.Collision.Shapes.PolygonShape, tainicom.Aether.Physics2D.Collision.Shapes.EdgeShape, tainicom.Aether.Physics2D.Collision.Shapes.CircleShape, and tainicom.Aether.Physics2D.Collision.Shapes.ChainShape.
|
protectedpure virtual |
Compute the mass properties of this shape using its dimensions and density. The inertia tensor is computed about the local origin, not the centroid.
Implemented in tainicom.Aether.Physics2D.Collision.Shapes.PolygonShape, tainicom.Aether.Physics2D.Collision.Shapes.EdgeShape, tainicom.Aether.Physics2D.Collision.Shapes.CircleShape, and tainicom.Aether.Physics2D.Collision.Shapes.ChainShape.
|
pure virtual |
Used for the buoyancy controller
Implemented in tainicom.Aether.Physics2D.Collision.Shapes.PolygonShape, tainicom.Aether.Physics2D.Collision.Shapes.EdgeShape, tainicom.Aether.Physics2D.Collision.Shapes.CircleShape, and tainicom.Aether.Physics2D.Collision.Shapes.ChainShape.
|
pure virtual |
Cast a ray against a child shape.
| output | The ray-cast results. |
| input | The ray-cast input parameters. |
| transform | The transform to be applied to the shape. |
| childIndex | The child shape index. |
Implemented in tainicom.Aether.Physics2D.Collision.Shapes.PolygonShape, tainicom.Aether.Physics2D.Collision.Shapes.EdgeShape, tainicom.Aether.Physics2D.Collision.Shapes.CircleShape, and tainicom.Aether.Physics2D.Collision.Shapes.ChainShape.
|
pure virtual |
Test a point for containment in this shape. Note: This only works for convex shapes.
| transform | The shape world transform. |
| point | A point in world coordinates. |
Implemented in tainicom.Aether.Physics2D.Collision.Shapes.PolygonShape, tainicom.Aether.Physics2D.Collision.Shapes.EdgeShape, tainicom.Aether.Physics2D.Collision.Shapes.CircleShape, and tainicom.Aether.Physics2D.Collision.Shapes.ChainShape.
| MassData tainicom.Aether.Physics2D.Collision.Shapes.Shape.MassData |
Contains the properties of the shape such as:
|
get |
Get the number of child primitives.
|
getset |
Gets or sets the density. Changing the density causes a recalculation of shape properties.
The density.
|
getset |
Radius of the Shape Changing the radius causes a recalculation of shape properties.
|
getset |
Get the type of this shape.
The type of the shape.


Atomically return and remove the first (LPOP) or last (RPOP) elementof the list. For example if the list contains the elements "a","b","c" LPOPwill return "a" and the list will become "b","c".
If the key does not exist or the list is already empty the specialvalue 'nil' is returned.


Are you sure you want to make this user an admin? This will allow the user to invite new members and remove existing members.

We built this tool because we didn't want to use a bloated CRM for our own profitability tracking. We hope you find it useful as well.
We'd love to hear what you think. Your input will have a direct impact on this product.


Number of medals stolen from Meath footballer Graham Geraghty recovered
13 GAA championship medals found by man walking home for lunch in Wicklow
A number of GAA medals stolen during a break-in at the home of Meath’s football legend Graham Geraghty have been recovered.
A total of 13 championship medals were found by a man walking home for lunch in Arklow, Co Wicklow on Wednesday, according to Mr Geraghty’s wife Amanda
The medals were found in a bag on the footpath
Unfortunately the recovered haul did not contain the former Meath captain’s five Leinster medals or his Railway Cup ones.
In a post on her Facebook page, Ms Geraghty said: “Unfortunately his five Leinster medals are still missing probably because they are gold but we will keep praying to Saint Anthony.”
Speaking this morning, she said: “We are delighted to get the 13 medals back but we will continue to hope and pray that we will get the Leinster and Railway Cup ones returned
“The medals were found in Arklow so we are appealing now to anyone around the whole country who might see them or be offered them for sale either on their own or through a cash for gold outlet to contact gardaí.
“We would also like to sincerely thank the man and his father who recognised the medals as Grahams.
“He was walking home for lunch and spotted a blue bag with medals at the side of the footpath
“They were still there later so he took the home. They were covered in an oily residue and as he was washing them, his father noticed they were Meath medals.”
The older man had read about the theft of Mr Geraghty’s medals and said that they might belong to him. He contacted Ms Geraghty through Facebook.
“We would like to say a huge thank you to them,” she said.
Mr Geraghty said captained Meath to the last All-Ireland success in 1999 at Croke Park against Cork
The medals were taken during a break in at their home outside Athboy, while their three children were asleep last Friday night.
At the time, in offering a reward for their return, Ms Geraghty said: “They are not worth much in monetary value but it took blood, sweat and tears to win these over a period of eleven years - one minor, two under 21s and three senior medals
“A lifetime of memories taken. We will gladly give you what the cash for gold shops will give you for them.”


Code Coverage |
|||||||||
Lines |
Functions and Methods |
Classes and Traits |
|||||||
| Total | |
94.63% |
2432 / 2570 |
|
95.29% |
263 / 276 |
|
91.43% |
32 / 35 |
| Test | |
100.00% |
1412 / 1412 |
|
100.00% |
96 / 96 |
|
100.00% |
19 / 19 |
| Autoloader.php | |
100.00% |
28 / 28 |
|
100.00% |
4 / 4 |
|
100.00% |
1 / 1 |
| Checker.php | |
100.00% |
99 / 99 |
|
100.00% |
16 / 16 |
|
100.00% |
1 / 1 |
| Command.php | |
70.42% |
100 / 142 |
|
83.33% |
15 / 18 |
|
0.00% |
0 / 1 |
| CommandArg.php | |
100.00% |
93 / 93 |
|
100.00% |
18 / 18 |
|
100.00% |
1 / 1 |
| CommandArrange.php | |
66.88% |
107 / 160 |
|
57.89% |
11 / 19 |
|
0.00% |
0 / 1 |
| CommandArrangeComp.php | |
100.00% |
14 / 14 |
|
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
| CommandComponent.php | |
100.00% |
40 / 40 |
|
100.00% |
15 / 15 |
|
100.00% |
1 / 1 |
| CommandDemo.php | |
100.00% |
35 / 35 |
|
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
| CommandDoubleDash.php | |
100.00% |
12 / 12 |
|
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
| CommandMessenger.php | |
100.00% |
82 / 82 |
|
100.00% |
16 / 16 |
|
100.00% |
1 / 1 |
| CommandOpt.php | |
100.00% |
115 / 115 |
|
100.00% |
10 / 10 |
|
100.00% |
1 / 1 |
| CommandOptGrp.php | |
100.00% |
55 / 55 |
|
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
| GuidCommand.php | |
0.00% |
0 / 43 |
|
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
| GuidGenerator.php | |
100.00% |
20 / 20 |
|
100.00% |
7 / 7 |
|
100.00% |
1 / 1 |
| UnitTestSupport.php | |
100.00% |
79 / 79 |
|
100.00% |
16 / 16 |
|
100.00% |
1 / 1 |
| UsageFormatter.php | |
100.00% |
141 / 141 |
|
100.00% |
22 / 22 |
|
100.00% |
1 / 1 |


DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.
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 < ApplicationRecord
validates :name, presence: true
end
irb> Person.create(name: "John Doe").valid?
=> true
irb> 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 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 and 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 Active Record class:
class Person < ApplicationRecord
end
We can see how it works by looking at some bin/rails console
output:
irb> p = Person.new(name: "John Doe")
=> #<Person id: nil, name: "John Doe", created_at: nil, updated_at: nil>
irb> p.new_record?
=> true
irb> p.save
=> true
irb> 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
, and
create
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
insert
insert!
insert_all
insert_all!
toggle!
touch
touch_all
update_all
update_attribute
update_column
update_columns
update_counters
upsert
upsert_all
Note that save
also has the ability to skip validations if passed validate:
false
as an argument. This technique should be used with caution.
save(validate: false)
valid?
and invalid?
Before saving an Active Record object, Rails runs your validations. If these validations produce any errors, Rails does not save the object.
You can also run these validations 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 < ApplicationRecord
validates :name, presence: true
end
irb> Person.create(name: "John Doe").valid?
=> true
irb> Person.create(name: nil).valid?
=> false
After Active Record has performed validations, any errors found can be accessed
through the errors
instance method, which returns a collection of errors.
By definition, an object is valid if this collection is empty after running
validations.
Note that an object instantiated with new
will not report errors
even if it's technically invalid, because validations are automatically run
only when the object is saved, such as with the create
or save
methods.
class Person < ApplicationRecord
validates :name, presence: true
end
irb> p = Person.new
=> #<Person id: nil, name: nil>
irb> p.errors.size
=> 0
irb> p.valid?
=> false
irb> p.errors.objects.first.full_message
=> "Name can't be blank"
irb> p = Person.create
=> #<Person id: nil, name: nil>
irb> p.errors.objects.first.full_message
=> "Name can't be blank"
irb> p.save
=> false
irb> p.save!
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
irb> Person.create!
ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
invalid?
is 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 error messages 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 < ApplicationRecord
validates :name, presence: true
end
irb> Person.new.errors[:name].any?
=> false
irb> Person.create.errors[:name].any?
=> true
We'll cover validation errors in greater depth in the Working with Validation Errors section.
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 is added to the object's
errors
collection, and this 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 that some text is read, or any similar concept.
class Person < ApplicationRecord
validates :terms_of_service, acceptance: true
end
This check is performed only if terms_of_service
is not nil
.
The default error message for this helper is "must be accepted".
You can also pass in a custom message via the message
option.
class Person < ApplicationRecord
validates :terms_of_service, acceptance: { message: 'must be abided' }
end
It can also receive an :accept
option, which determines the allowed values
that will be considered as accepted. It defaults to ['1', true]
and can be
easily changed.
class Person < ApplicationRecord
validates :terms_of_service, acceptance: { accept: 'yes' }
validates :eula, acceptance: { accept: ['TRUE', 'accepted'] }
end
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 create a virtual attribute. If
the field does exist in your database, the accept
option must be set to
or include true
or else the validation will not run.
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 < ApplicationRecord
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 < ApplicationRecord
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 in this guide):
class Person < ApplicationRecord
validates :email, confirmation: true
validates :email_confirmation, presence: true
end
There is also a :case_sensitive
option that you can use to define whether the
confirmation constraint will be case sensitive or not. This option defaults to
true.
class Person < ApplicationRecord
validates :email, confirmation: { case_sensitive: false }
end
The default error message for this helper is "doesn't match confirmation".
comparison
This check will validate a comparison between any two comparable values. The validator requires a compare option be supplied. Each option accepts a value, proc, or symbol. Any class that includes Comparable can be compared.
class Promotion < ApplicationRecord
validates :start_date, comparison: { greater_than: :end_date }
end
These options are all supported:
: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 to the supplied value. The default error message for this option is "must be less than or equal to %count
".:other_than
- Specifies the value must be other than the supplied value. The default error message for this option is "must be other than %count
".
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 < ApplicationRecord
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. For full options to the message argument please see the
message documentation.
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 < ApplicationRecord
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 < ApplicationRecord
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. For full
options please see the message documentation.
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 < ApplicationRecord
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 customize 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 < ApplicationRecord
validates :bio, length: { maximum: 1000,
too_long: "%{count} characters is the maximum allowed" }
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 custom message or use presence: true
instead. When
:in
or :within
have a lower limit of 1, you should either provide a
custom 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 integer or floating point number.
To specify that only integer numbers are allowed,
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
. Float
s are casted to BigDecimal
using the column's precision value or 15.
class Player < ApplicationRecord
validates :points, numericality: true
validates :games_played, numericality: { only_integer: true }
end
The default error message for :only_integer
is "must be an integer".
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 to the supplied value. The default error message for this option is "must be less than or equal to %count
".:other_than
- Specifies the value must be other than the supplied value. The default error message for this option is "must be other than %count
".:in
- Specifies the value must be in the supplied range. The default error message for this option is "must be in %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".
NOTE: By default, numericality
doesn't allow nil
values. You can use allow_nil: true
option to permit it.
The default error message when no options are specified 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 < ApplicationRecord
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. This way, it is not only checked that the foreign key is not empty but also that the referenced object exists.
class Supplier < ApplicationRecord
has_one :account
validates :account, presence: true
end
In order to validate associated records whose presence is required, you must
specify the :inverse_of
option for the association:
NOTE: If you want to ensure that the association it is both present and valid, you also need to use validates_associated
.
class Order < ApplicationRecord
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, inclusion: [true, false]
validates :boolean_field_name, exclusion: [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 < ApplicationRecord
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 < ApplicationRecord
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 < ApplicationRecord
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 that column in your database.
class Account < ApplicationRecord
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 one or more attributes that
are used to limit the uniqueness check:
class Holiday < ApplicationRecord
validates :name, uniqueness: { scope: :year,
message: "should happen once per year" }
end
Should you wish to create a database constraint to prevent possible violations of a uniqueness validation using the :scope
option, you must create a unique index on both columns in your database. See the MySQL manual for more details about multiple column indexes or the PostgreSQL manual for examples of unique constraints that refer to a group of columns.
There is also a :case_sensitive
option that you can use to define whether the uniqueness constraint will be case sensitive, case insensitive, or respects default database collation. This option defaults to respects default database collation.
class Person < ApplicationRecord
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.add :base, "This person is evil"
end
end
end
class Person < ApplicationRecord
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 [:fields].any? { |field| record.send(field) == "Evil" }
record.errors.add :base, "This person is evil"
end
end
end
class Person < ApplicationRecord
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 < ApplicationRecord
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.add :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 < ApplicationRecord
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 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 < ApplicationRecord
validates :size, inclusion: { in: %w(small medium large),
message: "%{value} is not a valid size" }, allow_nil: true
end
For full options to the message argument please see the message documentation.
: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 < ApplicationRecord
validates :title, length: { is: 5 }, allow_blank: true
end
irb> Topic.create(title: "").valid?
=> true
irb> 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. The :message
option accepts a String
or Proc
.
A String
:message
value can optionally contain any/all of %{value}
,
%{attribute}
, and %{model}
which will be dynamically replaced when
validation fails. This replacement is done using the I18n gem, and the
placeholders must match exactly, no spaces are allowed.
A Proc
:message
value is given two arguments: the object being validated, and
a hash with :model
, :attribute
, and :value
key-value pairs.
class Person < ApplicationRecord
# Hard-coded message
validates :name, presence: { message: "must be given please" }
# Message with dynamic attribute value. %{value} will be replaced
# with the actual value of the attribute. %{attribute} and %{model}
# are also available.
validates :age, numericality: { message: "%{value} seems wrong" }
# Proc
validates :username,
uniqueness: {
# object = person object being validated
# data = { model: "Person", attribute: "Username", value: <username> }
message: ->(object, data) do
"Hey #{object.name}, #{data[:value]} is already taken."
end
}
end
: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 < ApplicationRecord
# 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
You can also use on:
to define custom contexts. Custom contexts need to be
triggered explicitly by passing the name of the context to valid?
,
invalid?
, or save
.
class Person < ApplicationRecord
validates :email, uniqueness: true, on: :account_setup
validates :age, numericality: true, on: :account_setup
end
irb> person = Person.new(age: 'thirty-three')
irb> person.valid?
=> true
irb> person.valid?(:account_setup)
=> false
irb> person.errors.messages
=> {:email=>["has already been taken"], :age=>["is not a number"]}
person.valid?(:account_setup)
executes both the validations without saving
the model. person.save(context: :account_setup)
validates person
in the
account_setup
context before saving.
When triggered by an explicit context, validations are run for that context, as well as any validations without a context.
class Person < ApplicationRecord
validates :email, uniqueness: true, on: :account_setup
validates :age, numericality: true, on: :account_setup
validates :name, presence: true
end
irb> person = Person.new
irb> person.valid?(:account_setup)
=> false
irb> person.errors.messages
=> {:email=>["has already been taken"], :age=>["is not a number"], :name=>["can't be blank"]}
Strict Validations
You can also specify validations to be strict and raise
::ActiveModel::StrictValidationFailed
when the object is invalid.
class Person < ApplicationRecord
validates :name, presence: { strict: true }
end
irb> Person.new.valid?
ActiveModel::StrictValidationFailed: Name can't be blank
There is also the ability to pass a custom exception to the :strict
option.
class Person < ApplicationRecord
validates :token, presence: true, uniqueness: true, strict: TokenGenerationException
end
irb> 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 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 < ApplicationRecord
validates :card_number, presence: true, if: :paid_with_card?
def paid_with_card?
payment_type == "card"
end
end
Using a Proc with :if
and :unless
It is 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 < ApplicationRecord
validates :password, confirmation: true,
unless: Proc.new { |a| a.password.blank? }
end
As Lambdas
are a type of Proc
, they can also be used to write inline
conditions in a shorter way.
validates :password, confirmation: true, unless: -> { password.blank? }
Grouping Conditional Validations
Sometimes it is useful to have multiple validations use one condition. It can
be easily achieved using with_options
.
class User < ApplicationRecord
if: :is_admin? do |admin|
admin.validates :password, length: { minimum: 10 }
admin.validates :email, presence: true
end
end
All validations inside of the 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 < ApplicationRecord
validates :mouse, presence: true,
if: [Proc.new { |c| c.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 inherit from ::ActiveModel::Validator
. These
classes must implement the 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.start_with? 'X'
record.errors.add :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.add attribute, ( [: ] || "is not an email")
end
end
end
class Person < ApplicationRecord
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
errors to the errors
collection when they are invalid. You must then
register these methods by using the validate
class method, passing in the symbols for the validation methods' names.
You can pass more than one symbol for each class method and the respective validations will be run in the same order as they were registered.
The valid?
method will verify that the errors
collection is empty,
so your custom validation methods should add errors to it when you
wish validation to fail:
class Invoice < ApplicationRecord
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?
or save the object. But 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 < ApplicationRecord
validate :active_customer, on: :create
def active_customer
errors.add(:customer_id, "is not active") unless customer.active?
end
end
Working with Validation Errors
The valid?
and invalid?
methods only provide a summary status on validity. However you can dig deeper into each individual error by using various methods from the errors
collection.
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
The gateway through which you can drill down into various details of each error.
This returns an instance of the class ::ActiveModel::Errors
containing all errors,
each error is represented by an ::ActiveModel::Error
object.
class Person < ApplicationRecord
validates :name, presence: true, length: { minimum: 3 }
end
irb> person = Person.new
irb> person.valid?
=> false
irb> person.errors.full_messages
=> ["Name can't be blank", "Name is too short (minimum is 3 characters)"]
irb> person = Person.new(name: "John Doe")
irb> person.valid?
=> true
irb> person.errors.full_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 < ApplicationRecord
validates :name, presence: true, length: { minimum: 3 }
end
irb> person = Person.new(name: "John Doe")
irb> person.valid?
=> true
irb> person.errors[:name]
=> []
irb> person = Person.new(name: "JD")
irb> person.valid?
=> false
irb> person.errors[:name]
=> ["is too short (minimum is 3 characters)"]
irb> person = Person.new
irb> person.valid?
=> false
irb> person.errors[:name]
=> ["can't be blank", "is too short (minimum is 3 characters)"]
errors.where
and Error Object
Sometimes we may need more information about each error besides its message. Each error is encapsulated as an ::ActiveModel::Error
object, and the where
method is the most common way of access.
where
returns an array of error objects filtered by various degrees of conditions.
class Person < ApplicationRecord
validates :name, presence: true, length: { minimum: 3 }
end
irb> person = Person.new
irb> person.valid?
=> false
irb> person.errors.where(:name)
=> [ ... ] # all errors for :name attribute
irb> person.errors.where(:name, :too_short)
=> [ ... ] # :too_short errors for :name attribute
You can read various information from these error objects:
irb> error = person.errors.where(:name).last
irb> error.attribute
=> :name
irb> error.type
=> :too_short
irb> error.options[:count]
=> 3
You can also generate the error message:
irb> error.message
=> "is too short (minimum is 3 characters)"
irb> error.full_message
=> "Name is too short (minimum is 3 characters)"
The full_message
method generates a more user-friendly message, with the capitalized attribute name prepended. (To customize the format that full_message
uses, see the I18n guide.)
errors.add
The add
method creates the error object by taking the attribute
, the error type
and additional options hash. This is useful for writing your own validator.
class Person < ApplicationRecord
validate do |person|
errors.add :name, :too_plain, message: "is not cool enough"
end
end
irb> person = Person.create
irb> person.errors.where(:name).first.type
=> :too_plain
irb> person.errors.where(:name).first.full_message
=> "Name is not cool enough"
errors[:base]
You can add errors that are related to the object's state as a whole, instead of being related to a specific attribute. You can add errors to :base
when you want to say that the object is invalid, no matter the values of its attributes.
class Person < ApplicationRecord
validate do |person|
errors.add :base, :invalid, message: "This person is invalid because ..."
end
end
irb> person = Person.create
irb> person.errors.where(:base).first.full_message
=> "This person is invalid because ..."
errors.clear
The clear
method is used when you intentionally want to clear 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 < ApplicationRecord
validates :name, presence: true, length: { minimum: 3 }
end
irb> person = Person.new
irb> person.valid?
=> false
irb> person.errors.empty?
=> false
irb> person.errors.clear
irb> person.errors.empty?
=> true
irb> person.save
=> false
irb> person.errors.empty?
=> false
errors.size
The size
method returns the total number of errors for the object.
class Person < ApplicationRecord
validates :name, presence: true, length: { minimum: 3 }
end
irb> person = Person.new
irb> person.valid?
=> false
irb> person.errors.size
=> 2
irb> person = Person.new(name: "Andrea", email<EMAIL_ADDRESS>irb> person.valid?
=> true
irb> 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 fails.
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, you can 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:
<% if @article.errors.any? %>
<div id="error_explanation">
<h2><%=<EMAIL_ADDRESS>"error") %> prohibited this article from being saved:</h2>
<ul>
<% @article.errors.each do |error| %>
<li><%= error.full_message %></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.


Nottinghamshire Post Office is up for sale - and a retailer is wanted to take over
'We understand how important a Post Office is to a community'
by Ben ReidA Nottinghamshire Post Office has been put up for sale - and a new retailer is wanted to take it on.
Stapleford Post Office's current Post Master is resigning from the position and the branch will continue to trade until April.
If a replacement permanent Post Master is not found before April, the Post Office will look at other ways to try to maintain services in the area.
The Derby Road site takes an estimated £20,500 to £25,600 in fees per year.
Retailers running a Post Office do not have to pay franchise fees and equipment is paid and staff will be trained.
A Post Office spokesperson said: "We would like to reassure customers that we are committed to providing a Post Office in Stapleford.
"We have recently received a resignation from the operator for Stapleford Post Office. The branch will continue to trade until April.
“We understand how important a Post Office is to a community.
“Any retailer or small business owner interested in running the Post Office and incorporating it into their business should visit www.runapostoffice.co.uk email<EMAIL_ADDRESS>or phone 0333 345 5560, then select option 2. The vacancy is on our Run A Post Office website.”


My Dairy
Home
Sign up
Sign in
RESET PASSWORD
Submit your email to have a recovery link sent to your inbox.
SEND RECOVERY EMAIL


Howdy y’all!
The basis for this new design and adventure of automation all started with a random late night at Upwork preparing for a massive site “forklift” to AWS from our very outdated datacenter. I knew vacation would be needed after said migration. So I booked and began my 15 day vacation to Iceland, Germany & Spain for a few days after 48 hours of zero downtime. On my flight to Germany, I decided to re-launch all of thehar.com into a static site and to dog food
it myself.
Lets get started. First things first, DNS. Cloudflare offers a free service tier and will terminate SSL for you. Sure there’s LetsEncrypt
, but this is more fun and you can make your site more robust in the future. Lets make Cloudflare authoritative for the entire domain and proxy off www/non-www to S3. I’d like to not worry about uploading
or removing
content and re-generating all the static content all the time, so lets use AWS Lambda to do our dirty work. Lambda will do all of the things you tell it to in AWS “without server(s)”” or will orchestrate things for you. The biggest thing here is that you pay for the time spent reacting or processing. You don’t have to turn up completely new EC2 nodes or use Chef (like I normally would).
In order to get this working, we’ll need to have an input
bucket in S3 that you can put your non-generated assets into. I suggest input.domainname.com
just for ease of remembering what the hell these things are when you open S3’s console. Next you’ll need to create two buckets in S3 to serve up www.domainname.com
and domainname.com
. I prefer to keep things on the root domain and not serve up www traffic to everyone, although you can re-direct however you’d like. One bucket needs to forward to the other in some shape or form S3’s silliness.
Testing Hugo locally:
I make the assumption that all of your local development is done on MacOS, 10.12.3.
Dependencies
Homebrew
Cloudflare
Amazon Web Services (AWS)
When you’re ready to test out your changes and run a local web server, feel free to open Terminal.app and run:
hugo server -wvD --port 1313
.
Options tagged off demonizing hugo above:
-w means to watch the directory and recreate as needed.
-v means to verbosely state what is going on in the web server.
-D means to include drafted posts you may have created.
-1313 means to serve everything on port 1313.
Troubleshooting your hugo site
- Purge the public/ directory.
- Run the built in web server in watch mode.
- Open your site in a browser.
- Update the theme/content.
- Glance at your browser window to see changes.
- Rinse/repeat step 4.
Contributing
- Create a local branch to push to Github:
git checkout -b new_post_branch
- Create a new issue on https://www.github.com/thehar/www/issues/new
- Push your branch to Github:
git push origin new_post_branch
- Create a pull request https://www.github.com/thehar/www/pr/new


HANGMAN
Press any key to continue
Wins
current Word
NUmber of guesses remaining
10
Guessed Letters
Guess the country name


--- layout: post title: "Test Data Builders in C#" description: "A brief recap of the Test Data Builder design pattern with examples in C#." date: 2017-08-15 6:20 UTC tags: [Unit Testing, Design Patterns] --- {% include JB/setup %}
{{ page.description }}
This is the first in a series of articles about the relationship between the Test Data Builder design pattern, and the identity functor.
In 2007 Nat Pryce described the Test Data Builder design pattern. The original article is easy to read, but in case you don't want to read it, here's a quick summary, with some of Nat Pryce's examples translated to C#.
The purpose of a Test Data Builder is to make it easy to create input data (or objects) for unit tests. Imagine, for example, that for a particular test case, you need an address in Paris; no other values matter. With a Test Data Builder, you can write an expression that gives you such a value:
var address = new AddressBuilder().WithCity("Paris").Build();
The address
object explicity has a City
value of "Paris"
. Any other values are default values defined by AddressBuilder
. The values are there, but when they're unimportant to a particular test case, you don't have to specify them. To paraphrase Robert C. Martin, this eliminates the irrelevant, and amplifies the essentials of the test.
An AddressBuilder
could look like this:
public class AddressBuilder { private string street; private string city; private PostCode postCode; public AddressBuilder() { this.street = ""; this.city = ""; this.postCode = new PostCodeBuilder().Build(); } public AddressBuilder WithStreet(string newStreet) { this.street = newStreet; return this; } public AddressBuilder WithCity(string newCity) { this.city = newCity; return this; } public AddressBuilder WithPostCode(PostCode newPostCode) { this.postCode = newPostCode; return this; } public AddressBuilder WithNoPostcode() { this.postCode = new PostCode(); return this; } public Address Build() { return new Address(this.street, this.city, this.postCode); } }
The Address
class is simpler than the Builder:
public class Address { public string Street { get; set; } public string City { get; set; } public PostCode PostCode { get; set; } public Address(string street, string city, PostCode postCode) { this.Street = street; this.City = city; this.PostCode = postCode; } }
Clearly, this class could contain some behaviour, but in order to keep the example as simple as possible, it's only a simple Data Transfer Object.
Given that AddressBuilder
is more complicated than Address
itself, the benefit of the pattern may seem obscure, but one of the benefits is that Test Data Builders easily compose:
var invoice = new InvoiceBuilder() .WithRecipient(new RecipientBuilder() .WithAddress(new AddressBuilder() .WithNoPostcode() .Build()) .Build()) .Build();
Perhaps that looks verbose, but in general, the alternative is worse. If you didn't have a Test Utility Method, you'd have to fill in all the required data for the object:
var invoice = new Invoice( new Recipient("Sherlock Holmes", new Address("221b Baker Street", "London", new PostCode())), new List<InvoiceLine> { new InvoiceLine("Deerstalker Hat", new PoundsShillingsPence(0, 3, 10)), new InvoiceLine("Tweed Cape", new PoundsShillingsPence(0, 4, 12))});
Here, the important detail drowns in data. The post code is empty because the PostCode
constructor is called without arguments. This hardly jumps out when you see it. Such code neither eliminates the irrelevant, nor amplifies the essential.
Test Data Builders are useful because they are good abstractions. They enable you to write unit tests that you can trust.
The disadvantage, as you shall see, is that in languages like C# and Java, much boilerplate code is required.
Comments
So first off, great article as always. You totally hit a subject which has been driving me nuts, personally and lately. I have been developing my first FluentAPI and have been running up against both aspects of immutability and query/command separation that you have done an excellent job of presenting here on your blog. It does seem that FluentAPI design and the builder pattern you present above deviate from these principles, so it would be great to hear a little more context and valuable insight from you on how you reconcile this. Is this perhaps a C# issue that is easily remedied in F#? Thank you in advance for any assistance and for providing such a valuable technical resource here. It's been my favorite for many years now.
Mike, thank you for writing. The fluent interface that I show in this article is the most common form you see in C#. While it's not my preferred variation, I use it in this article because it's a direct translation of the style used in Nat Pryce's Java code.
Ordinarily, I prefer an immutable variant, but in C# this leads to even more boilerplate code, and I didn't want to sidetrack the topic by making this recap article more complicated than absolutely necessary.
You may be pleased to learn that future articles in this very article series will show alternatives in both C#, F#, and Haskell.
Hi Mark, A while ago I made a generic builder for this exact purpose. I also made som helper extension methods, that could act as sort of an Object Mother. I quite like how it work and I have used it quite a few times. So, reading this post, I thought I'd put in a link to it, as it might be usefull to other readers.
Generic Builder with Object Mother Gist
It's all in one big gist and probably not very weel structured, but if you look at the class GenericBuilder it should be quite easily understood. The examples of extensionmethods can be seen towards the end of the file.
I've used test data builders in C# just like this in the past, and couldn't decide whether I liked them or not, due to all the boilerplate.
I'm looking forward to the next few posts, thanks for doing this.
Hi, Mark
In C# I starated to prefer to use a "parameterized object mother". Please take a look and tell me what out think about it: Address Object Mother Gist.
From my experience it is less and simplier code. It is also a bid easier to debug. Personally, the Object Mother is the first pattern when refactoring test data creationg and I use Fluent Test Data Builder only in more complex scenarios.
@JanD: Unfortunately, your solution would not work for immutable data structures (which I prefer).
Robert, thank you for writing. I haven't seen that particular C# variation before, but it looks useful. I hope that as this article series progresses, it should become increasingly clear to the reader that the Test Data Builder pattern addresses various language deficiencies. (It has, by the way, for some time been a common criticism of design patterns in general that they are nothing but patches on language deficiencies. I don't think that I agree with that 100 percent, but I certainly understand the argument.)
Nat Pryce's original article about the Test Data Builder pattern is from 2007 with example code in Java. I don't know that much about Java, but back then, I don't think C# had optional arguments (as far as I can tell, that language feature was added in 2010). My point is that the pattern described a good way to model code given the language features that were available at the time.
As a general rule, I'm not a fan of C#'s optional argument feature (because I'm concerned what it does to forwards and backwards compatibility of my APIs), but used in the way you suggest it does look useful. Perhaps it does, indeed, address all the concerns that the Test Data Builder pattern addresses. I haven't tried it, so I can't really evaluate it (yet), but it looks like it'd be worth trying out.
My overall goal with this article series is, however, slightly different. In fact, I'm not trying to sell the Test Data Builder pattern to anyone. Rather, the point is that with better API design, and with better languages, it'd be largely redundant.
Hi, Mark
Thank you for this post
I personally leverage Impromptu Interface. It could be also verbose but as you only provide meaningful data it fits to Robert C. Martin credo. And it avoids creating a lot of one-shot boilerplate code and/or noising existing classes with UT specific stuff.
Romain, do you have an example of that, that you could share?
Partial
IAddress
withCity
value only:Partial
IAddress
withCity
value and partialIPostCode
withISO
value only:Main drawback is verbosity but intent is pretty clear.
We could reduce nested code by splitting
IAddress
andIPostCode
declarations but it also reduces intent: we do not care aboutIPostCode
, we care aboutIAddress
andIPostCode
is only an implementation detail.I heavily leverage
region
to cope with C# verbosity and to highlight common pattern - AAA in this case - so all this code is usually hidden in oneARRANGE
region.When I need multiple declaration I used
sut
(System Under Test) marker to highlight main actor.Do I understand it correctly that you'd have an interface like the following, then?
I'm not sure that I quite follow...
Mark, I tend to avoid
setter
in my interfaces so my domain objects usually are immutable and only exposegetter
.My implementation are mainly internal which prevent them to be used directly from within UT assembly (without using InternalsVisibleTo attribute).
I have factories - which implementation are also internal - to build my objects.
I then use an IoC container to access factories and create my objects.
AddressBuilder
lives in UT world so must be in another assembly to avoid noising my model.To cope with my internal visibility constraint I have at least 2 options I can live with:
- Using InternalsVisibleTo attribute for my UT assembly to be able to seamlessly use my types
- Leveraging a test container to resolve my factory and then create my objects.
To deal with the immutable constraint I can create new ones withinWith
methods. I can live with this too.The main drawback remains the verbosity/burden of those methods.
Using Impromptu Interface to generate partial test data spares builder classes creation while keeping verbosity acceptable and intent clear.
Does it make sense?
That helps clarify things, thank you.
I know that obviously, I could try for myself, but when you write
then what will be the value of
address.PostCode
?You have to be aware of this. When your test focus on a single aspect of your class you can safely use it.
Imagine you are testing a
City
centric algorithm: you do not care about Street, Street number, Floor, and so on.No need to create heavy/costly objects you can safely use a partial object which is only compliant with a part of the original interface.
The way you would have deal with if you had split IAddress interface into several parts namely IHaveACity, IHaveAStreet, ...
As it only declares what it needs to work the UT intent is pretty clear. As test builder it removes noisy stuff.
Now I think I get it! Thank you for taking the time to explain.
A slight variation on Robert Pajak's approach that allows writing
an.Address()
instead of unwieldyAddressObjectMother.Create()
: Mother Factory.Another usage sample: gist.


User:
Save
Home
tools
Fill color
blue
red
green
yellow
purple
none
Border color
black
blue
red
green
yellow
purple
Border width
thin
medium
thick
F
mDraw: Collab Drawing Session
Seems like your browser does not support html5.


My main hobbies include motorcycles, mountain bikes, camping, and Star Wars.
When I have enough down time, you can typically expect me to disappear into the woods for a few days. I love being able to camp out in the wildness and explore new trails on my mountain bike.
One of the major driving questions in my life has been:
"How do computers work?"
After my undergraduate education, I am not so convinced that any one person can really answer this question, because of the vast amalgamation of knowledge put together to push that technology to where it is today. However, that does not mean it's not a good goal to have.
I am particularly curious to find out more about machine learning and find out more ways that machine learning models can be leveraged to further improve computer architecture and the overall efficiency of machines in the world we live in.
Overall, I just really enjoy programming right now and I want to learn more about what else is out there.


pyfor.cloud module¶
-
class
pyfor.cloud.
Cloud
(path)¶ Bases:
object
The cloud object is an API for interacting with .las, .laz, and .ply files in memory, and is generally the starting point for any analysis with pyfor. For a more qualitative assessment of getting started with
Cloud
please see the user manual.-
__init__
(path)¶ Initialize self. See help(type(self)) for accurate signature.
-
chm
(cell_size, interp_method=None, pit_filter=None, kernel_size=3)¶ Returns a
Raster
object of the maximum z value in each cell, with optional interpolation (i.e. nan-filling) and pit filter parameters. Currently, only a median pit filter is implemented.- Parameters
cell_size – The cell size for the returned raster in the same units as the parent Cloud or las file.
interp_method – The interpolation method as a string to fill in NA values of the produced canopy height model, one of either “nearest”, “cubic”, or “linear”. This is an argument to scipy.interpolate.griddata.
pit_filter – If “median” passes a median filter over the produced canopy height model.
kernel_size – The kernel size of the median filter, must be an odd integer.
- Returns
A
Raster
object of the canopy height model.
-
clip
(polygon)¶ Clips the point cloud to the provided shapely polygon using a ray casting algorithm. This method calls
clip.poly_clip()
directly. This returns a newCloud
.- Parameters
polygon – A
shapely.geometry.Polygon
in the same CRS as the Cloud.- Returns
A new :class:.`Cloud` object clipped to the provided polygon.
-
property
convex_hull
¶ Calculates the convex hull of the cloud projected onto a 2d plane, a wrapper for
scipy.spatial.ConvexHull()
.- Returns
A
shapely.geometry.Polygon
of the convex hull.
-
filter
(min, max, dim)¶ Filters a cloud object for a given dimension in place.
- Parameters
min – Minimum dimension to retain.
max – Maximum dimension to retain.
dim – The dimension of interest as a string. For example “z”. This corresponds to a column label in
self.data.points
.
-
classmethod
from_pdal
(ins)¶ Converts a PDAL ins argument from a PDAL filters.python into a Cloud object.
- Parameters
ins – The ins argument from PDAL.
-
grid
(cell_size)¶ Generates a
Grid
object for the parent object given a cell size. See the documentation forGrid
for more information.- Parameters
cell_size – The resolution of the plot in the same units as the input file.
- Returns
A
Grid
object.
-
normalize
(cell_size, classified=False, **kwargs)¶ Normalize the cloud using the default Zhang et al. (2003) progressive morphological ground filter. Please see the documentation in
ground_filter.Zhang2003
for more information and keyword argument definitions. If you want to use a pre-computed DEM to normalize, please seesubtract()
.- Parameters
cell_size – The resolution of the intermediate bare earth model.
classified – If True and file type is .las or .laz, uses the points classified as ground (i.e. 2) to construct the intermediate bare earth model.
-
plot
(cell_size=1, cmap='viridis', return_plot=False, block=False)¶ Plots a basic canopy height model of the Cloud object. This is mainly a convenience function for
Raster.plot
. More robust methods exist for dealing with canopy height models. Please see the user manual.- Parameters
clip_size – The resolution of the plot in the same units as the input file.
return_plot – If true, returns a matplotlib plt object.
- Returns
If return_plot == True, returns matplotlib plt object. Not yet implemented.
-
plot3d
(dim='z', point_size=1, cmap='Spectral_r', max_points=500000.0, n_bin=8, plot_trees=False)¶ Plots the three dimensional point cloud using a Qt backend. By default, if the point cloud exceeds 5e5 points, then it is downsampled using a uniform random distribution. This is for performance purposes.
- Parameters
point_size – The size of the rendered points.
dim – The dimension upon which to color (i.e. “z”, “intensity”, etc.)
cmap – The matplotlib color map used to color the height distribution.
max_points – The maximum number of points to render.
-
standard_metrics
(heightbreak=0)¶
-
subtract
(path)¶ Normalize using a pre-computed raster file, i.e. “subtract” the heights from the input raster in place. This assumes the raster and the point cloud are in the same coordinate system. :param path: The path to the raster file, must be in a format supported by rasterio. :return:
-
write
(path)¶ Write to file. The precise mechanisms of this writing will depend on the file input type. For .las files this will be handled by
LASData.write()
, for .ply files this will be handled byPLYData.write()
.- Parameters
path – The path of the output file.
-
-
class
pyfor.cloud.
CloudData
(points, header)¶ Bases:
object
-
__init__
(points, header)¶ Initialize self. See help(type(self)) for accurate signature.
-
-
class
pyfor.cloud.
LASData
(points, header)¶ Bases:
pyfor.cloud.CloudData
-
write
(path)¶ Writes the object to file. This is a wrapper for
laspy.file.File()
- Parameters
path – The path of the ouput file.
-
-
class
pyfor.cloud.
PLYData
(points, header)¶ Bases:
pyfor.cloud.CloudData
-
write
(path)¶ Writes the object to file. This is a wrapper for
plyfile.PlyData.write()
- Parameters
path – The path of the ouput file.
-