text:
Looking for an opinionated guide to Angular syntax, conventions, and application structure?
Step right in!
This style guide presents preferred conventions and, as importantly, explains why.

{@a toc}

## Style vocabulary

Each guideline describes either a good or bad practice, and all have a consistent presentation.

The wording of each guideline indicates how strong the recommendation is.

**Do** is one that should always be followed.
_Always_ might be a bit too strong of a word.
Guidelines that literally should always be followed are extremely rare.
On the other hand, you need a really unusual case for breaking a *Do* guideline.

**Consider** guidelines should generally be followed.
If you fully understand the meaning behind the guideline and have a good reason to deviate, then do so. Please strive to be consistent.

**Avoid** indicates something you should almost never do. Code examples to *avoid* have an unmistakable red header.

**Why?** gives reasons for following the previous recommendations.

## File structure conventions

Some code examples display a file that has one or more similarly named companion files.
For example, `hero.component.ts` and `hero.component.html`.

The guideline uses the shortcut `hero.component.ts|html|css|spec` to represent those various files. Using this shortcut makes this guide's file structures easier to read and more terse.

{@a single-responsibility}

## Single responsibility

Apply the
single responsibility principle (SRP)
to all components, services, and other symbols.
This helps make the app cleaner, easier to read and maintain, and more testable.

{@a 01-01}

### Rule of One

#### Style 01-01

**Do** define one thing, such as a service or component, per file.

**Consider** limiting files to 400 lines of code.

**Why?** One component per file makes it far easier to read, maintain, and avoid
collisions with teams in source control.

**Why?** One component per file avoids hidden bugs that often arise when combining components in a file where they may share variables, create unwanted closures, or unwanted coupling with dependencies.

**Why?** A single component can be the default export for its file which facilitates lazy loading with the router.

The key is to make the code more reusable, easier to read, and less mistake prone.

The following *negative* example defines the `AppComponent`, bootstraps the app,
defines the `Hero` model object, and loads heroes from the server all in the same file.
*Don't do this*.

It is a better practice to redistribute the component and its
supporting classes into their own, dedicated files.

As the app grows, this rule becomes even more important.
Back to top

{@a 01-02}

### Small functions

#### Style 01-02

**Do** define small functions

**Consider** limiting to no more than 75 lines.

**Why?** Small functions are easier to test, especially when they do one thing and serve one purpose.

**Why?** Small functions promote reuse.

**Why?** Small functions are easier to read.

**Why?** Small functions are easier to maintain.

**Why?** Small functions help avoid hidden bugs that come with large functions that share variables with external scope, create unwanted closures, or unwanted coupling with dependencies.

Back to top

## Naming

Naming conventions are hugely important to maintainability and readability. This guide recommends naming conventions for the file name and the symbol name.

{@a 02-01}

### General Naming Guidelines

#### Style 02-01

**Do** use consistent names for all symbols.

**Do** follow a pattern that describes the symbol's feature then its type. The recommended pattern is `feature.type.ts`.

**Why?** Naming conventions help provide a consistent way to find content at a glance. Consistency within the project is vital. Consistency with a team is important. Consistency across a company provides tremendous efficiency.

**Why?** The naming conventions should simply help find desired code faster and make it easier to understand.

**Why?** Names of folders and files should clearly convey their intent. For example, `app/heroes/hero-list.component.ts` may contain a component that manages a list of heroes.

Back to top

{@a 02-02}

### Separate file names with dots and dashes

#### Style 02-02

**Do** use dashes to separate words in the descriptive name.

**Do** use dots to separate the descriptive name from the type.

**Do** use consistent type names for all components following a pattern that describes the component's feature then its type. A recommended pattern is `feature.type.ts`.

**Do** use conventional type names including `.service`, `.component`, `.pipe`, `.module`, and `.directive`.
Invent additional type names if you must but take care not to create too many.

**Why?** Type names provide a consistent way to quickly identify what is in the file.

**Why?** Type names make it easy to find a specific file type using an editor or IDE's fuzzy search techniques.

**Why?** Unabbreviated type names such as `.service` are descriptive and unambiguous.
Abbreviations such as `.srv`, `.svc`, and `.serv` can be confusing.

**Why?** Type names provide pattern matching for any automated tasks.

Back to top

{@a 02-03}

### Symbols and file names

#### Style 02-03

**Do** use consistent names for all assets named after what they represent.

**Do** use upper camel case for class names.

**Do** match the name of the symbol to the name of the file.

**Do** append the symbol name with the conventional suffix (such as `Component`,
`Directive`, `Module`, `Pipe`, or `Service`) for a thing of that type.

**Do** give the filename the conventional suffix (such as `.component.ts`, `.directive.ts`,
`.module.ts`, `.pipe.ts`, or `.service.ts`) for a file of that type.

**Why?** Consistent conventions make it easy to quickly identify
and reference assets of different types.

  <col width="50%">

  </col>

  <col width="50%">

  </col>

      Symbol Name

      File Name

        @Component({ ... })
        export class AppComponent { }

      app.component.ts

        @Component({ ... })
        export class HeroesComponent { }

      heroes.component.ts

        @Component({ ... })
        export class HeroListComponent { }

      hero-list.component.ts

        @Component({ ... })
        export class HeroDetailComponent { }

      hero-detail.component.ts

        @Directive({ ... })
        export class ValidationDirective { }

      validation.directive.ts

        @NgModule({ ... })
        export class AppModule

      app.module.ts

        @Pipe({ name: 'initCaps' })
        export class InitCapsPipe implements PipeTransform { }

      init-caps.pipe.ts

        @Injectable()
        export class UserProfileService { }

      user-profile.service.ts

Back to top

{@a 02-04}

### Service names

#### Style 02-04

**Do** use consistent names for all services named after their feature.

**Do** suffix a service class name with `Service`.
For example, something that gets data or heroes
should be called a `DataService` or a `HeroService`.

A few terms are unambiguously services. They typically
indicate agency by ending in "-er". You may prefer to name
a service that logs messages `Logger` rather than `LoggerService`.
Decide if this exception is agreeable in your project.
As always, strive for consistency.

**Why?** Provides a consistent way to quickly identify and reference services.

**Why?** Clear service names such as `Logger` do not require a suffix.

**Why?** Service names such as `Credit` are nouns and require a suffix and should be named with a suffix when it is not obvious if it is a service or something else.

  <col width="50%">

  </col>

  <col width="50%">

  </col>

      Symbol Name

      File Name

        @Injectable()
        export class HeroDataService { }

      hero-data.service.ts

        @Injectable()
        export class CreditService { }

      credit.service.ts

        @Injectable()
        export class Logger { }

      logger.service.ts

Back to top

{@a 02-05}

### Bootstrapping

#### Style 02-05

**Do** put bootstrapping and platform logic for the app in a file named `main.ts`.

**Do** include error handling in the bootstrapping logic.

**Avoid** putting app logic in `main.ts`. Instead, consider placing it in a component or service.

**Why?** Follows a consistent convention for the startup logic of an app.

**Why?** Follows a familiar convention from other technology platforms.

Back to top

{@a 05-02}

### Component selectors

#### Style 05-02

**Do** use _dashed-case_ or _kebab-case_ for naming the element selectors of components.

**Why?** Keeps the element names consistent with the specification for [Custom Elements](https://www.w3.org/TR/custom-elements/).

Back to top

{@a 02-07}

### Component custom prefix

#### Style 02-07

**Do** use a hyphenated, lowercase element selector value; for example, `admin-users`.

**Do** use a custom prefix for a component selector.
For example, the prefix `toh` represents **T**our **o**f **H**eroes and the prefix `admin` represents an admin feature area.

**Do** use a prefix that identifies the feature area or the app itself.

**Why?** Prevents element name collisions with components in other apps and with native HTML elements.

**Why?** Makes it easier to promote and share the component in other apps.

**Why?** Components are easy to identify in the DOM.

Back to top

{@a 02-06}

### Directive selectors

#### Style 02-06

**Do** Use lower camel case for naming the selectors of directives.

**Why?** Keeps the names of the properties defined in the directives that are bound to the view consistent with the attribute names.

**Why?** The Angular HTML parser is case sensitive and recognizes lower camel case.

Back to top

{@a 02-08}

### Directive custom prefix

#### Style 02-08

**Do** use a custom prefix for the selector of directives (e.g, the prefix `toh` from **T**our **o**f **H**eroes).

**Do** spell non-element selectors in lower camel case unless the selector is meant to match a native HTML attribute.

**Why?** Prevents name collisions.

**Why?** Directives are easily identified.

Back to top

{@a 02-09}

### Pipe names

#### Style 02-09

**Do** use consistent names for all pipes, named after their feature.
The pipe class name should use [UpperCamelCase](guide/glossary#case-types)
(the general convention for class names),
and the corresponding `name` string should use *lowerCamelCase*.
The `name` string cannot use hyphens ("dash-case" or "kebab-case").

**Why?** Provides a consistent way to quickly identify and reference pipes.

  <col width="50%">

  </col>

  <col width="50%">

  </col>

      Symbol Name

      File Name

        @Pipe({ name: 'ellipsis' })
        export class EllipsisPipe implements PipeTransform { }

      ellipsis.pipe.ts

        @Pipe({ name: 'initCaps' })
        export class InitCapsPipe implements PipeTransform { }

      init-caps.pipe.ts

Back to top

{@a 02-10}

### Unit test file names

#### Style 02-10

**Do** name test specification files the same as the component they test.

**Do** name test specification files with a suffix of `.spec`.

**Why?** Provides a consistent way to quickly identify tests.

**Why?** Provides pattern matching for [karma](http://karma-runner.github.io/) or other test runners.

  <col width="50%">

  </col>

  <col width="50%">

  </col>

      Test Type

      File Names

      Components

      heroes.component.spec.ts

      hero-list.component.spec.ts

      hero-detail.component.spec.ts

      Services

      logger.service.spec.ts

      hero.service.spec.ts

      filter-text.service.spec.ts

      Pipes

      ellipsis.pipe.spec.ts

      init-caps.pipe.spec.ts

Back to top

{@a 02-11}

### _End-to-End_ (E2E) test file names

#### Style 02-11

**Do** name end-to-end test specification files after the feature they test with a suffix of `.e2e-spec`.

**Why?** Provides a consistent way to quickly identify end-to-end tests.

**Why?** Provides pattern matching for test runners and build automation.

  <col width="50%">

  </col>

  <col width="50%">

  </col>

      Test Type

      File Names

      End-to-End Tests

      app.e2e-spec.ts

      heroes.e2e-spec.ts

Back to top

{@a 02-12}

### Angular _NgModule_ names

#### Style 02-12

**Do** append the symbol name with the suffix `Module`.

**Do** give the file name the `.module.ts` extension.

**Do** name the module after the feature and folder it resides in.

**Why?** Provides a consistent way to quickly identify and reference modules.

**Why?** Upper camel case is conventional for identifying objects that can be instantiated using a constructor.

**Why?** Easily identifies the module as the root of the same named feature.

**Do** suffix a _RoutingModule_ class name with `RoutingModule`.

**Do** end the filename of a _RoutingModule_ with `-routing.module.ts`.

**Why?** A `RoutingModule` is a module dedicated exclusively to configuring the Angular router.
A consistent class and file name convention make these modules easy to spot and verify.

  <col width="50%">

  </col>

  <col width="50%">

  </col>

      Symbol Name

      File Name

        @NgModule({ ... })
        export class AppModule { }

      app.module.ts

        @NgModule({ ... })
        export class HeroesModule { }

      heroes.module.ts

        @NgModule({ ... })
        export class VillainsModule { }

      villains.module.ts

        @NgModule({ ... })
        export class AppRoutingModule { }

      app-routing.module.ts

        @NgModule({ ... })
        export class HeroesRoutingModule { }

      heroes-routing.module.ts

Back to top

## Application structure and NgModules

Have a near-term view of implementation and a long-term vision. Start small but keep in mind where the app is heading down the road.

All of the app's code goes in a folder named `src`.
All feature areas are in their own folder, with their own NgModule.

All content is one asset per file. Each component, service, and pipe is in its own file.
All third party vendor scripts are stored in another folder and not in the `src` folder.
You didn't write them and you don't want them cluttering `src`.
Use the naming conventions for files in this guide.
Back to top

{@a 04-01}

### _LIFT_

#### Style 04-01

**Do** structure the app such that you can **L**ocate code quickly,
**I**dentify the code at a glance,
keep the **F**lattest structure you can, and
**T**ry to be DRY.

**Do** define the structure to follow these four basic guidelines, listed in order of importance.

**Why?** LIFT provides a consistent structure that scales well, is modular, and makes it easier to increase developer efficiency by finding code quickly.
To confirm your intuition about a particular structure, ask:
_can I quickly open and start work in all of the related files for this feature_?

Back to top

{@a 04-02}

### Locate

#### Style 04-02

**Do** make locating code intuitive, simple, and fast.

**Why?** To work efficiently you must be able to find files quickly,
especially when you do not know (or do not remember) the file _names_.
Keeping related files near each other in an intuitive location saves time.
A descriptive folder structure makes a world of difference to you and the people who come after you.

Back to top

{@a 04-03}

### Identify

#### Style 04-03

**Do** name the file such that you instantly know what it contains and represents.

**Do** be descriptive with file names and keep the contents of the file to exactly one component.

**Avoid** files with multiple components, multiple services, or a mixture.

**Why?** Spend less time hunting and pecking for code, and become more efficient.
Longer file names are far better than _short-but-obscure_ abbreviated names.

It may be advantageous to deviate from the _one-thing-per-file_ rule when
you have a set of small, closely-related features that are better discovered and understood
in a single file than as multiple files. Be wary of this loophole.

Back to top

{@a 04-04}

### Flat

#### Style 04-04

**Do** keep a flat folder structure as long as possible.

**Consider** creating sub-folders when a folder reaches seven or more files.

**Consider** configuring the IDE to hide distracting, irrelevant files such as generated `.js` and `.js.map` files.

**Why?** No one wants to search for a file through seven levels of folders.
A flat structure is easy to scan.

On the other hand,
psychologists believe
that humans start to struggle when the number of adjacent interesting things exceeds nine.
So when a folder has ten or more files, it may be time to create subfolders.

Base your decision on your comfort level.
Use a flatter structure until there is an obvious value to creating a new folder.

Back to top

{@a 04-05}

### _T-DRY_ (Try to be _DRY_)

#### Style 04-05

**Do** be DRY (Don't Repeat Yourself).

**Avoid** being so DRY that you sacrifice readability.

**Why?** Being DRY is important, but not crucial if it sacrifices the other elements of LIFT.
That's why it's called _T-DRY_.
For example, it's redundant to name a template `hero-view.component.html` because
with the `.html` extension, it is obviously a view.
But if something is not obvious or departs from a convention, then spell it out.

Back to top

{@a 04-06}

### Overall structural guidelines

#### Style 04-06

**Do** start small but keep in mind where the app is heading down the road.

**Do** have a near term view of implementation and a long term vision.

**Do** put all of the app's code in a folder named `src`.

**Consider** creating a folder for a component when it has multiple accompanying files (`.ts`, `.html`, `.css` and `.spec`).

**Why?** Helps keep the app structure small and easy to maintain in the early stages, while being easy to evolve as the app grows.

**Why?** Components often have four files (e.g. `*.html`, `*.css`, `*.ts`, and `*.spec.ts`) and can clutter a folder quickly.

{@a file-tree}

Here is a compliant folder and file structure:

    <project root>

      src

        app

          core

            exception.service.ts|spec.ts

            user-profile.service.ts|spec.ts

          heroes

            hero

              hero.component.ts|html|css|spec.ts

            hero-list

              hero-list.component.ts|html|css|spec.ts

            shared

              hero-button.component.ts|html|css|spec.ts

              hero.model.ts

              hero.service.ts|spec.ts

            heroes.component.ts|html|css|spec.ts

            heroes.module.ts

            heroes-routing.module.ts

          shared

            shared.module.ts

            init-caps.pipe.ts|spec.ts

            filter-text.component.ts|spec.ts

            filter-text.service.ts|spec.ts

          villains

            villain

              ...

            villain-list

              ...

            shared

              ...

            villains.component.ts|html|css|spec.ts

            villains.module.ts

            villains-routing.module.ts

          app.component.ts|html|css|spec.ts

          app.module.ts

          app-routing.module.ts

        main.ts

        index.html

        ...

      node_modules/...

      ...

While components in dedicated folders are widely preferred,
another option for small apps is to keep components flat (not in a dedicated folder).
This adds up to four files to the existing folder, but also reduces the folder nesting.
Whatever you choose, be consistent.

Back to top

{@a 04-07}

### _Folders-by-feature_ structure

#### Style 04-07

**Do** create folders named for the feature area they represent.

**Why?** A developer can locate the code and identify what each file represents
at a glance. The structure is as flat as it can be and there are no repetitive or redundant names.

**Why?** The LIFT guidelines are all covered.

**Why?** Helps reduce the app from becoming cluttered through organizing the
content and keeping them aligned with the LIFT guidelines.

**Why?** When there are a lot of files, for example 10+,
locating them is easier with a consistent folder structure
and more difficult in a flat structure.

**Do** create an NgModule for each feature area.

**Why?** NgModules make it easy to lazy load routable features.

**Why?** NgModules make it easier to isolate, test, and reuse features.

  For more information, refer to this folder and file structure example.

Back to top

{@a 04-08}

### App _root module_

#### Style 04-08

**Do** create an NgModule in the app's root folder,
for example, in `/src/app`.

**Why?** Every app requires at least one root NgModule.

**Consider** naming the root module `app.module.ts`.

**Why?** Makes it easier to locate and identify the root module.

Back to top

{@a 04-09}

### Feature modules

#### Style 04-09

**Do** create an NgModule for all distinct features in an application;
for example, a `Heroes` feature.

**Do** place the feature module in the same named folder as the feature area;
for example, in `app/heroes`.

**Do** name the feature module file reflecting the name of the feature area
and folder; for example, `app/heroes/heroes.module.ts`.

**Do** name the feature module symbol reflecting the name of the feature
area, folder, and file; for example, `app/heroes/heroes.module.ts` defines `HeroesModule`.

**Why?** A feature module can expose or hide its implementation from other modules.

**Why?** A feature module identifies distinct sets of related components that comprise the feature area.

**Why?** A feature module can easily be routed to both eagerly and lazily.

**Why?** A feature module defines clear boundaries between specific functionality and other application features.

**Why?** A feature module helps clarify and make it easier to assign development responsibilities to different teams.

**Why?** A feature module can easily be isolated for testing.

Back to top

{@a 04-10}

### Shared feature module

#### Style 04-10

**Do** create a feature module named `SharedModule` in a `shared` folder;
for example, `app/shared/shared.module.ts` defines `SharedModule`.

**Do** declare components, directives, and pipes in a shared module when those
items will be re-used and referenced by the components declared in other feature modules.

**Consider** using the name SharedModule when the contents of a shared
module are referenced across the entire application.

**Consider** _not_ providing services in shared modules. Services are usually
singletons that are provided once for the entire application or
in a particular feature module. There are exceptions, however. For example, in the sample code that follows, notice that the `SharedModule` provides `FilterTextService`. This is acceptable here because the service is stateless;that is, the consumers of the service aren't impacted by new instances.

**Do** import all modules required by the assets in the `SharedModule`;
for example, `CommonModule` and `FormsModule`.

**Why?** `SharedModule` will contain components, directives and pipes
that may need features from another common module; for example,
`ngFor` in `CommonModule`.

**Do** declare all components, directives, and pipes in the `SharedModule`.

**Do** export all symbols from the `SharedModule` that other feature modules need to use.

**Why?** `SharedModule` exists to make commonly used components, directives and pipes available for use in the templates of components in many other modules.

**Avoid** specifying app-wide singleton providers in a `SharedModule`. Intentional singletons are OK. Take care.

**Why?** A lazy loaded feature module that imports that shared module will make its own copy of the service and likely have undesirable results.

**Why?** You don't want each module to have its own separate instance of singleton services.
Yet there is a real danger of that happening if the `SharedModule` provides a service.

    src

      app

        shared

          shared.module.ts

          init-caps.pipe.ts|spec.ts

          filter-text.component.ts|spec.ts

          filter-text.service.ts|spec.ts

        app.component.ts|html|css|spec.ts

        app.module.ts

        app-routing.module.ts

      main.ts

      index.html

    ...

Back to top

{@a 04-11}

### Lazy Loaded folders

#### Style 04-11

A distinct application feature or workflow may be *lazy loaded* or *loaded on demand* rather than when the application starts.

**Do** put the contents of lazy loaded features in a *lazy loaded folder*.
A typical *lazy loaded folder* contains a *routing component*, its child components, and their related assets and modules.

**Why?** The folder makes it easy to identify and isolate the feature content.

Back to top

{@a 04-12}

### Never directly import lazy loaded folders

#### Style 04-12

**Avoid** allowing modules in sibling and parent folders to directly import a module in a *lazy loaded feature*.

**Why?** Directly importing and using a module will load it immediately when the intention is to load it on demand.

Back to top

## Components

{@a 05-03}

### Components as elements

#### Style 05-03

**Consider** giving components an _element_ selector, as opposed to _attribute_ or _class_ selectors.

**Why?** Components have templates containing HTML and optional Angular template syntax.
They display content.
Developers place components on the page as they would native HTML elements and web components.

**Why?** It is easier to recognize that a symbol is a component by looking at the template's html.

There are a few cases where you give a component an attribute, such as when you want to augment a built-in element. For example, [Material Design](https://material.angular.io/components/button/overview) uses this technique with `<button mat-button>`. However, you wouldn't use this technique on a custom element.

Back to top

{@a 05-04}

### Extract templates and styles to their own files

#### Style 05-04

**Do** extract templates and styles into a separate file, when more than 3 lines.

**Do** name the template file `[component-name].component.html`, where [component-name] is the component name.

**Do** name the style file `[component-name].component.css`, where [component-name] is the component name.

**Do** specify _component-relative_ URLs, prefixed with `./`.

**Why?** Large, inline templates and styles obscure the component's purpose and implementation, reducing readability and maintainability.

**Why?** In most editors, syntax hints and code snippets aren't available when developing inline templates and styles.
The Angular TypeScript Language Service (forthcoming) promises to overcome this deficiency for HTML templates
in those editors that support it; it won't help with CSS styles.

**Why?** A _component relative_ URL requires no change when you move the component files, as long as the files stay together.

**Why?** The `./` prefix is standard syntax for relative URLs; don't depend on Angular's current ability to do without that prefix.

Back to top

{@a 05-12}

### Decorate _input_ and _output_ properties

#### Style 05-12

**Do** use the `@Input()` and `@Output()` class decorators instead of the `inputs` and `outputs` properties of the
`@Directive` and `@Component` metadata:

**Consider** placing `@Input()` or `@Output()` on the same line as the property it decorates.

**Why?** It is easier and more readable to identify which properties in a class are inputs or outputs.

**Why?** If you ever need to rename the property or event name associated with
`@Input()` or `@Output()`, you can modify it in a single place.

**Why?** The metadata declaration attached to the directive is shorter and thus more readable.

**Why?** Placing the decorator on the same line _usually_ makes for shorter code and still easily identifies the property as an input or output.
Put it on the line above when doing so is clearly more readable.

Back to top

{@a 05-13}

### Avoid aliasing _inputs_ and _outputs_

#### Style 05-13

**Avoid** _input_ and _output_ aliases except when it serves an important purpose.

**Why?** Two names for the same property (one private, one public) is inherently confusing.

**Why?** You should use an alias when the directive name is also an _input_ property,
and the directive name doesn't describe the property.

Back to top

{@a 05-14}

### Member sequence

#### Style 05-14

**Do** place properties up top followed by methods.

**Do** place private members after public members, alphabetized.

**Why?** Placing members in a consistent sequence makes it easy to read and
helps instantly identify which members of the component serve which purpose.

Back to top

{@a 05-15}

### Delegate complex component logic to services

#### Style 05-15

**Do** limit logic in a component to only that required for the view. All other logic should be delegated to services.

**Do** move reusable logic to services and keep components simple and focused on their intended purpose.

**Why?** Logic may be reused by multiple components when placed within a service and exposed via a function.

**Why?** Logic in a service can more easily be isolated in a unit test, while the calling logic in the component can be easily mocked.

**Why?** Removes dependencies and hides implementation details from the component.

**Why?** Keeps the component slim, trim, and focused.

Back to top

{@a 05-16}

### Don't prefix _output_ properties

#### Style 05-16

**Do** name events without the prefix `on`.

**Do** name event handler methods with the prefix `on` followed by the event name.

**Why?** This is consistent with built-in events such as button clicks.

**Why?** Angular allows for an [alternative syntax](guide/template-syntax#binding-syntax) `on-*`. If the event itself was prefixed with `on` this would result in an `on-onEvent` binding expression.

Back to top

{@a 05-17}

### Put presentation logic in the component class

#### Style 05-17

**Do** put presentation logic in the component class, and not in the template.

**Why?** Logic will be contained in one place (the component class) instead of being spread in two places.

**Why?** Keeping the component's presentation logic in the class instead of the template improves testability, maintainability, and reusability.

Back to top

## Directives

{@a 06-01}

### Use directives to enhance an element

#### Style 06-01

**Do** use attribute directives when you have presentation logic without a template.

**Why?** Attribute directives don't have an associated template.

**Why?** An element may have more than one attribute directive applied.

Back to top

{@a 06-03}

### _HostListener_/_HostBinding_ decorators versus _host_ metadata

#### Style 06-03

**Consider** preferring the `@HostListener` and `@HostBinding` to the
`host` property of the `@Directive` and `@Component` decorators.

**Do** be consistent in your choice.

**Why?** The property associated with `@HostBinding` or the method associated with `@HostListener`
can be modified only in a single place—in the directive's class.
If you use the `host` metadata property, you must modify both the property/method declaration in the
directive's class and the metadata in the decorator associated with the directive.

Compare with the less preferred `host` metadata alternative.

**Why?** The `host` metadata is only one term to remember and doesn't require extra ES imports.

Back to top

## Services

{@a 07-01}

### Services are singletons

#### Style 07-01

**Do** use services as singletons within the same injector. Use them for sharing data and functionality.

**Why?** Services are ideal for sharing methods across a feature area or an app.

**Why?** Services are ideal for sharing stateful in-memory data.

Back to top

{@a 07-02}

### Single responsibility

#### Style 07-02

**Do** create services with a single responsibility that is encapsulated by its context.

**Do** create a new service once the service begins to exceed that singular purpose.

**Why?** When a service has multiple responsibilities, it becomes difficult to test.

**Why?** When a service has multiple responsibilities, every component or service that injects it now carries the weight of them all.

Back to top

{@a 07-03}

### Providing a service

#### Style 07-03

**Do** provide a service with the app root injector in the `@Injectable` decorator of the service.

**Why?** The Angular injector is hierarchical.

**Why?** When you provide the service to a root injector, that instance of the service is shared and available in every class that needs the service. This is ideal when a service is sharing methods or state.

**Why?** When you register a service in the `@Injectable` decorator of the service, optimization tools such as those used by the [Angular CLI's](cli) production builds can perform tree shaking and remove services that aren't used by your app.

**Why?** This is not ideal when two different components need different instances of a service. In this scenario it would be better to provide the service at the component level that needs the new and separate instance.

Back to top

{@a 07-04}

### Use the @Injectable() class decorator

#### Style 07-04

**Do** use the `@Injectable()` class decorator instead of the `@Inject` parameter decorator when using types as tokens for the dependencies of a service.

**Why?** The Angular Dependency Injection (DI) mechanism resolves a service's own
dependencies based on the declared types of that service's constructor parameters.

**Why?** When a service accepts only dependencies associated with type tokens, the `@Injectable()` syntax is much less verbose compared to using `@Inject()` on each individual constructor parameter.

Back to top

## Data Services

{@a 08-01}

### Talk to the server through a service

#### Style 08-01

**Do** refactor logic for making data operations and interacting with data to a service.

**Do** make data services responsible for XHR calls, local storage, stashing in memory, or any other data operations.

**Why?** The component's responsibility is for the presentation and gathering of information for the view. It should not care how it gets the data, just that it knows who to ask for it. Separating the data services moves the logic on how to get it to the data service, and lets the component be simpler and more focused on the view.

**Why?** This makes it easier to test (mock or real) the data calls when testing a component that uses a data service.

**Why?** The details of data management, such as headers, HTTP methods,
caching, error handling, and retry logic, are irrelevant to components
and other data consumers.

A data service encapsulates these details. It's easier to evolve these
details inside the service without affecting its consumers. And it's
easier to test the consumers with mock service implementations.

Back to top

## Lifecycle hooks

Use Lifecycle hooks to tap into important events exposed by Angular.

Back to top

{@a 09-01}

### Implement lifecycle hook interfaces

#### Style 09-01

**Do** implement the lifecycle hook interfaces.

**Why?** Lifecycle interfaces prescribe typed method
signatures. Use those signatures to flag spelling and syntax mistakes.

Back to top

## Appendix

Useful tools and tips for Angular.

Back to top

{@a A-01}

### Codelyzer

#### Style A-01

**Do** use [codelyzer](https://www.npmjs.com/package/codelyzer) to follow this guide.

**Consider** adjusting the rules in codelyzer to suit your needs.

Back to top

{@a A-02}

### File templates and snippets

#### Style A-02

**Do** use file templates or snippets to help follow consistent styles and patterns. Here are templates and/or snippets for some of the web development editors and IDEs.

**Consider** using [snippets](https://marketplace.visualstudio.com/items?itemName=johnpapa.Angular2) for [Visual Studio Code](https://code.visualstudio.com/) that follow these styles and guidelines.

**Consider** using [snippets](https://atom.io/packages/angular-2-typescript-snippets) for [Atom](https://atom.io/) that follow these styles and guidelines.

**Consider** using [snippets](https://github.com/orizens/sublime-angular2-snippets) for [Sublime Text](http://www.sublimetext.com/) that follow these styles and guidelines.

**Consider** using [snippets](https://github.com/mhartington/vim-angular2-snippets) for [Vim](http://www.vim.org/) that follow these styles and guidelines.

Back to top


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Onsen UI App</title>

  <ons-page ng-controller="PageController as page">
    <ons-toolbar>

{{page.title}}

        <ons-toolbar-button>
          <ons-icon icon="ion-ios-menu, material:md-menu"></ons-icon>
        </ons-toolbar-button>

    </ons-toolbar>

      <ons-button ng-click="page.showAlert('Hello world!')">Click me!</ons-button>

  </ons-page>

redpajama_set_name: RedPajamaGithub


text:
"use strict";
//Conforms to the ConditionHandler protocol in UIAutoMonkey
//Usage
//  var handlers = [ ];
//  var handlerInterval = 20;  //every how many events to process. Can vary by each handler, but often useful to group them
//  handlers.push(new ButtonHandler("Done", handlerInterval, false));  //every 20 events, press "Done" button if found as a top level button (no nav bar).
//  ...
//  config.conditionHandlers = handlers
//
function ButtonHandler(buttonName, checkEveryNumber, useNavBar, optionalIsTrueFunction) {
	this.buttonName = buttonName;
	this.checkEveryNumber = checkEveryNumber || 10;
	if (useNavBar == undefined) {
		useNavBar = true;
	};
	this.useNavBar = useNavBar;
	this.optionalIsTrueFunction = optionalIsTrueFunction || null;
	//stats
	this.statsIsTrueInvokedCount = 0;
	this.statsIsTrueReturnedTrue = 0;
	this.statsIsTrueReturnedFalse = 0;
	this.statsHandleInvokedCount = 0;
	this.statsHandleNotValidAndVisibleCount = 0;
	this.statsHandleErrorCount = 0;
	this.debugLogElementTreeOnIsTrue = false;
}

ButtonHandler.prototype.setDebugLogElementTreeOnIsTrue = function(aBool) {
	this.debugLogElementTreeOnIsTrue = aBool;
}

ButtonHandler.prototype.isObjectNil = function(anObject) {
	return anObject.toString() == "[object UIAElementNil]"
};

ButtonHandler.prototype.isValidAndVisible = function(aButtonOrNil) {
	if (this.isObjectNil(aButtonOrNil)) {
		return false;
	}
	//we now expect aButtonOrNil to be a button
	return aButtonOrNil.checkIsValid() && aButtonOrNil.isVisible();
}

// return true if we our button is visible
ButtonHandler.prototype.isTrue = function(target, eventCount, mainWindow) {
	this.statsIsTrueInvokedCount++;
	var result;
	if (this.optionalIsTrueFunction == null) {
		if (this.debugLogElementTreeOnIsTrue) {
			UIATarget.localTarget().logElementTree();
		}
		var aButton = this.findButton(target);
		result = this.isValidAndVisible(aButton);
	} else {
		result = this.optionalIsTrueFunction(target, eventCount, mainWindow);
	}
	if (result) {
		this.statsIsTrueReturnedTrue++;
	} else {
		this.statsIsTrueReturnedFalse++;
	};
	return result;
};

ButtonHandler.prototype.findButton = function(target) {
	return this.useNavBar ?
	    target.frontMostApp().mainWindow().navigationBar().buttons()[this.buttonName] :
        target.frontMostApp().mainWindow().buttons()[this.buttonName];
};

//every checkEvery() number of events our isTrue() method will be queried.
ButtonHandler.prototype.checkEvery = function() {
    return this.checkEveryNumber;
};

// if true then after we handle an event consider the particular Monkey event handled, and don't process the other condition handlers.
ButtonHandler.prototype.isExclusive = function() {
    return true;
};

// Press our button
ButtonHandler.prototype.handle = function(target, mainWindow) {
	this.statsHandleInvokedCount++;
	var button = this.findButton(target);
	if (this.isValidAndVisible(button)) {
		try{
		    button.tap();
		} catch(err) {
			this.statsHandleErrorCount++;
			UIALogger.logWarning(err);
		}
	} else {
		this.statsHandleNotValidAndVisibleCount++
		//UIALogger.logWarning(this.toString() + " button is not validAndVisible");
	};
};

ButtonHandler.prototype.toString = function() {
	return ["MonkeyTest::ButtonHandler(" + this.buttonName, this.checkEveryNumber, this.useNavBar, ")"].join();
};

ButtonHandler.prototype.logStats = function() {
	UIALogger.logDebug([this.toString(),
	    "IsTrueInvokedCount", this.statsIsTrueInvokedCount,
		"IsTrueReturnedTrue", this.statsIsTrueReturnedTrue,
		"IsTrueReturnedFalse", this.statsIsTrueReturnedFalse,
		"HandleInvokedCount", this.statsHandleInvokedCount,
		"HandleNotValidAndVisibleCount", this.statsHandleNotValidAndVisibleCount,
		"HandleErrorCount", this.statsHandleErrorCount].join());
};


text:
Renotifier.com Login with Facebook Demo
=======================================

This is the Login with Facebook button with ReNotifier integration. With this code sample you can integrate ReNotifier into any website that utilizes Login with Facebook to send them notifications with ReNotifier.

You can try out this demo live @

https://renotifier.com/demo/button/


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/ads/googleads/v11/services/campaign_asset_service.proto

package com.google.ads.googleads.v11.services;

public interface MutateCampaignAssetResultOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.ads.googleads.v11.services.MutateCampaignAssetResult)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * Returned for successful operations.
   *

   *
   * string resource_name = 1 [(.google.api.resource_reference) = { ... }
   * @return The resourceName.
   */
  java.lang.String getResourceName();
  /**
   *

   * Returned for successful operations.
   *

   *
   * string resource_name = 1 [(.google.api.resource_reference) = { ... }
   * @return The bytes for resourceName.
   */
  com.google.protobuf.ByteString
      getResourceNameBytes();

  /**
   *

   * The mutated campaign asset with only mutable fields after
   * mutate. The field will only be returned when response_content_type is set
   * to "MUTABLE_RESOURCE".
   *

   *
   * .google.ads.googleads.v11.resources.CampaignAsset campaign_asset = 2;
   * @return Whether the campaignAsset field is set.
   */
  boolean hasCampaignAsset();
  /**
   *

   * The mutated campaign asset with only mutable fields after
   * mutate. The field will only be returned when response_content_type is set
   * to "MUTABLE_RESOURCE".
   *

   *
   * .google.ads.googleads.v11.resources.CampaignAsset campaign_asset = 2;
   * @return The campaignAsset.
   */
  com.google.ads.googleads.v11.resources.CampaignAsset getCampaignAsset();
  /**
   *

   * The mutated campaign asset with only mutable fields after
   * mutate. The field will only be returned when response_content_type is set
   * to "MUTABLE_RESOURCE".
   *

   *
   * .google.ads.googleads.v11.resources.CampaignAsset campaign_asset = 2;
   */
  com.google.ads.googleads.v11.resources.CampaignAssetOrBuilder getCampaignAssetOrBuilder();
}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Medallion.OData.Dynamic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

// TODO VNEXT: move this out of the client namespace
namespace Medallion.OData.Client
{
    /// <summary>
    /// A dynamic entity type to provide support for dynamic client queries
    /// </summary>
    public sealed class ODataEntity : ODataObject
    {
        private static readonly IEqualityComparer<string> KeyComparer = StringComparer.OrdinalIgnoreCase;

        // TODO we could potentially optimized this class by sharing "class" definitions like ExpandoObject does
        // note that we can't use ExpandoObject directly because it doesn't support case-insensitive comparison

        internal IReadOnlyDictionary<string, object> Values { get; }

        /// <summary>
        /// Constructs a entity from the given set of key value pairs
        /// </summary>
        public ODataEntity(IEnumerable<KeyValuePair<string, object>> values)
        {
            Throw.IfNull(values, "values");

            var valuesDictionary = new Dictionary<string, object>(KeyComparer);
            foreach (var kvp in values)
            {
                var oDataValue = kvp.Value as ODataValue;
                valuesDictionary.Add(kvp.Key, oDataValue != null ? oDataValue.Value : kvp.Value);
            }
            this.Values = valuesDictionary;
        }

        /// <summary>
        /// Gets the strongly-typed value of the named property. This method can be used in OData queries as long as <paramref name="propertyName"/>
        /// is a constant or local variable capture
        /// </summary>
        /// <typeparam name="TProperty">the property type</typeparam>
        /// <param name="propertyName">the property name</param>
        /// <returns>the property value</returns>
        public TProperty Get<TProperty>(string propertyName)
        {
            Throw.IfNull(propertyName, "propertyName");

            if (!this.Values.TryGetValue(propertyName, out var result))
            {
                throw new ArgumentException("The entity does not contain a value for property '" + propertyName + "'!");
            }

            if (result == null)
            {
                if (!typeof(TProperty).CanBeNull())
                {
                    throw new InvalidCastException(string.Format(
                        "Property '{0}' has a null value and cannot be cast to requested type '{1}'",
                        propertyName,
                        typeof(TProperty)
                    ));
                }
                return default(TProperty); // always null due to check above
            }

            if (result is TProperty)
            {
                return (TProperty)result;
            }

            var tProperty = typeof(TProperty);
            if (tProperty.IsNumeric() && result.GetType().IsNumeric())
            {
                try
                {
                    return NumberHelper.CheckedConvert<TProperty>(result);
                }
                catch (Exception ex)
                {
                    throw new InvalidCastException(
                        string.Format(
                            "Failed to convert property '{0}' value '{1}' of type {2} to requested type {3}",
                            propertyName,
                            result,
                            result.GetType(),
                            tProperty
                        ),
                        ex
                    );
                }
            }

            if (typeof(ODataObject).GetTypeInfo().IsAssignableFrom(tProperty))
            {
                // at this point, we already know it's not ODataEntity since that would be
                // handled above. Thus, we can just handle ODataValue
                return (TProperty)(object)ODataValue.FromObject(result);
            }

            throw new InvalidCastException(string.Format(
                "value '{0}' of type {1} for property '{2}' is not compatible with requested type {3}",
                result,
                result.GetType(), // already checked for null above!
                propertyName,
                tProperty
            ));
        }

        #region ---- Translation ----
#if NETSTANDARD1_5
        private static PlatformNotSupportedException ODataEntityQueriesNotSupported() =>
            new PlatformNotSupportedException($"Queries with the {typeof(ODataEntity)} class are not supported on .NET Standard < 2.0. See https://github.com/madelson/MedallionOData/issues/9 for more details");
#endif

#if !NETSTANDARD1_5
        private static readonly MethodInfo GetMethod = Helpers.GetMethod((ODataEntity r) => r.Get<int>(null))
            .GetGenericMethodDefinition();
#endif

        /// <summary>
        /// Replaces calls to <see cref="ODataEntity.Get{T}"/> with property accesses
        /// </summary>
        // TODO vNext this should not be public
        public static Expression Normalize(Expression expression)
        {
#if !NETSTANDARD1_5
            var result = Normalizer.Instance.Visit(expression);
            return result;
#else
            throw ODataEntityQueriesNotSupported();
#endif
        }

#if !NETSTANDARD1_5
        #region ---- Normalizer ----
        private sealed class Normalizer : ExpressionVisitor
        {
            public static readonly Normalizer Instance = new Normalizer();

            protected override Expression VisitMethodCall(MethodCallExpression methodCall)
            {
                if (methodCall.Method.MetadataToken == GetMethod.MetadataToken
                    && Equals(methodCall.Method.Module, GetMethod.Module))
                {
                    Throw<ODataCompileException>.If(
                        !LinqHelpers.TryGetValue(methodCall.Arguments[0], LinqHelpers.GetValueOptions.All, out var value),
                        () => string.Format(
                            "Unable to extract value for parameter '{0}' of {1}. Ensure that the value for the parameter can be statically determined",
                            methodCall.Method.GetParameters()[0].Name,
                            methodCall.Method
                        )
                    );
                    var propertyName = (string)value;
                    Throw<ODataCompileException>.If(
                        string.IsNullOrWhiteSpace(propertyName),
                        () => string.Format(
                            "'{0}' value for {1} must not be null or whitespace",
                            methodCall.Method.GetParameters()[0].Name,
                            methodCall.Method
                        )
                    );

                    var property = EntityPropertyInfo.For(name: propertyName, type: methodCall.Method.GetGenericArguments()[0]);
                    return Expression.Property(this.Visit(methodCall.Object), property);
                }

                return base.VisitMethodCall(methodCall);
            }
        }
        #endregion
#endif

        /// <summary>
        /// Reverts changes to an expression made by <see cref="ODataEntity.Normalize"/>
        /// </summary>
        // TODO vNext this should not be public
        public static Expression Denormalize(Expression expression)
        {
#if !NETSTANDARD1_5
            var result = Denormalizer.Instance.Visit(expression);
            return result;
#else
            throw ODataEntityQueriesNotSupported();
#endif
        }

#if !NETSTANDARD1_5
        #region ---- Denormalizer ----
        private sealed class Denormalizer : ExpressionVisitor
        {
            public static readonly Denormalizer Instance = new Denormalizer();

            protected override Expression VisitMember(MemberExpression node)
            {
                var entityProp = node.Member as EntityPropertyInfo;
                if (entityProp != null)
                {
                    return Expression.Call(
                        this.Visit(node.Expression),
                        GetMethod.MakeGenericMethod(entityProp.PropertyType),
                        Expression.Constant(entityProp.Name)
                    );
                }
                return base.VisitMember(node);
            }
        }
        #endregion
#endif

        #region ---- Fake property implementation ----
        internal static PropertyInfo GetProperty(string name, Type type)
        {
#if !NETSTANDARD1_5
            return EntityPropertyInfo.For(name, type);
#else
            throw ODataEntityQueriesNotSupported();
#endif
        }

#if !NETSTANDARD1_5
        private TProperty FakeGetter<TProperty>()
        {
            throw new InvalidOperationException("This getter is not valid");
        }

        private sealed class EntityPropertyInfo : PropertyInfo
        {
            private static readonly ConcurrentDictionary<Tuple<Type, string>, EntityPropertyInfo> Cache = new ConcurrentDictionary<Tuple<Type, string>, EntityPropertyInfo>(
                EqualityComparers.Create<Tuple<Type, string>>(
                    equals: (t1, t2) => t1.Item1 == t2.Item1 && KeyComparer.Equals(t1.Item2, t2.Item2),
                    hash: t => t.Item1.GetHashCode() ^ KeyComparer.GetHashCode(t.Item2)
                )
            );
            private static int _lastMetadataToken = 0;

            private readonly string _name;
            private readonly Type _type;
            private readonly int _metadataToken;

            private EntityPropertyInfo(string name, Type type, int metadataToken)
            {
                Throw.IfNull(name, "name");
                Throw.IfNull(type, "type");

                this._name = name;
                this._type = type;
                this._metadataToken = metadataToken;
            }

            public override PropertyAttributes Attributes
            {
                get { return PropertyAttributes.None; }
            }

            public override bool CanRead
            {
                get { return true; }
            }

            public override bool CanWrite
            {
                get { return true; }
            }

            public override MethodInfo[] GetAccessors(bool nonPublic)
            {
                return new[] { this.GetMethod };
            }

            public override MethodInfo GetGetMethod(bool nonPublic)
            {
                // we need to implement this because it's checked by Expression.Property calls
                return Helpers.GetMethod((ODataEntity r) => r.FakeGetter<object>())
                    .GetGenericMethodDefinition()
                    .MakeGenericMethod(this.PropertyType);
            }

            public override ParameterInfo[] GetIndexParameters()
            {
                return Empty<ParameterInfo>.Array;
            }

            public override MethodInfo GetSetMethod(bool nonPublic)
            {
                return null; // read-only
            }

            public override Type PropertyType
            {
                get { return this._type; }
            }

            public override object GetValue(object obj, BindingFlags invokeAttr, Binder binder, object[] index, System.Globalization.CultureInfo culture)
            {
                Throw.If(index != null && index.Length > 0, "index: properties cannot have indexers");

                Throw.IfNull(obj, "obj");
                var entity = obj as ODataEntity;
                Throw.If(entity == null, "obj: must be of type ODataEntity");
                Throw<ArgumentException>.If(!entity.Values.ContainsKey(this.Name), () => "the given entity instance does not contain property '" + this.Name + "'");

                return entity.Values[this.Name];
            }

            public override void SetValue(object obj, object value, BindingFlags invokeAttr, Binder binder, object[] index, System.Globalization.CultureInfo culture)
            {
                throw new InvalidOperationException("ODataEntity properties are read-only!");
            }

            public override Type DeclaringType
            {
                get { return typeof(ODataEntity); }
            }

            public override object[] GetCustomAttributes(Type attributeType, bool inherit)
            {
                return Empty<object>.Array;
            }

            public override object[] GetCustomAttributes(bool inherit)
            {
                return Empty<object>.Array;
            }

            public override bool IsDefined(Type attributeType, bool inherit)
            {
                return false;
            }

            public override string Name
            {
                get { return this._name; }
            }

            public override Type ReflectedType
            {
                get { return typeof(ODataEntity); }
            }

            public override bool Equals(object obj)
            {
                var that = obj as EntityPropertyInfo;
                return that != null && KeyComparer.Equals(this.Name, that.Name) && this.PropertyType == that.PropertyType;
            }

            public override int GetHashCode()
            {
                return KeyComparer.GetHashCode(this.Name) ^ this.PropertyType.GetHashCode();
            }

            public override string ToString()
            {
                return string.Format("{0}.Get<{1}>(\"{2}\")", typeof(ODataEntity), this.PropertyType, this.Name);
            }

            // TODO FUTURE consider returning a static token with a new module each time instead
            public override int MetadataToken { get { return this._metadataToken; } }
            public override Module Module { get { return EntityModule.Instance; } }

            public static EntityPropertyInfo For(string name, Type type)
            {
                var cacheKey = Tuple.Create(type, name);
                if (Cache.TryGetValue(cacheKey, out var cached))
                {
                    return cached;
                }

                var metadataToken = Interlocked.Increment(ref _lastMetadataToken);
                var newProp = new EntityPropertyInfo(name, type, metadataToken);
                // to avoid ever having equivalent props with different tokens, we only return
                // the new prop if it becomes the cached instance
                return Cache.TryAdd(cacheKey, newProp)
                    ? newProp
                    : Cache[cacheKey];
            }
        }

        private sealed class EntityModule : Module
        {
            public static readonly Module Instance = new EntityModule();
        }
#endif
        #endregion
        #endregion
    }
}


text:
title: Run PostgreSQL with Custom Configuration
menu:
  docs_0.11.0:
    identifier: pg-custom-config-quickstart
    name: Quickstart
    parent: pg-custom-config
    weight: 10
menu_name: docs_0.11.0
section_menu_id: guides
---
> New to KubeDB? Please start [here](/docs/concepts/README.md).

# Using Custom Configuration File

KubeDB supports providing custom configuration for PostgreSQL. This tutorial will show you how to use KubeDB to run PostgreSQL database with custom configuration.

## Before You Begin

At first, you need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. If you do not already have a cluster, you can create one by using [minikube](https://github.com/kubernetes/minikube).

Now, install KubeDB cli on your workstation and KubeDB operator in your cluster following the steps [here](/docs/setup/install.md).

To keep things isolated, this tutorial uses a separate namespace called `demo` throughout this tutorial.

```console
$ kubectl create ns demo
namespace/demo created
```

> Note: YAML files used in this tutorial are stored in [docs/examples/postgres](https://github.com/kubedb/cli/tree/master/docs/examples/postgres) folder in GitHub repository [kubedb/cli](https://github.com/kubedb/cli).

## Overview

PostgreSQL allows to configure database via **Configuration File**, **SQL** and **Shell**. The most common way is to edit configuration file `postgresql.conf`. When PostgreSQL docker image starts, it uses the configuration specified in `postgresql.conf` file. This file can have `include` directive which allows to include configuration from other files. One of these `include` directives is `include_if_exists` which accept a file reference. If the referenced file exists, it includes configuration from the file. Otherwise, it uses default configuration. KubeDB takes advantage of this feature to allow users to provide their custom configuration. To know more about configuring PostgreSQL see [here](https://www.postgresql.org/docs/current/static/runtime-config.html).

At first, you have to create a config file named `user.conf` with your desired configuration. Then you have to put this file into a [volume](https://kubernetes.io/docs/concepts/storage/volumes/). You have to specify this volume in `spec.configSource` section while creating Postgres crd. KubeDB will mount this volume into `/etc/config/` directory of the database pod which will be referenced by `include_if_exists` directive.

In this tutorial, we will configure `max_connections` and `shared_buffers` via a custom config file. We will use configMap as volume source.

## Custom Configuration

At first, let's create `user.conf` file setting `max_connections` and `shared_buffers` parameters.

```ini
$ cat user.conf
max_connections=300
shared_buffers=256MB
```

> Note that config file name must be `user.conf`

Now, create a configMap with this configuration file.

```console
$ kubectl create configmap -n demo pg-custom-config --from-literal=user.conf="$(curl -fsSL https://raw.githubusercontent.com/kubedb/cli/0.11.0/docs/examples/postgres/custom-config/user.conf)"
configmap/pg-custom-config created
```

Verify the config map has the configuration file.

```yaml
$ kubectl get configmap -n demo pg-custom-config -o yaml
apiVersion: v1
data:
  user.conf: |-
    max_connections=300
    shared_buffers=256MB
kind: ConfigMap
metadata:
  creationTimestamp: "2019-02-07T12:08:26Z"
  name: pg-custom-config
  namespace: demo
  resourceVersion: "44214"
  selfLink: /api/v1/namespaces/demo/configmaps/pg-custom-config
  uid: 131b321f-2ad1-11e9-9d44-080027154f61
```

Now, create Postgres crd specifying `spec.configSource` field.

```console
$ kubectl apply -f https://raw.githubusercontent.com/kubedb/cli/0.11.0/docs/examples/postgres/custom-config/pg-custom-config.yaml
postgres.kubedb.com/custom-postgres created
```

Below is the YAML for the Postgres crd we just created.

```yaml
apiVersion: kubedb.com/v1alpha1
kind: Postgres
metadata:
  name: custom-postgres
  namespace: demo
spec:
  version: "9.6-v2"
  configSource:
    configMap:
      name: pg-custom-config
  storage:
    storageClassName: "standard"
    accessModes:
    - ReadWriteOnce
    resources:
      requests:
        storage: 1Gi
```

Now, wait a few minutes. KubeDB operator will create necessary PVC, statefulset, services, secret etc. If everything goes well, we will see that a pod with the name `custom-postgres-0` has been created.

Check that the statefulset's pod is running

```console
$ kubectl get pod -n demo custom-postgres-0
NAME                READY     STATUS    RESTARTS   AGE
custom-postgres-0   1/1       Running   0          14m
```

Check the pod's log to see if the database is ready

```console
$ kubectl logs -f -n demo custom-postgres-0
I0705 12:05:51.697190       1 logs.go:19] FLAG: --alsologtostderr="false"
I0705 12:05:51.717485       1 logs.go:19] FLAG: --enable-analytics="true"
I0705 12:05:51.717543       1 logs.go:19] FLAG: --help="false"
I0705 12:05:51.717558       1 logs.go:19] FLAG: --log_backtrace_at=":0"
I0705 12:05:51.717566       1 logs.go:19] FLAG: --log_dir=""
I0705 12:05:51.717573       1 logs.go:19] FLAG: --logtostderr="false"
I0705 12:05:51.717581       1 logs.go:19] FLAG: --stderrthreshold="0"
I0705 12:05:51.717589       1 logs.go:19] FLAG: --v="0"
I0705 12:05:51.717597       1 logs.go:19] FLAG: --vmodule=""
We want "custom-postgres-0" as our leader
I0705 12:05:52.753464       1 leaderelection.go:175] attempting to acquire leader lease  demo/custom-postgres-leader-lock...
I0705 12:05:52.822093       1 leaderelection.go:184] successfully acquired lease demo/custom-postgres-leader-lock
Got leadership, now do your jobs
Running as Primary
sh: locale: not found

WARNING: enabling "trust" authentication for local connections
You can change this by editing pg_hba.conf or using the option -A, or
--auth-local and --auth-host, the next time you run initdb.
ALTER ROLE
/scripts/primary/start.sh: ignoring /var/initdb/*

LOG:  database system was shut down at 2018-07-05 12:07:51 UTC
LOG:  MultiXact member wraparound protections are now enabled
LOG:  database system is ready to accept connections
LOG:  autovacuum launcher started
```

Once we see `LOG:  database system is ready to accept connections` in the log, the database is ready.

Now, we will check if the database has started with the custom configuration we have provided. We will `exec` into the pod and use [SHOW](https://www.postgresql.org/docs/9.6/static/sql-show.html) query to check the run-time parameters.

```console
 $ kubectl exec -it -n demo custom-postgres-0 sh
 / #
 ## login as user "postgres". no authentication required from inside the pod because it is using trust authentication local connection.
/ # psql -U postgres
psql (9.6.7)
Type "help" for help.

## query for "max_connections"
postgres=# SHOW max_connections;
 max_connections
-----------------
 300
(1 row)

## query for "shared_buffers"
postgres=# SHOW shared_buffers;
 shared_buffers
----------------
 256MB
(1 row)

## log out from database
postgres=# \q
/ #

```

You can also connect to this database from pgAdmin and use following SQL query to check these configuration.

```sql
SELECT name,setting
FROM pg_settings
WHERE name='max_connections' OR name='shared_buffers';
```

## Cleaning up

To cleanup the Kubernetes resources created by this tutorial, run:

```console
kubectl patch -n demo pg/custom-postgres -p '{"spec":{"terminationPolicy":"WipeOut"}}' --type="merge"
kubectl delete -n demo pg/custom-postgres

kubectl delete -n demo configmap pg-custom-config
kubectl delete ns demo
```

If you would like to uninstall KubeDB operator, please follow the steps [here](/docs/setup/uninstall.md).

## Next Steps

- Learn about [taking instant backup](/docs/guides/postgres/snapshot/instant_backup.md) of PostgreSQL database using KubeDB Snapshot.
- Learn how to [schedule backup](/docs/guides/postgres/snapshot/scheduled_backup.md)  of PostgreSQL database.
- Learn about initializing [PostgreSQL with Script](/docs/guides/postgres/initialization/script_source.md).
- Learn about initializing [PostgreSQL from KubeDB Snapshot](/docs/guides/postgres/initialization/snapshot_source.md).
- Want to setup PostgreSQL cluster? Check how to [configure Highly Available PostgreSQL Cluster](/docs/guides/postgres/clustering/ha_cluster.md)
- Monitor your PostgreSQL database with KubeDB using [built-in Prometheus](/docs/guides/postgres/monitoring/using-builtin-prometheus.md).
- Monitor your PostgreSQL database with KubeDB using [CoreOS Prometheus Operator](/docs/guides/postgres/monitoring/using-coreos-prometheus-operator.md).
- Want to hack on KubeDB? Check our [contribution guidelines](/docs/CONTRIBUTING.md).


text:
module Peek
  module Activerecord
    VERSION = "0.1.1"
  end
end


text:
<?php

/**
 * PHPExcel_Writer_Excel2007_Drawing
 *
 * @category   PHPExcel
 * @package    PHPExcel_Writer_Excel2007
 * @copyright  Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
 */
class PHPExcel_Writer_Excel2007_Drawing extends PHPExcel_Writer_Excel2007_WriterPart
{

    /**
     * Write drawings to XML format
     *
     * @param    PHPExcel_Worksheet $pWorksheet
     * @param    int                &$chartRef     Chart ID
     * @param    boolean            $includeCharts Flag indicating if we should include drawing details for charts
     *
     * @return    string                XML Output
     * @throws    PHPExcel_Writer_Exception
     */
    public function writeDrawings( PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = false )
    {

        // Create XML writer
        $objWriter = null;
        if ($this->getParentWriter()->getUseDiskCaching()) {
            $objWriter = new PHPExcel_Shared_XMLWriter( PHPExcel_Shared_XMLWriter::STORAGE_DISK,
                $this->getParentWriter()->getDiskCachingDirectory() );
        } else {
            $objWriter = new PHPExcel_Shared_XMLWriter( PHPExcel_Shared_XMLWriter::STORAGE_MEMORY );
        }

        // XML header
        $objWriter->startDocument( '1.0', 'UTF-8', 'yes' );

        // xdr:wsDr
        $objWriter->startElement( 'xdr:wsDr' );
        $objWriter->writeAttribute( 'xmlns:xdr',
            'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing' );
        $objWriter->writeAttribute( 'xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main' );

        // Loop through images and write drawings
        $i = 1;
        $iterator = $pWorksheet->getDrawingCollection()->getIterator();
        while ($iterator->valid()) {
            $this->_writeDrawing( $objWriter, $iterator->current(), $i );

            $iterator->next();
            ++$i;
        }

        if ($includeCharts) {
            $chartCount = $pWorksheet->getChartCount();
            // Loop through charts and write the chart position
            if ($chartCount > 0) {
                for ($c = 0; $c < $chartCount; ++$c) {
                    $this->_writeChart( $objWriter, $pWorksheet->getChartByIndex( $c ), $c + $i );
                }
            }
        }

        $objWriter->endElement();

        // Return
        return $objWriter->getData();
    }

    /**
     * Write drawings to XML format
     *
     * @param    PHPExcel_Shared_XMLWriter      $objWriter XML Writer
     * @param    PHPExcel_Worksheet_BaseDrawing $pDrawing
     * @param    int                            $pRelationId
     *
     * @throws    PHPExcel_Writer_Exception
     */
    public function _writeDrawing(
        PHPExcel_Shared_XMLWriter $objWriter = null,
        PHPExcel_Worksheet_BaseDrawing $pDrawing = null,
        $pRelationId = -1
    ) {

        if ($pRelationId >= 0) {
            // xdr:oneCellAnchor
            $objWriter->startElement( 'xdr:oneCellAnchor' );
            // Image location
            $aCoordinates = PHPExcel_Cell::coordinateFromString( $pDrawing->getCoordinates() );
            $aCoordinates[0] = PHPExcel_Cell::columnIndexFromString( $aCoordinates[0] );

            // xdr:from
            $objWriter->startElement( 'xdr:from' );
            $objWriter->writeElement( 'xdr:col', $aCoordinates[0] - 1 );
            $objWriter->writeElement( 'xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU( $pDrawing->getOffsetX() ) );
            $objWriter->writeElement( 'xdr:row', $aCoordinates[1] - 1 );
            $objWriter->writeElement( 'xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU( $pDrawing->getOffsetY() ) );
            $objWriter->endElement();

            // xdr:ext
            $objWriter->startElement( 'xdr:ext' );
            $objWriter->writeAttribute( 'cx', PHPExcel_Shared_Drawing::pixelsToEMU( $pDrawing->getWidth() ) );
            $objWriter->writeAttribute( 'cy', PHPExcel_Shared_Drawing::pixelsToEMU( $pDrawing->getHeight() ) );
            $objWriter->endElement();

            // xdr:pic
            $objWriter->startElement( 'xdr:pic' );

            // xdr:nvPicPr
            $objWriter->startElement( 'xdr:nvPicPr' );

            // xdr:cNvPr
            $objWriter->startElement( 'xdr:cNvPr' );
            $objWriter->writeAttribute( 'id', $pRelationId );
            $objWriter->writeAttribute( 'name', $pDrawing->getName() );
            $objWriter->writeAttribute( 'descr', $pDrawing->getDescription() );
            $objWriter->endElement();

            // xdr:cNvPicPr
            $objWriter->startElement( 'xdr:cNvPicPr' );

            // a:picLocks
            $objWriter->startElement( 'a:picLocks' );
            $objWriter->writeAttribute( 'noChangeAspect', '1' );
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            // xdr:blipFill
            $objWriter->startElement( 'xdr:blipFill' );

            // a:blip
            $objWriter->startElement( 'a:blip' );
            $objWriter->writeAttribute( 'xmlns:r',
                'http://schemas.openxmlformats.org/officeDocument/2006/relationships' );
            $objWriter->writeAttribute( 'r:embed', 'rId'.$pRelationId );
            $objWriter->endElement();

            // a:stretch
            $objWriter->startElement( 'a:stretch' );
            $objWriter->writeElement( 'a:fillRect', null );
            $objWriter->endElement();

            $objWriter->endElement();

            // xdr:spPr
            $objWriter->startElement( 'xdr:spPr' );

            // a:xfrm
            $objWriter->startElement( 'a:xfrm' );
            $objWriter->writeAttribute( 'rot', PHPExcel_Shared_Drawing::degreesToAngle( $pDrawing->getRotation() ) );
            $objWriter->endElement();

            // a:prstGeom
            $objWriter->startElement( 'a:prstGeom' );
            $objWriter->writeAttribute( 'prst', 'rect' );

            // a:avLst
            $objWriter->writeElement( 'a:avLst', null );

            $objWriter->endElement();

//						// a:solidFill
//						$objWriter->startElement('a:solidFill');

//							// a:srgbClr
//							$objWriter->startElement('a:srgbClr');
//							$objWriter->writeAttribute('val', 'FFFFFF');

///* SHADE
//								// a:shade
//								$objWriter->startElement('a:shade');
//								$objWriter->writeAttribute('val', '85000');
//								$objWriter->endElement();
//*/

//							$objWriter->endElement();

//						$objWriter->endElement();
            /*
                                    // a:ln
                                    $objWriter->startElement('a:ln');
                                    $objWriter->writeAttribute('w', '88900');
                                    $objWriter->writeAttribute('cap', 'sq');

                                        // a:solidFill
                                        $objWriter->startElement('a:solidFill');

                                            // a:srgbClr
                                            $objWriter->startElement('a:srgbClr');
                                            $objWriter->writeAttribute('val', 'FFFFFF');
                                            $objWriter->endElement();

                                        $objWriter->endElement();

                                        // a:miter
                                        $objWriter->startElement('a:miter');
                                        $objWriter->writeAttribute('lim', '800000');
                                        $objWriter->endElement();

                                    $objWriter->endElement();
            */

            if ($pDrawing->getShadow()->getVisible()) {
                // a:effectLst
                $objWriter->startElement( 'a:effectLst' );

                // a:outerShdw
                $objWriter->startElement( 'a:outerShdw' );
                $objWriter->writeAttribute( 'blurRad',
                    PHPExcel_Shared_Drawing::pixelsToEMU( $pDrawing->getShadow()->getBlurRadius() ) );
                $objWriter->writeAttribute( 'dist',
                    PHPExcel_Shared_Drawing::pixelsToEMU( $pDrawing->getShadow()->getDistance() ) );
                $objWriter->writeAttribute( 'dir',
                    PHPExcel_Shared_Drawing::degreesToAngle( $pDrawing->getShadow()->getDirection() ) );
                $objWriter->writeAttribute( 'algn', $pDrawing->getShadow()->getAlignment() );
                $objWriter->writeAttribute( 'rotWithShape', '0' );

                // a:srgbClr
                $objWriter->startElement( 'a:srgbClr' );
                $objWriter->writeAttribute( 'val', $pDrawing->getShadow()->getColor()->getRGB() );

                // a:alpha
                $objWriter->startElement( 'a:alpha' );
                $objWriter->writeAttribute( 'val', $pDrawing->getShadow()->getAlpha() * 1000 );
                $objWriter->endElement();

                $objWriter->endElement();

                $objWriter->endElement();

                $objWriter->endElement();
            }
            /*

                                    // a:scene3d
                                    $objWriter->startElement('a:scene3d');

                                        // a:camera
                                        $objWriter->startElement('a:camera');
                                        $objWriter->writeAttribute('prst', 'orthographicFront');
                                        $objWriter->endElement();

                                        // a:lightRig
                                        $objWriter->startElement('a:lightRig');
                                        $objWriter->writeAttribute('rig', 'twoPt');
                                        $objWriter->writeAttribute('dir', 't');

                                            // a:rot
                                            $objWriter->startElement('a:rot');
                                            $objWriter->writeAttribute('lat', '0');
                                            $objWriter->writeAttribute('lon', '0');
                                            $objWriter->writeAttribute('rev', '0');
                                            $objWriter->endElement();

                                        $objWriter->endElement();

                                    $objWriter->endElement();
            */
            /*
                                    // a:sp3d
                                    $objWriter->startElement('a:sp3d');

                                        // a:bevelT
                                        $objWriter->startElement('a:bevelT');
                                        $objWriter->writeAttribute('w', '25400');
                                        $objWriter->writeAttribute('h', '19050');
                                        $objWriter->endElement();

                                        // a:contourClr
                                        $objWriter->startElement('a:contourClr');

                                            // a:srgbClr
                                            $objWriter->startElement('a:srgbClr');
                                            $objWriter->writeAttribute('val', 'FFFFFF');
                                            $objWriter->endElement();

                                        $objWriter->endElement();

                                    $objWriter->endElement();
            */
            $objWriter->endElement();

            $objWriter->endElement();

            // xdr:clientData
            $objWriter->writeElement( 'xdr:clientData', null );

            $objWriter->endElement();
        } else {
            throw new PHPExcel_Writer_Exception( "Invalid parameters passed." );
        }
    }

    /**
     * Write drawings to XML format
     *
     * @param    PHPExcel_Shared_XMLWriter $objWriter XML Writer
     * @param    PHPExcel_Chart            $pChart
     * @param    int                       $pRelationId
     *
     * @throws    PHPExcel_Writer_Exception
     */
    public function _writeChart(
        PHPExcel_Shared_XMLWriter $objWriter = null,
        PHPExcel_Chart $pChart = null,
        $pRelationId = -1
    ) {

        $tl = $pChart->getTopLeftPosition();
        $tl['colRow'] = PHPExcel_Cell::coordinateFromString( $tl['cell'] );
        $br = $pChart->getBottomRightPosition();
        $br['colRow'] = PHPExcel_Cell::coordinateFromString( $br['cell'] );

        $objWriter->startElement( 'xdr:twoCellAnchor' );

        $objWriter->startElement( 'xdr:from' );
        $objWriter->writeElement( 'xdr:col', PHPExcel_Cell::columnIndexFromString( $tl['colRow'][0] ) - 1 );
        $objWriter->writeElement( 'xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU( $tl['xOffset'] ) );
        $objWriter->writeElement( 'xdr:row', $tl['colRow'][1] - 1 );
        $objWriter->writeElement( 'xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU( $tl['yOffset'] ) );
        $objWriter->endElement();
        $objWriter->startElement( 'xdr:to' );
        $objWriter->writeElement( 'xdr:col', PHPExcel_Cell::columnIndexFromString( $br['colRow'][0] ) - 1 );
        $objWriter->writeElement( 'xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU( $br['xOffset'] ) );
        $objWriter->writeElement( 'xdr:row', $br['colRow'][1] - 1 );
        $objWriter->writeElement( 'xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU( $br['yOffset'] ) );
        $objWriter->endElement();

        $objWriter->startElement( 'xdr:graphicFrame' );
        $objWriter->writeAttribute( 'macro', '' );
        $objWriter->startElement( 'xdr:nvGraphicFramePr' );
        $objWriter->startElement( 'xdr:cNvPr' );
        $objWriter->writeAttribute( 'name', 'Chart '.$pRelationId );
        $objWriter->writeAttribute( 'id', 1025 * $pRelationId );
        $objWriter->endElement();
        $objWriter->startElement( 'xdr:cNvGraphicFramePr' );
        $objWriter->startElement( 'a:graphicFrameLocks' );
        $objWriter->endElement();
        $objWriter->endElement();
        $objWriter->endElement();

        $objWriter->startElement( 'xdr:xfrm' );
        $objWriter->startElement( 'a:off' );
        $objWriter->writeAttribute( 'x', '0' );
        $objWriter->writeAttribute( 'y', '0' );
        $objWriter->endElement();
        $objWriter->startElement( 'a:ext' );
        $objWriter->writeAttribute( 'cx', '0' );
        $objWriter->writeAttribute( 'cy', '0' );
        $objWriter->endElement();
        $objWriter->endElement();

        $objWriter->startElement( 'a:graphic' );
        $objWriter->startElement( 'a:graphicData' );
        $objWriter->writeAttribute( 'uri', 'http://schemas.openxmlformats.org/drawingml/2006/chart' );
        $objWriter->startElement( 'c:chart' );
        $objWriter->writeAttribute( 'xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart' );
        $objWriter->writeAttribute( 'xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships' );
        $objWriter->writeAttribute( 'r:id', 'rId'.$pRelationId );
        $objWriter->endElement();
        $objWriter->endElement();
        $objWriter->endElement();
        $objWriter->endElement();

        $objWriter->startElement( 'xdr:clientData' );
        $objWriter->endElement();

        $objWriter->endElement();
    }

    /**
     * Write VML header/footer images to XML format
     *
     * @param    PHPExcel_Worksheet $pWorksheet
     *
     * @return    string                                XML Output
     * @throws    PHPExcel_Writer_Exception
     */
    public function writeVMLHeaderFooterImages( PHPExcel_Worksheet $pWorksheet = null )
    {

        // Create XML writer
        $objWriter = null;
        if ($this->getParentWriter()->getUseDiskCaching()) {
            $objWriter = new PHPExcel_Shared_XMLWriter( PHPExcel_Shared_XMLWriter::STORAGE_DISK,
                $this->getParentWriter()->getDiskCachingDirectory() );
        } else {
            $objWriter = new PHPExcel_Shared_XMLWriter( PHPExcel_Shared_XMLWriter::STORAGE_MEMORY );
        }

        // XML header
        $objWriter->startDocument( '1.0', 'UTF-8', 'yes' );

        // Header/footer images
        $images = $pWorksheet->getHeaderFooter()->getImages();

        // xml
        $objWriter->startElement( 'xml' );
        $objWriter->writeAttribute( 'xmlns:v', 'urn:schemas-microsoft-com:vml' );
        $objWriter->writeAttribute( 'xmlns:o', 'urn:schemas-microsoft-com:office:office' );
        $objWriter->writeAttribute( 'xmlns:x', 'urn:schemas-microsoft-com:office:excel' );

        // o:shapelayout
        $objWriter->startElement( 'o:shapelayout' );
        $objWriter->writeAttribute( 'v:ext', 'edit' );

        // o:idmap
        $objWriter->startElement( 'o:idmap' );
        $objWriter->writeAttribute( 'v:ext', 'edit' );
        $objWriter->writeAttribute( 'data', '1' );
        $objWriter->endElement();

        $objWriter->endElement();

        // v:shapetype
        $objWriter->startElement( 'v:shapetype' );
        $objWriter->writeAttribute( 'id', '_x0000_t75' );
        $objWriter->writeAttribute( 'coordsize', '21600,21600' );
        $objWriter->writeAttribute( 'o:spt', '75' );
        $objWriter->writeAttribute( 'o:preferrelative', 't' );
        $objWriter->writeAttribute( 'path', 'm@4@5l@4@11@9@11@9@5xe' );
        $objWriter->writeAttribute( 'filled', 'f' );
        $objWriter->writeAttribute( 'stroked', 'f' );

        // v:stroke
        $objWriter->startElement( 'v:stroke' );
        $objWriter->writeAttribute( 'joinstyle', 'miter' );
        $objWriter->endElement();

        // v:formulas
        $objWriter->startElement( 'v:formulas' );

        // v:f
        $objWriter->startElement( 'v:f' );
        $objWriter->writeAttribute( 'eqn', 'if lineDrawn pixelLineWidth 0' );
        $objWriter->endElement();

        // v:f
        $objWriter->startElement( 'v:f' );
        $objWriter->writeAttribute( 'eqn', 'sum @0 1 0' );
        $objWriter->endElement();

        // v:f
        $objWriter->startElement( 'v:f' );
        $objWriter->writeAttribute( 'eqn', 'sum 0 0 @1' );
        $objWriter->endElement();

        // v:f
        $objWriter->startElement( 'v:f' );
        $objWriter->writeAttribute( 'eqn', 'prod @2 1 2' );
        $objWriter->endElement();

        // v:f
        $objWriter->startElement( 'v:f' );
        $objWriter->writeAttribute( 'eqn', 'prod @3 21600 pixelWidth' );
        $objWriter->endElement();

        // v:f
        $objWriter->startElement( 'v:f' );
        $objWriter->writeAttribute( 'eqn', 'prod @3 21600 pixelHeight' );
        $objWriter->endElement();

        // v:f
        $objWriter->startElement( 'v:f' );
        $objWriter->writeAttribute( 'eqn', 'sum @0 0 1' );
        $objWriter->endElement();

        // v:f
        $objWriter->startElement( 'v:f' );
        $objWriter->writeAttribute( 'eqn', 'prod @6 1 2' );
        $objWriter->endElement();

        // v:f
        $objWriter->startElement( 'v:f' );
        $objWriter->writeAttribute( 'eqn', 'prod @7 21600 pixelWidth' );
        $objWriter->endElement();

        // v:f
        $objWriter->startElement( 'v:f' );
        $objWriter->writeAttribute( 'eqn', 'sum @8 21600 0' );
        $objWriter->endElement();

        // v:f
        $objWriter->startElement( 'v:f' );
        $objWriter->writeAttribute( 'eqn', 'prod @7 21600 pixelHeight' );
        $objWriter->endElement();

        // v:f
        $objWriter->startElement( 'v:f' );
        $objWriter->writeAttribute( 'eqn', 'sum @10 21600 0' );
        $objWriter->endElement();

        $objWriter->endElement();

        // v:path
        $objWriter->startElement( 'v:path' );
        $objWriter->writeAttribute( 'o:extrusionok', 'f' );
        $objWriter->writeAttribute( 'gradientshapeok', 't' );
        $objWriter->writeAttribute( 'o:connecttype', 'rect' );
        $objWriter->endElement();

        // o:lock
        $objWriter->startElement( 'o:lock' );
        $objWriter->writeAttribute( 'v:ext', 'edit' );
        $objWriter->writeAttribute( 'aspectratio', 't' );
        $objWriter->endElement();

        $objWriter->endElement();

        // Loop through images
        foreach ($images as $key => $value) {
            $this->_writeVMLHeaderFooterImage( $objWriter, $key, $value );
        }

        $objWriter->endElement();

        // Return
        return $objWriter->getData();
    }

    /**
     * Write VML comment to XML format
     *
     * @param    PHPExcel_Shared_XMLWriter              $objWriter  XML Writer
     * @param    string                                 $pReference Reference
     * @param    PHPExcel_Worksheet_HeaderFooterDrawing $pImage     Image
     *
     * @throws    PHPExcel_Writer_Exception
     */
    public function _writeVMLHeaderFooterImage(
        PHPExcel_Shared_XMLWriter $objWriter = null,
        $pReference = '',
        PHPExcel_Worksheet_HeaderFooterDrawing $pImage = null
    ) {

        // Calculate object id
        preg_match( '{(\d+)}', md5( $pReference ), $m );
        $id = 1500 + ( substr( $m[1], 0, 2 ) * 1 );

        // Calculate offset
        $width = $pImage->getWidth();
        $height = $pImage->getHeight();
        $marginLeft = $pImage->getOffsetX();
        $marginTop = $pImage->getOffsetY();

        // v:shape
        $objWriter->startElement( 'v:shape' );
        $objWriter->writeAttribute( 'id', $pReference );
        $objWriter->writeAttribute( 'o:spid', '_x0000_s'.$id );
        $objWriter->writeAttribute( 'type', '#_x0000_t75' );
        $objWriter->writeAttribute( 'style',
            "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1" );

        // v:imagedata
        $objWriter->startElement( 'v:imagedata' );
        $objWriter->writeAttribute( 'o:relid', 'rId'.$pReference );
        $objWriter->writeAttribute( 'o:title', $pImage->getName() );
        $objWriter->endElement();

        // o:lock
        $objWriter->startElement( 'o:lock' );
        $objWriter->writeAttribute( 'v:ext', 'edit' );
        $objWriter->writeAttribute( 'rotation', 't' );
        $objWriter->endElement();

        $objWriter->endElement();
    }

    /**
     * Get an array of all drawings
     *
     * @param    PHPExcel $pPHPExcel
     *
     * @return    PHPExcel_Worksheet_Drawing[]        All drawings in PHPExcel
     * @throws    PHPExcel_Writer_Exception
     */
    public function allDrawings( PHPExcel $pPHPExcel = null )
    {

        // Get an array of all drawings
        $aDrawings = array();

        // Loop through PHPExcel
        $sheetCount = $pPHPExcel->getSheetCount();
        for ($i = 0; $i < $sheetCount; ++$i) {
            // Loop through images and add to array
            $iterator = $pPHPExcel->getSheet( $i )->getDrawingCollection()->getIterator();
            while ($iterator->valid()) {
                $aDrawings[] = $iterator->current();

                $iterator->next();
            }
        }

        return $aDrawings;
    }
}


text:
import _plotly_utils.basevalidators

class ZsrcValidator(_plotly_utils.basevalidators.SrcValidator):
    def __init__(self, plotly_name="zsrc", parent_name="isosurface", **kwargs):
        super(ZsrcValidator, self).__init__(
            plotly_name=plotly_name,
            parent_name=parent_name,
            edit_type=kwargs.pop("edit_type", "none"),
            **kwargs,
        )


text:
using MoonSharp.Interpreter.Debugging;
using MoonSharp.Interpreter.Execution;
using MoonSharp.Interpreter.Execution.VM;

namespace MoonSharp.Interpreter.Tree.Statements
{
    internal class WhileStatement : Statement
    {
        private readonly Statement m_Block;
        private readonly Expression m_Condition;
        private readonly SourceRef m_End;
        private readonly RuntimeScopeBlock m_StackFrame;
        private readonly SourceRef m_Start;

        public WhileStatement(ScriptLoadingContext lcontext)
            : base(lcontext)
        {
            var whileTk = CheckTokenType(lcontext, TokenType.While);

            m_Condition = Expression.Expr(lcontext);

            m_Start = whileTk.GetSourceRefUpTo(lcontext.Lexer.Current);

            //m_Start = BuildSourceRef(context.Start, exp.Stop);
            //m_End = BuildSourceRef(context.Stop, context.END());

            lcontext.Scope.PushBlock();
            CheckTokenType(lcontext, TokenType.Do);
            m_Block = new CompositeStatement(lcontext);
            m_End = CheckTokenType(lcontext, TokenType.End).GetSourceRef();
            m_StackFrame = lcontext.Scope.PopBlock();

            lcontext.Source.Refs.Add(m_Start);
            lcontext.Source.Refs.Add(m_End);
        }

        public override void Compile(ByteCode bc)
        {
            var L = new Loop
            {
                Scope = m_StackFrame
            };

            bc.LoopTracker.Loops.Push(L);

            bc.PushSourceRef(m_Start);

            var start = bc.GetJumpPointForNextInstruction();

            m_Condition.Compile(bc);
            var jumpend = bc.Emit_Jump(OpCode.Jf, -1);

            bc.Emit_Enter(m_StackFrame);

            m_Block.Compile(bc);

            bc.PopSourceRef();
            bc.Emit_Debug("..end");
            bc.PushSourceRef(m_End);

            bc.Emit_Leave(m_StackFrame);
            bc.Emit_Jump(OpCode.Jump, start);

            bc.LoopTracker.Loops.Pop();

            var exitpoint = bc.GetJumpPointForNextInstruction();

            foreach (var i in L.BreakJumps)
                i.NumVal = exitpoint;

            jumpend.NumVal = exitpoint;

            bc.PopSourceRef();
        }
    }
}