text:
# Polymer Primer

Below is a description of current Polymer features, followed by individual feature guides.

**Basic Custom Element sugaring**

| Feature | Usage
|---------|-------
| [Custom element constructor](#element-constructor) | Polymer.Class({ … });
| [Custom element registration](#register-element) | Polymer({ is: '...',  … }};
| [Bespoke constructor support](#bespoke-constructor) | factoryImpl: function() { … }
| [Basic lifecycle callbacks](#basic-callbacks) | created, attached, detached, attributeChanged
| [Native HTML element extension](#type-extension) | extends: '…'
| [Property configuration](#property-config) | properties: { … }
| [Attribute deserialization to property](#attribute-deserialization) | properties: { \<property>: \<Type> }
| [Static attributes on host](#host-attributes) | hostAttributes: { \<attribute>: \<value> }
| [Behavior mixins](#behaviors) | behaviors: [ … ]

**Template stamped into "local DOM" and tree lifecycle**

| Feature | Usage
|---------|-------
| [Template stamping into local DOM](#template-stamping) | \<dom-module>\<template>...\</template>\</dom-module>
| [Scoped styling](#scoped-styling) | \

  <template>

In local Dom!

<content></content>

  </template>

  <script>

      Polymer({
          is: 'my-element'
      });

  </script>

</dom-module>
```

Loading external stylesheets (as opposed to defining them inline in HTML) for styling local DOM is currently supported via a special [`<link rel="import" type="css">`](#external-stylesheets) import tag (as opposed to a `<link rel="stylesheet">`).

<a name="dom-distribution"></a>
## DOM (re-)distribution

To support composition of an element's light DOM with its local DOM, Polymer supports the `<content>` element. The `<content>` element provides an insertion point at which an element's light DOM is combined with its local DOM. The `<content>` element supports a `select` attribute which filters nodes via a simple selector.

Polymer supports multiple local DOM implementations. On browsers that support ShadowDOM, ShadowDOM may be used to create local DOM. On other supported browsers, Polymer provides local DOM via a custom implementation called ShadyDOM which is inspired by and compatible with ShadowDOM.

Example:

```html
<template>
  Local dom header followed by distributed dom.
  <content select=".content"></content>
  Footer after distributed dom.
</template>
```
<a name="dom-api"></a>
## DOM API

Polymer provides custom API for manipulating DOM such that local DOM and light DOM trees are properly maintained.

**<div style="color:red">Note: All DOM manipulation must use this API, as opposed to DOM API directly on nodes.</div>**

The following methods are provided:

  * `Polymer.dom(parent).appendChild(node)`
  * `Polymer.dom(parent).insertBefore(node, beforeNode)`
  * `Polymer.dom(parent).removeChild(node)`
  * `Polymer.dom(parent).replaceChild(oldNode, newNode)`
  * `Polymer.dom(parent).querySelector(selector)`
  * `Polymer.dom(parent).querySelectorAll(selector)`
  * `Polymer.dom(parent).childNodes`
  * `Polymer.dom(parent).firstChild`
  * `Polymer.dom(parent).lastChild`
  * `Polymer.dom(node).previousSibling`
  * `Polymer.dom(node).nextSibling`
  * `Polymer.dom(parent).children`
  * `Polymer.dom(parent).firstElementChild`
  * `Polymer.dom(parent).lastElementChild`
  * `Polymer.dom(node).previousElementSibling`
  * `Polymer.dom(node).nextElementSibling`
  * `Polymer.dom(node).textContent`
  * `Polymer.dom(node).innerHTML`
  * `Polymer.dom(node).parentNode`
  * `Polymer.dom(contentElement).getDistributedNodes()`
  * `Polymer.dom(node).getDestinationInsertionPoints()`
  * `Polymer.dom.flush()` - The insert, append, and remove operations are transacted lazily in certain cases for performance.  In order to interrogate the dom (e.g. `offsetHeight`, `getComputedStyle`, etc.) immediately after one of these operations, call `Polymer.dom.flush()` first.

Calling `append`/`insertBefore` where `parent` is a custom Polymer element adds the node to the light DOM of the element.  In order to insert/append into the shadow root of a custom element, use `this.root` as the parent.

`Polymer.dom` properties and methods that return a list of nodes return an `Array`, not a `NodeList` like the standard DOM equivalent.

Example:

```js
var toLight = document.createElement('div');
Polymer.dom(this).appendChild(toLight);

var toLocal = document.createElement('div');
var beforeNode = Polymer.dom(this.root).childNodes[0];
Polymer.dom(this.root).insertBefore(toLocal, beforeNode);

var allSpans = Polymer.dom(this).querySelectorAll('span');
```

You can use `Polymer.dom` on any node, whether or not it has a local DOM tree:

Example:

```html
<template>

     <content></content>

</template>

...

var insert = document.createElement('div');
Polymer.dom(this.$.container).insertBefore(insert, this.$.first);

```

Sometimes it's necessary to access the elements which have been distributed to a given `<content>` insertion point or to know to which `<content>` a given node has been distributed. The `getDistributedNodes` and `getDestinationInsertionPoints` respectively provide this information.

Example:

```html
<x-foo>

</x-foo>

// x-foo's template
<template>
  <content></content>
</template>
```

```js
var div = Polymer.dom(xFoo).querySelector('div');
var content = Polymer.dom(xFoo.root).querySelector('content');
var distributed = Polymer.dom(content).getDistributedNodes()[0];
var insertedTo = Polymer.dom(div).getDestinationInsertionPoints();

// the following should be true:
assert.equal(distributed, div);
assert.equal(insertedTo, content)
```

<a name="configure-values"></a>
## Configuring default property values

Default values for properties may be specified in the `properties` object using the `value` field.  The value may either be a primitive value, or a function that returns a value (which should be used for initializing Objects and Arrays to avoid shared objects on instances).

Example:

```js
Polymer({

  is: 'x-custom',

  properties: {

    mode: {
      type: String,
      value: 'auto'
    },

    data: {
      type: Object,
      notify: true,
      value: function() { return {}; }
    }

  }

});
```
<a name="ready-method"></a>
## Ready callback

The `ready` method is part of an element's lifecycle and is automatically called 'bottom-up' after the element's template has been stamped and all elements inside the element's local DOM have been configured (with values bound from parents, deserialized attributes, or else default values) and had their `ready` method called. Implement `ready` when it's necessary to manipulate an element's local DOM when the element is constructed.

Example:

```js
ready: function() {
  this.$.ajax.go();
}
```

# Declarative data binding, event handlers, and property effects

<a name="node-marshaling"></a>
## Local node marshaling

Polymer automatically builds a map of instance nodes stamped into its local DOM, to provide convenient access to frequently used nodes without the need to query for (and memoize) them manually.  Any node specified in the element's template with an `id` is stored on the `this.$` hash by `id`.

Example:

```html
<dom-module id="x-custom">
  <template>
    Hello World from !
  </template>

  <script>

    Polymer({

      is: 'x-custom',

      ready: function() {
        this.$.name.textContent = this.name;
      }

    });

  </script>
</dom-module>
```

<a name="event-listeners"></a>
## Event listener setup

Event listeners can be added to the host element by providing an object-valued `listeners` property that maps events to event handler function names.

Example:

```html
<dom-module id="x-custom">
  <template>

I will respond

to a click on

any of my children!

  </template>

  <script>

    Polymer({

      is: 'x-custom',

      listeners: {
        'click': 'handleClick'
      },

      handleClick: function(e) {
        alert("Thank you for clicking");
      }

    });

  </script>
</dom-module>
```

<a name="annotated-listeners"></a>
## Annotated event listener setup

For adding event listeners to local-DOM children, a more convenient `on-<event>` annotation syntax is supported directly in the template.  This often eliminates the need to give an element an `id` solely for the purpose of binding an event listener.

Example:

```html
<dom-module id="x-custom">
  <template>
    <button on-click="handleClick">Kick Me</button>
  </template>

  <script>

    Polymer({

      is: 'x-custom',

      handleClick: function() {
        alert('Ow!');
      }

    });

  </script>
</dom-module>
```

<a name="gesture-events"></a>
## Gesture events

Polymer will generate and fire a custom "gesture" event for certain user interactions automatically when a declarative listener is added for the event type.  These events will fire consistenly on both touch and mouse environments, and so it is advised to listen for these events rather than their mouse- or touch-specific event counterparts for interoperability with both touch and desktop/mouse environments.  For example, `tap` should be used instead of `click` for the most reliable cross-platform results.

For convenience, calling `preventDefault` on gesture events will prevent the native event that generated that gesture. For example, calling `preventDefault` on a `tap` event will also call `preventDefault` on the `click` event that generated the `tap`.

Certain gestures will be able to control scrolling direction for touch input. For example, nodes with a listener for the `track` event will prevent scrolling by default. Elements can be override scroll direction with `this.setScrollDirection(direction, node)`, where `direction` is one of `'x'`, `'y'`, `'none'`, or `'all'`, and `node` defaults to `this`.

The following are the gesture event types supported, with a short description and list of detail properties available on `event.detail` for each type:

* **down** - finger/button went down
  * `x` - clientX coordinate for event
  * `y` - clientY coordinate for event
  * `prevent(type)` - a function that may be called to prevent the given gesture events. Currently supported gestures to prevent are `tap` and `track`.
  * `sourceEvent` - the original DOM event that caused the `down` action
* **up** - finger/button went up
  * `x` - clientX coordinate for event
  * `y` - clientY coordinate for event
  * `prevent(type)` - a function that may be called to prevent the given gesture events. Currently supported gestures to prevent are `tap` and `track`.
  * `sourceEvent` - the original DOM event that caused the `up` action
* **tap** - down & up occurred
  * `x` - clientX coordinate for event
  * `y` - clientY coordinate for event
  * `sourceEvent` - the original DOM event that caused the `tap` action
* **track** - moving while finger/button is down
  * `state` - a string indicating the tracking state:
      * `start` - fired when tracking is first detected (finger/button down and moved past a pre-set distance threshold)
      * `track` - fired while tracking
      * `end` - fired when tracking ends
  * `x` - clientX coordinate for event
  * `y` - clientY coordinate for event
  * `dx` - change in pixels horizontally since the first track event
  * `dy` - change in pixels vertically since the first track event
  * `ddx` - change in pixels horizontally since last track event
  * `ddy` - change in pixels vertically since last track event
  * `hover()` - a function that may be called to determine the element currently being hovered over

Example:

```html
<dom-module id="drag-me">
  <style>
    #dragme {
      width: 500px;
      height: 500px;
      background: gray;
    }
  </style>
  <template>

{{message}}

  </template>

  <script>

    Polymer({

      is: 'drag-me',

      handleTrack: function(e) {
        switch(e.detail.state) {
          case 'start':
            this.message = 'Tracking started!';
            break;
          case 'track':
            this.message = 'Tracking in progress... ' +
              e.detail.x + ', ' + e.detail.y;
            break;
          case 'end':
            this.message = 'Tracking ended!';
            break;
        }
      }

    });

  </script>
</dom-module>
```
Example with `listeners`:

```html
<dom-module id="drag-me">
  <style>
    :host {
      width: 500px;
      height: 500px;
      background: gray;
    }
  </style>

  <script>

    Polymer({

      is: 'drag-me',

      listeners: {
        track: 'handleTrack'
      },

      handleTrack: function(e) {
        switch(e.detail.state) {
          case 'start':
            this.message = 'Tracking started!';
            break;
          case 'track':
            this.message = 'Tracking in progress... ' +
              e.detail.x + ', ' + e.detail.y;
            break;
          case 'end':
            this.message = 'Tracking ended!';
            break;
        }
      }

    });

  </script>
</dom-module>
```

<a name="change-callbacks"></a>
## Property change callbacks (observers)

### Single property observation

Custom element properties may be observed for changes by specifying `observer` property in the `properties` for the property that gives the name of a funciton to call.  When the property changes, the change handler will be called with the new and old values as arguments.

Example:

```js
Polymer({

  is: 'x-custom',

  properties: {
    disabled: {
      type: Boolean,
      observer: 'disabledChanged'
    },
    highlight: {
      observer: 'highlightChanged'
    }
  },

  disabledChanged: function(newValue, oldValue) {
    this.toggleClass('disabled', newValue);
    this.highlight = true;
  },

  highlightChanged: function() {
    this.classList.add('highlight');
    setTimeout(function() {
      this.classList.remove('highlight');
    }, 300);
  }

});
```

Note that property change observation is achieved in Polymer by installing setters on the custom element prototype for properties with registered interest (as opposed to observation via Object.observe or dirty checking, for example).

<a name="multiple-observation"></a>
### Multiple property observation

Observing changes to multiple properties is supported via the `observers` array on the prototype, using a string containing a method signature that includes any dependent arguments.  Once all properties are defined (`!== undefined`), the observer method will be called once for each change to a dependent property.  The current values of the dependent properties will be passed as arguments to the observer method in the order defined in the `observers` method signature.

*Note, multiple-property observers will only be called once all dependent properties are defined (`!== undefined`).  If one or more of the properties are optional, they would need default `value`'s defined in `properties` to ensure the observer is called.*

*Note that any observers defined in the `observers` array will not receive `old` values as arguments, only new values.  Only single-property observers defined in the `properties` object received both `old` and `new` values.*

Example:

```js
Polymer({

  is: 'x-custom',

  properties: {
    preload: Boolean,
    src: String,
    size: String
  },

  observers: [
    'updateImage(preload, src, size)'
  ],

  updateImage: function(preload, src, size) {
    // ... do work using dependent values
  }

});
```

<a name="path-observation"></a>
### Path observation

Observing changes to object sub-properties is also supported via the same `observers` array, by specifying a path (e.g. `user.manager.name`).

Example:

```js
Polymer({

  is: 'x-custom',

  properties: {
    user: Object
  },

  observers: [
    'userManagerChanged(user.manager)'
  ],

  userManagerChanged: function(user) {
    console.log('new manager name is ' + user.name);
  }

});
```

*Note that observing changes to paths (object sub-properties) is dependent on one of two requirements: either the value at the path in question changed via a two-way Polymer [property binding](#property-binding) to another element, or the value was changed using the [`set`](#set-path) API, which provides the required notification to elements with registered interest.*

<a name="deep-observation"></a>
### Deep path observation

Additionally, wildcard matching of path changes is also supported via the `observers` array, which allows notification when any (deep) sub-property of an object changes.  Note that the argument passed for a path with a wildcard is a change record object containing the `path` that changed, the new `value` of the path that changed, and the `base` value of the wildcard expression.

Example:

```js
Polymer({

  is: 'x-custom',

  properties: {
    user: Object
  },

  observers: [
    'userManagerChanged(user.manager.*)'
  ],

  userManagerChanged: function(changeRecord) {
    if (changeRecord.path == 'user.manager') {
      // user.manager object itself changed
      console.log('new manager name is ' + changeRecord.base.name);
    } else {
      // sub-property of user.manager changed
      console.log(changeRecord.path + ' changed to ' + changeRecord.value);
    }
  }

});
```

<a name="array-observation"></a>
### Array observation

Finally, mutations to arrays (e.g. changes resulting from calls to `push`, `pop`, `shift`, `unshift`, and `splice`, generally referred to as "splices") may be observed via the `observers` array by giving a path to an array followd by `.splices` as an argument to the observer function.  The value received by the observer for the `splices` path of an array will be a change record containing `indexSplices` and `keySplices` arrays listing the set of changes that occurred to the array, either in terms of array indicies or "keys" used by Polymer for identifying array elements.  Each `indexSplices` record contains a start `index`, array of `removed` items, and `addedCount` of items inserted.  Each `keySplices` record contains an array of `added` and `removed` keys).

```js
Polymer({

  is: 'x-custom',

  properties: {
    users: Array
  },

  observers: [
    'usersAddedOrRemoved(users.splices)'
  ],

  usersAddedOrRemoved: function(changeRecord) {
    changeRecord.indexSplices.forEach(function(s) {
      s.removed.forEach(function(user) {
        console.log(user.name + ' was removed');
      });
      console.log(s.addedCount + ' users were added');
    }, this);
  }

});
```

*Note that observing changes to arrays is dependent on the change to the array being made through one of the [array mutation API's](#array-mutation) provided on Polymer elements, which provides the required notification to elements with registered interest.*

Note that an observer for a wildcard path of an array will be called for both splices as well as array element sub-property changes.  Hence, the observer in the following example will be called for all additions, removals, and deep changes that occur in the array:

```js
Polymer({

  is: 'x-custom',

  properties: {
    users: Array
  },

  observers: [
    'usersChanged(users.*)'
  ],

  usersChanged: function(changeRecord) {
    if (changeRecord.path == 'users.splices') {
      // a user was added or removed
    } else {
      // an individual user or its sub-properties changed
      // check `changeRecord.path` to determine what changed
    }
  }

});
```

<a name="property-binding"></a>
## Annotated property binding

### Basic property binding

Properties of the custom element may be bound into text content or properties of local DOM elements using binding annotations in the template.

To bind to textContent, the binding annotation must currently span the entire content of the tag:

```html
<dom-module id="user-view">
  <template>

    First: {{first}}

    Last: {{last}}

First: {{first}}

Last: {{last}}

  </template>

  <script>

    Polymer({

      is: 'user-view',

      properties: {
        first: String,
        last: String
      }

    });

  </script>

</dom-module>

<user-view first="Samuel" last="Adams"></user-view>

```

To bind to properties, the binding annotation should be provided as the value to an attribute with the same name of the JS property to bind to:

```html
<dom-module id="main-view">
  <template>
    <user-view first="{{user.first}}" last="{{user.last}}"></user-view>
  </template>

  <script>

    Polymer({

      is: 'main-view',

      properties: {
        user: Object
      }

    });

  </script>
</dom-module>
```

As in the example above, paths to object sub-properties may also be specified in templates.  See [Binding to structured data](#path-binding) for details.

In order to bind to camel-case properties of elements, dash-case should be used in the attribute name.  Example:

```html
<user-view first-name="{{managerName}}"></user-view>

```

Note that while HTML attributes are used to specify bindings, values are assigned directly to JS properties, not to the HTML attributes of the elements unless specific [attribute bindings](#attribute-binding) are used.

<a name="property-notification"></a>
### Property change notification and Two-way binding

Polymer supports cooperative two-way binding between elements, allowing elements that "produce" data or changes to data to propagate those changes upwards to hosts when desired.

When a Polymer elements changes a property that was configured in `properties` with the `notify` flag set to true, it automatically fires a non-bubbling DOM event to indicate those changes to interested hosts.  These events follow a naming convention of `<property>-changed`, and contain a `value` property in the `event.detail` object indicating the new value.

As such, one could attach an `on-<property>-changed` listener to an element to be notified of changes to such properties, set the `event.detail.value` to a property on itself, and take necessary actions based on the new value.  However, given this is a common pattern, bindings using "curly-braces" (e.g. `{{property}}`) will automatically perform this upwards binding automatically without the user needing to perform those tasks.  This can be disabled by using "square-brace" syntax (e.g. `[[property]]`), which results in only one-way (downward) data-binding.

To summarize, two-way data-binding is achieved when both the host and the child agree to participate, satisfying these three conditions:

1. The host must use curly-brace `{{property}}` syntax.  Square-brace `[[property]]` syntax results in one-way downward binding, regardless of the notify state of the child's property.
2. The child property being bound to must be configured with the `notify` flag set to true (or otherwise send a `<property>-changed` custom event).  If the property being bound does not have the `notify` flag set, only one-way (downward) binding will occur.
3. The child property being bound to must not be configured with the `readOnly` flag set to true.  If the child property is `notify: true` and `readOnly:true`, and the host binding uses curly-brace syntax, the binding will effectively be one-way (upward).

Example 1: Two-way binding

```html
<script>

  Polymer({
    is: 'custom-element',
    properties: {
      prop: {
        type: String,
        notify: true
      }
    }
  });

</script>
...

<custom-element prop="{{value}}"></custom-element>
```

Example 2: One-way binding (downward)

```html
<script>
  Polymer({
    is: 'custom-element',
    properties: {
      prop: {
        type: String,
        notify: true
      }
    }
  });
</script>

...

<custom-element prop="[[value]]"></custom-element>
```

Example 3: One-way binding (downward)

```html
<script>

  Polymer({
    is: 'custom-element',
    properties: {
      prop: String    // no `notify:true`!
    }
  });

</script>
...

<custom-element prop="{{value}}"></custom-element>
```

Example 4: One-way binding (upward)

```html
<script>
  Polymer({
    is: 'custom-element',
    properties: {
      prop: {
          type: String,
          notify: true,
          readOnly: true
        }
    }
  });
</script>

...

<custom-element prop="{{value}}"></custom-element>
```

Example 5: Error / non-sensical state

```html
<script>

  Polymer({
    is: 'custom-element',
    properties: {
      prop: {
          type: String,
          notify: true,
          readOnly: true
        }
    }
  });

</script>

...

<custom-element prop="[[value]]"></custom-element>
```

### Custom notify event and binding to native elements

As mentioned above, Polymer uses an event naming convention to achieve two-way binding.  The act of two-way binding to a property using `target-prop={{hostProp}}` syntax results in Polymer adding a `<target-prop>-changed` event listener to the element by default.  All properties of a Polymer element with `notify: true` send events using this convention to notify of changes.

In order to two-way bind to native elements or non-Polymer elements that do not follow this event naming convention when notifying changes, you may specify a custom event name in the curley braces, delimited with `::`.

Example:

```html

<input value="{{hostValue::input}}">

<input type="checkbox" checked="{{hostChecked::change}}">

<video url="..." current-time="{{hostTime::timeupdate}}">
```

Note: When binding to standard notifying properties on Polymer elements, specifying the event name is unnecessary, as the default convention will be used.  The following constructions are equivalent:

```html

<my-element value="{{hostValue::value-changed}}">

<my-element value="{{hostValue}}">

```

<a name="path-binding"></a>
### Binding to structured data

Sub-properties of objects may be two-way bound to properties of custom elements as well by specifying the path of interest to the binding annotation.

Example:

```html
<template>

{{user.manager.name}}

  <user-element user="{{user}}"></user-element>
</template>
```

As with change handlers for paths, bindings to paths (object sub-properties) are dependent on one of two requirements: either the value at the path in question changed via a Polymer [property binding](#property-binding) to another element, or the value was changed using the [`set`](#set-path) API, which provides the required notification to elements with registered interest, as discussed below.

Note that path bindings are distinct from property bindings in a subtle way: when a property's value changes, an assignment must occur for the value to propagate to the property on the element at the other side of the binding.  However, if two elements are bound to the same path of a shared object and the value at that path changes (via a property binding or via `set`), the value seen by both elements actually changes with no additional assignment necessary, by virtue of it being a property on a shared object reference.  In this case, the element who changed the path must notify the system so that other elements who have registered interest in the same path may take side effects.  However, there is no concept of one-way binding in this case, since there is no concept of propagation.  That is, all bindings and change handlers for the same path will always be notified and update when the value of the path changes.

<a name="set-path"></a>
### Path change notification

Two-way data-binding and observation of paths in Polymer is achieved using a similar strategy to the one described above for [2-way property binding](#property-notification): When a sub-property of a property configured with `type: Object` changes, an element fires a non-bubbling `<property>-changed` DOM event with a `detail.path` value indicating the path on the object that changed.  Elements that have registered interest in that object (either via binding or change handler) may then take side effects based on knowledge of the path having changed.  Finally, those elements will forward the notification on to any children they have bound the object to, and will also fire a new `<property>-changed` event where `property` is the root object, to notify any hosts that may have bound root object down.  Through this method, a notification will reach any part of the tree that has registered interest in that path so that side effects occur.

This system "just works" to the extent that changes to object sub-properties occur as a result of being bound to a notifying custom element property that changed.  However, sometimes imperative code needs to "poke" at an object's sub-properties directly.  As we avoid more sophisticated observation mechanisms such as Object.observe or dirty-checking in order to achieve the best startup and runtime performance cross-platform for the most common use cases, changing an object's sub-properties directly requires cooperation from the user.

Specifically, Polymer provides several API's that allow such changes to be notified to the system: `notifyPath(path, value)` and `set(path, value)`, as well as a full set of [array mutation API's](#array-mutation).

Example:

```html
<dom-module id="custom-element">
  <template>

{{user.manager.name}}

  </template>

  <script>
    Polymer({

      is: 'custom-element',

      reassignManager: function(newManager) {
        this.user.manager = newManager;
        // Notification required for binding to update!
        this.notifyPath('user.manager', this.user.manager);
      }

    });
  </script>
</dom-module>
```

Since in the majority of cases, `notifyPath` will be called directly after an assignment, a convenience function `set` is provided that performs both the assignment and notify actions:

```js
reassignManager: function(newManager) {
  this.set('user.manager', newManager);
}
```

<a name="array-mutation"></a>
### Array mutation

When modifying arrays, a set of array mutation API's are provided on Polymer
element prototypes which mimic `Array.prototype` API's, with the exception that
they take a `path` API as the first argument.  The `path` argument identifies
an array on the element to mutate, with the following arguments matching those
of the native `Array` methods.  These methods perform the mutation action on
the array, and then notify other elements that may be bound to the same
array of the changes.  Using these methods when mutating arrays is required
to ensure elements that deal with arrays are kept in sync.

Every Polymer element has the following array mutation API's available:

* `push(path, item1, [..., itemN])`
* `pop(path)`
* `unshift(path, item1, [..., itemN])`
* `shift(path)`
* `splice(path, index, removeCount, [item1, ..., itemN]`

Example:

```html
<dom-module id="custom-element">
  <template>
    <template is="dom-repeat">{{users}}

  </template>

  <script>
    Polymer({

      is: 'custom-element',

      addUser: function(user) {
        this.push('users', user);
      },

      removeUser: function(user) {
        var index = this.users.indexOf(user);
        this.splice('users', index, 1);
      }

    });
  </script>
</dom-module>
```

### Expressions in binding annotations

Currently the only binding expression supported in Polymer binding annotations is negation using `!`:

Example:

```html
<template>

</template>
```

<a name="attribute-binding"></a>
## Declarative attribute binding

In the vast majority of cases, binding data to other elements should use property binding described above, where changes are propagated by setting the new value to the JavaScript property on the element.

However, there may be cases where a user actually needs to set an attribute on an element, as opposed to a property.  These include a handful of [problematic native HTML attributes](#native-binding), when attribute selectors are used for CSS or for for interoperability with elements that require using attribute-based API.

Polymer provides an alternate binding annotation syntax to make it explicit when binding values to attributes is desired by using `$=` rather than `=`.  This results in in a call to `element.setAttribute('<attr>', value);`, as opposed to `element.property = value;`.

```html
<template>

  <my-element selected$="{{value}}"></my-element>

  <my-element selected="{{value}}"></my-element>

</template>
```

Values will be serialized according to type: Arrays/Objects will be `JSON.stringify`'ed, booleans will result in a non-valued attribute to be either set or removed, and `Dates` and all primitive types will be serialized using the value returned from `toString`.

Again, as values must be serialized to strings when binding to attributes, it is always more performant to use property binding for pure data propagation.

<a name="native-binding"></a>
## Binding to native element attributes

There are a handful of extremely common native element attributes which can also be modified as properties.  Due to cross-browser limitations with the ability to place binding braces `{{...}}` in some of these attribute values, as well as the fact that some of these attributes map to differently named JS properties, it is recommended to always use attribute binding (using `$=`) when binding dynamic values to these specific attributes, rather than binding to their property names.

Normal attribute assignment to static values:

```html

```

Attribute binding to dynamic values (use `$=`):

```html

```

<a name="attribute-reflection"></a>
## Reflecting properties to attributes

In specific cases, it may be useful to keep an HTML attribute value in sync with a property value.  This may be achieved by setting `reflectToAttribute: true` on a property in the `properties` configuration object.  This will cause any change to the property to be serialized out to an attribute of the same name.

```html
<script>
  Polymer({

    properties: {
     response: {
        type: Object,
        reflectToAttribute: true
     }
    },

    responseHandler: function(response) {
      this.response = 'loaded';
      // results in this.setAttribute('response', 'loaded');
    }

  });
</script>
```

<a name="attribute-serialization'></a>
Values will be serialized according to type; by default Arrays/Objects will be `JSON.stringify`'ed, booleans will result in a non-valued attribute to be either set or removed, and `Dates` and all primitive types will be serialized using the value returned from `toString`.  The `serialize` method may be overridden to supply custom object serialization.

<a name="computed-properties"></a>
## Computed properties

Polymer supports virtual properties whose values are calculated from other properties.  Computed properties can be defined in the `properties` object by providing a `computed` key mapping to a computing function.  The name of the function to compute the value is provided as a string with dependent properties as arguments in parenthesis.  Once all properties are defined (`!== undefined`), the computing function will be called to update the computed property once for each change to a dependent property.

*Note, computing functions will only be called once all dependent properties are defined (`!=undefined`).  If one or more of the properties are optional, they would need default `value`'s defined in `properties` to ensure the property is computed.*

Computed properties are implicitly `readOnly`, and cannot be manually set.

```html
<dom-module id="x-custom">
  <template>
    My name is {{fullName}}
  </template>

  <script>
    Polymer({

      is: 'x-custom',

      properties: {

        first: String,

        last: String,

        fullName: {
          type: String,
          // when `first` or `last` changes `computeFullName` is called once
          // (asynchronously) and the value it returns is stored as `fullName`
          computed: 'computeFullName(first, last)'
        }

      },

      computeFullName: function(first, last) {
        return first + ' ' + last;
      }

      ...

    });
  </script>
</dom-module>
```

Note that arguments to computing functions may be simple properties on the element, as well as all of the arguments types supported by `observers`, including [paths](#path-observation), [paths with wildcards](#deep-observation), and [paths to array splices](#array-observation).  The arguments received in the comuting function will match those described in the sections referenced above.

<a name="annotated-computed"></a>
## Annotated computed properties

Anonymous computed properties may also be placed directly in template binding annotations.  This is useful when the property need not be a part of the element's API or otherwise used by logic in the element, and is only used for downward data propagation.

*Note: this is the only form of functions allowed in template bindings, and they must specify one or more dependent properties as arguments, otherwise the function will not be called.*

*Note, computing functions will only be called once all dependent properties are defined (`!=undefined`).  If one or more of the properties are optional, they would need default `value`'s defined in `properties` to ensure the property is computed.*

Example:

```html
<dom-module id="x-custom">
  <template>
    My name is {{computeFullName(first, last)}}
  </template>

  <script>
   Polymer({

     is: 'x-custom',

     properties: {

       first: String,

       last: String

     },

     computeFullName: function(first, last) {
       return first + ' ' + last;
     }

     ...

   });
  </script>

</dom-module>
```

Note that literal strings and numbers may be used as arguments to annotated computed properties.  Strings may be either single- or double-quoted (taking care to use the opposite of the quotes used for the attribute value itself for attribute/property binding).  __Note that if the string includes commas, the _must_ be escaped using a `\`.__

Example:

```html
<dom-module id="x-custom">
  <template>
    {{translate('Hello\, nice to meet you', first, last)}}
  </template>
</dom-module>
```

Finally, annotated computed properties may be argument-less, in which case they are evaluated once.

```html
<dom-module id="x-custom">
  <template>
    {{doThisOnce()}}
  </template>

  <script>
   Polymer({

     is: 'x-custom',

     doThisOnce: function() {
       return Math.random();
     }

   });
  </script>
</dom-module>
```

<a name="read-only"></a>
## Read-only properties

When a property only "produces" data and never consumes data, this can be made explicit to avoid accidental changes from the host by setting the `readOnly` flag to `true` in the `properties` property definition.  In order for the element to actually change the value of the property, it must use a private generated setter of the convention `_set<Property>(value)`.

```html
<script>
  Polymer({

    properties: {
      response: {
        type: Object,
        readOnly: true,
        notify: true
      }
    },

    responseHandler: function(response) {
      this._setResponse(response);
    }

    ...

  });
</script>
```

Generally, read-only properties should also be set to `notify: true` such that their changes are observable from above.

<a name="xscope-stadyling"></a>
## Cross-scope styling

### Background

Shadow DOM (and its approximation via Shady DOM) bring much needed benefits of scoping and style encapsulation to web development, making it safer and easier to reason about the effects of CSS on parts of your application.  Styles do not leak into the local DOM from above, and styles do not leak from one local DOM into the local DOM of other elements inside.

This is great for *protecting* scopes from unwanted style leakage.  But what about when you intentionally want to *customize* the style of a custom element's local DOM, as the user of an element?  This often comes up under the umbrella of "theming".  For example a "custom-checkbox" element that may interally use a `.checked` class can protect itself from being affected by CSS from other components that may also happen to use a `.checked` class.  However, as the user of the checkbox you may wish to intentionally change the color of the check to match your product's branding, for example.  The "protection" that Shadow DOM provides at the same time introduces a practical barrier to "theming" use cases.

One solution the Shadow DOM spec authors provided to address the theming problem are the `/deep/` and `::shadow` combinators, which allow writing rules that pierce through the Shadow DOM encapsulation boundary.  Although Polymer 0.5 promoted this mechanism for theming, it was ultimately unsatisfying for several reasons:

* Using `/deep/` and `::shadow` for theming leaks details of an otherwise encapsulated element to the user, leading to brittle selectors piercing into the internal details of an element's Shadow DOM that are prone to breakage when the internal implementation changes.  As a result, the structure of of an element's Shadow DOM inadvertently becomes API surface subject to breakage, diminishing the practical effectiveness of Shadow DOM as an encapsulation primitive.
* Although Shadow DOM's style encapsulation *improves* the predictability of style recalc performance since the side effects of a style change are limited to a small subset of the document, using `/deep/` and `::shadow` re-open the style invalidation area and reduce Shadow DOM's effectiveness as a performance primitive.
* Using `/deep/` and `::shadow` lead to verbose and difficult to understand selectors.

For the reasons above, the Polymer team is currently exploring other options for theming that address the shortcomings above and provide a possible path to obsolescence of `/deep/` and `::shadow` altogether.

<a name="xscope-styling-details"></a>
### Custom CSS properties

Polymer includes a shim for custom CSS properties inspired by (and compatible with) the future W3C [CSS Custom Properties for Cascading Variables](http://dev.w3.org/csswg/css-variables/) specification (see [explainer on MDN here](https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables)).

Rather than exposing the details of an element's internal implementation for theming, instead an element author would define one or more custom CSS properties as part of the element's API which it would consume to style internals of the element deemed important for theming by the element's author.  These custom properties can be defined similar to other standard CSS properties and will inherit from the point of definition down the DOM tree (into local DOM), similar to the effect of `color` and `font-family`.  There are some important [limitations](x-styling-limitations) of the shim; see details below.

In the simple example below, the author of `my-toolbar` identified the need for users of the toolbar to be able to change the color of the toolbar title.  The author exposed a custom property called `--my-toolbar-title-color` which is assigned to the `color` property of the selector for the title element.  Users of the toolbar may define this variable in a CSS rule anywhere up the tree, and the value of the property will inherit down to the toolbar where it is used if defined, similar to other standard inheriting CSS properties.

Example:

```html
<dom-module id="my-toolbar">

  <style>
    :host {
      padding: 4px;
      background-color: gray;
    }
    .title {
      color: var(--my-toolbar-title-color);
    }
  </style>

  <template>
    {{title}}
  </template>

  <script>
    Polymer({
      is: 'my-toolbar',
      properties: {
        title: String
      }
    });
  </script>

</dom-module>
```

Example usage of `my-toolbar`:

```html
<dom-module id="my-element">

  <style>

    /* Make all toolbar titles in this host green by default */
    :host {
      --my-toolbar-title-color: green;
    }

    /* Make only toolbars with the .warning class red */
    .warning {
      --my-toolbar-title-color: red;
    }

  </style>

  <template>

    <my-toolbar title="This one is green."></my-toolbar>
    <my-toolbar title="This one is green too."></my-toolbar>

    <my-toolbar class="warning" title="This one is red."></my-toolbar>

  </template>

</dom-module>
```

The `--my-toolbar-title-color` property will only affect the color of the title element encapsulated in `my-toolbar`'s internal implementation.  If in the future the `my-toolbar` author chose to rename the `.title` class or otherwise restructure the internal details of `my-toolbar`, users are shielded from this change via the indirection afforded by custom properties.

Thus, custom CSS properties introduce a powerful way for element authors to expose a theming API to their users in a way that naturally fits right alongside normal CSS styling and avoids the problems with `/deep/` and `::shadow`, and is already on a standards track with shipping implementation by Mozilla and planned support by Chrome.

However, it may be tedious (or impossible) for an element author to anticipate and expose every possible CSS property that may be important for theming an element as individual CSS properties (for example, what if a user needed to adjust the `opacity` of the toolbar title?).  For this reason, the custom properties shim included in Polymer includes an extension allowing a bag of CSS properties to be defined as a custom property and allowing all properties in the bag to be applied to a specific CSS rule in an element's local DOM.  For this, we introduce an `@apply` capability that is analogous to `var`, but allows an entire set of properties to be mixed in to the rule.

Example:

```html
<dom-module id="my-toolbar">

  <style>
    :host {
      padding: 4px;
      background-color: gray;
      @apply(--my-toolbar-theme);
    }
    .title {
      @apply(--my-toolbar-title-theme);
    }
  </style>

  <template>
    {{title}}
  </template>

  ...

</dom-module>
```

Example usage of `my-toolbar`.

```html
<dom-module id="my-element">

  <style>

    /* Apply custom theme to toolbars */
    :host {
      /* the value of a custom property can be a set of properties
         that will inherit down to the point of application */
      --my-toolbar-theme: {
        background-color: green;
        border-radius: 4px;
        border: 1px solid gray;
      };
      --my-toolbar-title-theme: {
        color: green;
      };
    }

    /* Make only toolbars with the .warning class red and bold */
    .warning {
      --my-toolbar-title-theme: {
        color: red;
        font-weight: bold;
      }
    }

  </style>

  <template>

    <my-toolbar title="This one is green."></my-toolbar>
    <my-toolbar title="This one is green too."></my-toolbar>

    <my-toolbar class="warning" title="This one is red."></my-toolbar>

  </template>

</dom-module>
```

### Custom Property API for Polymer Elements

Polymer's custom property shim evaluates and applies custom property values once at element creation time.  In order to have an element (and its subtree) re-evaluate custom property values due to dynamic changes such as application of CSS classes, etc., the user should call `this.updateStyles()` on the element.  To update all elements on the page, you can also call `Polymer.updateStyles()`.

The user can also directly modify a Polymer element's custom property by setting key-value pairs in `customStyle` on the element (analogous to setting `style`) and then calling `updateStyles()`.

Example:

```html
<dom-module id="x-custom">
  <style>
    :host {
      --my-toolbar-color: red;
    }
  </style>

  <template>
    <my-toolbar>My awesome app</my-toolbar>
    <button on-tap="changeTheme">Change theme</button>
  </template>

  <script>
    Polymer({
      is: 'x-custom',
      changeTheme: function() {
        this.customStyle['--my-toolbar-color'] = 'blue';
        this.updateStyles();
      }
    });
  </script>
</dom-module>
```

<a name="x-styling-limitations"></a>
### Custom Properties Shim - Limitations and API details

Cross-platform support for custom properties is provided in Polymer by a Javascript library that approximates the capabilities of the CSS Variables specification  *for the specific use case of theming custom elements*, while also extending it to add the capability to mixin property sets to rules as described above.  **It is important to note that this is not a full polyfill**, as doing so would be prohibitively expensive; rather this is a shim that is inspired by that specification and trades off aspects of the full dynamism possible in CSS with practicality and performance.

Below are current limitations of this system.  Improvements to performance and dynamism will continue to be explored.

* Only rules which match the element at *creation time* are applied. Any dynamic changes that update variable values are not applied automatically.

    ```html

      <x-foo class="a"></x-foo>

    ```

    ```css
    /* applies */
    x-foo.a {
      --foo: brown;
    }
    /* does not apply */
    x-foo.b {
      --foo: orange;
    }
    /* does not apply to x-foo */
    .container {
      --nog: blue;
    }
    ```
* Re-evaluation of custom property styles does not currently occur as a result of changes to the DOM.  Re-evaluation can be forced by calling `this.updateStyles()` on a Polymer element (or `Polymer.updateStyles()` to update all element styles).  For example, if class `b` was added to `x-foo` above, the scope must call `this.updateStyles()` to apply the styling. This re-calcs/applies styles down the tree from this point.

* Dynamic effects are reflected at the point of a variable's application, but not its definition.

    For the following example, adding/removing the `highlighted` class on the `#title` element will have the desired effect, since the dynamism is related to *application* of a custom property.

    ```css
    #title {
      background-color: var(--title-background-normal);
    }

    #title.highlighted {
      background-color: var(--title-background-highlighted);
    }
    ```

    However, the shim does not currently support dynamism at the point of *definition* of a custom property.  In the following example, `this.updateStyles()` would be required to update the value of `--title-background` being applied to `#title` when the `highlighted` class was added or removed.

    ```css
    #title {
      --title-background: gray;
    }

    #title.highlighted {
      --title-background: yellow;
    }
    ```
* Unlike normal CSS inheritance which flows from parent to child, custom properties in Polymer's shim can only change when inherited by a custom element from rules that set properties in scope(s) above it, or in a `:host` rule for that scope.  Within a given element's local DOM scope, a custom property can only have a single value.  Calculating property changes within a scope would be prohibitvely expensive for the shim and are not required to achieve cross-scope styling for custom elements, which is the primary goal of the shim.

   ```html
   <dom-module>
     <style>
       :host {
         --custom-color: red;
       }
       .container {
         /* Setting the custom property here will not change */
         /* the value of the property for other elements in  */
         /* this scope.                                      */
         --custom-color: blue;
       }
       .child {
         /* This will be always be red. */
         color: var(--custom-color);
       }
     </style>

     <template>

I will be red

     </template>
   </dom-module>
   ```

<a name="custom-style"></a>
## Custom element for document styling (custom-style)

The `<style is="custom-style">` custom element is provided for defining styles in the main document that can take advantage of several special features of Polymer's styling system:

* Document styles defined in an `custom-style` will be shimmed to ensure they do not leak into local DOM when running on browsers without non-native Shadow DOM.
* Shadow DOM-specific `/deep/` and `::shadow` combinators will be shimmed on browsers without non-native Shadow DOM.
* Custom properties used by Polymer's [shim for cross-scope styling](#xscope-styling-details) may be defined in an `custom-style`.

Example:

```html
<!doctype html>

  <script src="components/webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="components/polymer/polymer.html">

  <style is="custom-style">

    /* Will be prevented from affecting local DOM of Polymer elements */
    * {
      box-sizing: border-box;
    }

    /* Can use /deep/ and ::shadow combinators */
    body /deep/ .my-special-view::shadow #thing-inside {
      background: yellow;
    }

    /* Custom properties that inherit down the document tree may be defined */
    * {
      --my-toolbar-title-color: green;
    }

  </style>

    ...

```

Note, all features of `custom-style` are available when defining styles as part of Polymer elements (e.g. `<style>` elements within `<dom-module>`'s used for defining Polymer elements. The `custom-style` extension should only be used for defining document styles, outside of a custom element's local DOM.

<a name="external-stylesheets"></a>
## External stylesheets

Polymer leverages HTML Imports to support loading external stylesheets that will be applied to the local DOM of an element.  This is typically convenient for developers who like to separate styles, share common styles between elements, or use style pre-processing tools.  The syntax is slightly different from how stylesheets are typically loaded, as the feature leverages HTML Imports (or the HTML Imports polyfill, where appropriate) to load the stylesheet text such that it may be properly shimmed and/or injected as an inline style.

To include a remote stylesheet that applies to your Polymer element's local DOM, place a special HTML import `<link>` tag with `type="css"` in your `<dom-module>` that refers to the external stylesheet to load.

Example:

```html
<dom-module id="my-awesome-button">

  <link rel="import" type="css" href="my-awesome-button.css">

  <template>
    ...
  </template>

  <script>
    Polymer({
      is: 'my-awesome-button',
      ...
    });
  </script>

</dom-module>
```

<a name="utility-functions"></a>
## Utility Functions

Polymer's Base prototype provides a set of useful convenience/utility functions for instances to use.  See API documentation for more details.

* toggleClass: function(name, bool, [node])
* toggleAttribute: function(name, bool, [node])
* attributeFollows: function(name, neo, old)
* fire: function(type, [detail], [onNode], [bubbles], [cancelable])
* async: function(method)
* transform: function(node, transform)
* translate3d: function(node, x, y, z)
* importHref: function(href, onload, onerror)

<a name="settings"></a>
## Global Polymer settings

Document-level global Polymer settings can be set before loading by setting a `Polymer` object on window as the first script in the main document:

```html

  <meta charset="utf-8">
  <script> Polymer = { dom: 'shadow' }; </script>
  <script src="../../../webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="components/my-app.html">

  ...

```

Settings can also be switched on the URL query string:

```
http://myserver.com/test-app/index.html?dom=shadow
```

Available settings:

* `dom` - options:
    * `shady` - all local DOM will be rendered using Shady DOM (even where shadow-DOM supported (current default)
    * `shadow` - local DOM will be rendered using Shadow DOM where supported (this will be made default soon)

<a name="polymer-elements"></a>
# Helper Custom Elements

The following useful helper custom elements are shipped with Polymer.

<a name="dom-repeat"></a>
## Template repeater (dom-repeat)

Elements in a template can be automatically repeated and bound to array items using a custom `HTMLTemplateElement` type extension called `dom-repeat`.  `dom-repeat` accepts an `items` property, and one instance of the template is stamped for each item into the DOM at the location of the `dom-repeat` element.  The `item` property will be set on each instance's binding scope, thus templates should bind to sub-properties of `item`.  Example:

```html
<dom-module id="employee-list">

  <template>

 Employee list:

    <template is="dom-repeat" items="{{employees}}">

First name: {{item.first}}

Last name: {{item.last}}

    </template>

  </template>

  <script>
    Polymer({
      is: 'employee-list',
      ready: function() {
        this.employees = [
            {first: 'Bob', last: 'Smith'},
            {first: 'Sally', last: 'Johnson'},
            ...
        ];
      }
    });
  </script>

</dom-module>
```

Notifications for changes to items sub-properties will be forwarded to template instances, which will update via the normal [structured data notification system](#path-binding).

Mutations to the `items` array itself (`push`, `pop`, `splice`, `shift`, `unshift`) must be performed using methods provided on Polymer elements, such that the changes are observable to any elements bound to the same array in the tree.  See

A view-specific filter/sort may be applied to each `dom-repeat` by supplying a `filter` and/or `sort` property.  This may be a string that names a function on the host, or a function may be assigned to the property directly.  The functions should implemented following the standard `Array` filter/sort API.

In order to re-run the filter or sort functions based on changes to sub-fields of `items`, the `observe` property may be set as a space-separated list of `item` sub-fields that should cause a re-filter/sort when modified.

For example, for an `dom-repeat` with a filter of the following:

```js
isEngineer: function(item) {
    return item.type == 'engineer' || item.manager.type == 'engineer';
}
```

Then the `observe` property should be configured as follows:

```html
<template is="dom-repeat" items="{{employees}}"
          filter="isEngineer" observe="type manager.type">
```

<a name="array-selector"></a>
## Array selector (array-selector)

Keeping structured data in sync requires that Polymer understand the path associations of data being bound.  The `array-selector` element ensures path linkage when selecting specific items from an array (either single or multiple).  The `items` property accepts an array of user data, and via the `select(item)` and `deselect(item)` API, updates the `selected` property which may be bound to other parts of the application, and any changes to sub-fields of `selected` item(s) will be kept in sync with items in the `items` array.  When `multi` is false, `selected` is a property representing the last selected item.  When `multi` is true, `selected` is an array of multiply selected items.

```html
<dom-module id="employee-list">

  <template>

 Employee list:

    <template is="dom-repeat" id="employeeList" items="{{employees}}">

First name: {{item.first}}

Last name: {{item.last}}

        <button on-click="toggleSelection">Select</button>
    </template>

    <array-selector id="selector" items="{{employees}}" selected="{{selected}}" multi toggle></array-selector>

 Selected employees:

    <template is="dom-repeat" items="{{selected}}">

First name: {{item.first}}

Last name: {{item.last}}

    </template>

  </template>

  <script>
    Polymer({
      is: 'employee-list',
      ready: function() {
        this.employees = [
            {first: 'Bob', last: 'Smith'},
            {first: 'Sally', last: 'Johnson'},
            ...
        ];
      },
      toggleSelection: function(e) {
        var item = this.$.employeeList.itemForElement(e.target);
        this.$.selector.select(item);
      }
    });
  </script>

</dom-module>
```

<a name="dom-if"></a>
## Conditional template

Elements can be conditionally stamped based on a boolean property by wrapping them in a custom `HTMLTemplateElement` type extension called `dom-if`.  The `dom-if` template stamps itself into the DOM only when its `if` property becomes truthy.

If the `if` property becomes falsy again, by default all stamped elements will be hidden (but will remain in DOM) for faster performance should the `if` property become truthy again.  This behavior may be disabled by setting the `restamp` property, which results in slower `if` switching behavior as the elements are destroyed and re-stamped each time.

Example:

**Note, this is a simple example for illustrative purposes only.  Read below for guidance on recommended usage of conditional templates.**

```html
<dom-module id="user-page">

  <template>

    All users will see this:

{{user.name}}

    <template is="dom-if" if="{{user.isAdmin}}">
      Only admins will see this.

{{user.secretAdminStuff}}

    </template>

  </template>

  <script>
    Polymer({
      is: 'user-page',
      properties: {
        user: Object
      }
    });
  </script>

</dom-module>
```

Note, since it is generally much faster to hide/show elements rather than create/destroy them, conditional templates are only useful to save initial creation cost when the elements being stamped are relatively heavyweight and the conditional may rarely (or never) be true in given useages.  Otherwise, liberal use of conditional templates can actually *add* significant runtime performance overhead.

Consider an app with 4 screens, plus an optional admin screen.  If most users will use all 4 screens during normal use of the app, it is generally better to incur the cost of stamping those elements once at startup (where some app initialization time is expected) and simply hide/show the screens as the user navigates through the app, rather than re-create and destroy all the elements of each screen as the user navigates.  Using a conditional template here may be a poor choice, since although it may save time at startup by stamping only the first screen, that saved time gets shifted to runtime latency for each user interaction, since the time to show the second screen will be *slower* as it must create the second screen from scratch rather than simply showing that screen.  Hiding/showing elements is as simple as attribute-binding to the `hidden` attribute (e.g. `<div hidden$="{{!shouldShow}}">`), and does not require conditional templating at all.

However, using a conditional template may be appropriate in the case of an admin screen that should only be shown to admin users of an app.  Since most users would not be admins, there may be performance benefits to not burdening most of the users with the cost of stamping the elements for the admin page, especially if it is relatively heavyweight.

<a name="dom-bind"></a>
## Self-binding template

Polymer's binding features are only available within templates that are managed by Polymer.  As such, these features are available in templates used to define Polymer elements, for example, but not for elements placed directly in the main document.

In order to use Polymer bindings without defining a new custom element, you may wrap the elements utilizing bindings with a custom template extension called `dom-bind`.  This template will immediately stamp itself into the main document and bind elements to the template itself as the binding scope.

```html
<!doctype html>

  <meta charset="utf-8">
  <script src="components/webcomponentsjs/webcomponents-lite.js"></script>
  <link rel="import" href="components/polymer/polymer.html">
  <link rel="import" href="components/core-ajax/core-ajax.html">

  <template is="dom-bind">

    <core-ajax url="http://..." lastresponse="{{data}}"></core-ajax>

    <template is="dom-repeat" items="{{data}}">

{{item.first}} {{item.last}}

    </template>

  </template>

```

## Feature layering

Polymer is currently layered into 3 sets of features provided as 3 discrete HTML imports, such that an individual element developer can depend on a version of Polymer whose feature set matches their tastes/needs.  For authors who opt out of the more opinionated local DOM or data-binding features, their element's dependencies would not be payload- or runtime-burdened by these higher-level features, to the extent that a user didn't depend on other elements using those features on that page.  That said, all features are designed to have low runtime cost when unused by a given element.

Higher layers depend on lower layers, and elements requiring lower layers will actually be imbued with features of the highest-level version of Polymer used on the page (those elements would simply not use/take advantage of those features).  This provides a good tradeoff between element authors being able to avoid direct dependencies on unused features when their element is used standalone, while also allowing end users to mix-and-match elements created with different layers on the same page.

* polymer-micro.html: [Polymer micro features](#polymer-micro) (bare-minum Custom Element sugaring)
* polymer-mini.html: [Polymer mini features](#polymer-mini) (template stamped into "local DOM" and tree lifecycle)
* polymer.html: [Polymer standard features](#polymer-standard) (all other features: declarative data binding and event handlers, property nofication, computed properties, and the set of helper custom elements provided with Polymer)

This layering is subject to change in the future and the number of layers may be reduced.


text:
package com.adamtaft.eb;

/**
 * An EventBus is a simple pattern to promote loose coupling between various
 * components.  An event bus can be used in place of a traditional listener
 * or observer pattern, and is useful when ties between multiple components
 * become too complicated to track.
 *

 * A traditional use case for an event bus is a Swing based application, where
 * multiple actions and listeners are configured to capture the various events
 * of the application, such as mouse clicks, window events, data loading events,
 * etc.  Swing promotes a one-to-one mapping between listener/listenee components,
 * and as such, it can become difficult to configure the various listeners
 * without tightly coupling all the various componenets together.
 *

 * With an event bus, events can be published to the bus and any class can be
 * configured to listen for such events.  Thus, each individual component only
 * needs to be tightly coupled with the event bus, and it can then receive
 * notifications about events that it cares to know about.
 *

 * The event bus pattern has a simple interface, with a subscribe/publish type
 * model.  Any object can be subscribed to the event bus, but to received messages
 * from the bus, the object must have its methods annotated with the {@link EventHandler}
 * annotation.  This annotation marks the methods of the subscriber class which
 * should be used to receive event bus events.
 *

 * A published event has the potential to be vetoed and thus not propagated to
 * other non-vetoing subscribers.  This is accomplished by setting the
 * {@link EventHandler#canVeto()} property to true and throwing a {@link VetoException}
 * when the method is called from the EventBus.  The event bus will note the
 * veto and not relay the message to the subscribers, but will instead send a
 * {@link VetoEvent} out on the bus indicating that the published event has been
 * vetoed.
 *
 * @author Adam Taft
 */
public interface EventBus {

	/**
	 * Subscribes the specified subscriber to the event bus.  A subscribed object
	 * will be notified of any published events on the methods annotated with the
	 * {@link EventHandler} annotation.
	 *

	 * Each event handler method should take a single parameter indicating the
	 * type of event it wishes to receive.  When events are published on the
	 * bus, only subscribers who have an EventHandler method with a matching
	 * parameter of the same type as the published event will receive the
	 * event notification from the bus.
	 *
	 * @param subscriber The object to subscribe to the event bus.
	 */
	void subscribe(Object subscriber);

	/**
	 * Removes the specified object from the event bus subscription list.  Once
	 * removed, the specified object will no longer receive events posted to the
	 * event bus.
	 *
	 * @param subscriber The object previous subscribed to the event bus.
	 */
	void unsubscribe(Object subscriber);

	/**
	 * Sends a message on the bus which will be propagated to the appropriate
	 * subscribers of the event type.  Only subscribers which have elected to
	 * subscribe to the same event type as the supplied event will be notified
	 * of the event.
	 *

	 * Events can be vetoed, indicating that the event should not propagate to
	 * the subscribers that don't have a veto.  The subscriber can veto by
	 * setting the {@link EventHandler#canVeto()} return to true and by throwing
	 * a {@link VetoException}.
	 *

	 * There is no specification given as to how the messages will be delivered,
	 * in terms of synchronous or asynchronous.  The only requirement is that
	 * all the event handlers that can issue vetos be called before non-vetoing
	 * handlers.  Most implementations will likely deliver messages asynchronously.
	 *
	 * @param event The event to send out to the subscribers of the same type.
	 */
	void publish(Object event);

	/**
	 * Indicates whether the bus has pending events to publish.  Since message/event
	 * delivery can be asynchronous (on other threads), the method can be used to
	 * start or stop certain actions based on all the events having been published.
	 * I.e. perhaps before an application closes, etc.
	 *
	 * @return True if events are still being delivered.
	 */
	boolean hasPendingEvents();

}

redpajama_set_name: RedPajamaGithub


text:
    <title>Data Kategori Kegiatan</title>

Data Kategori Kegiatan

 Home

Tambah data Kegiatan

                <form role="form" th:object="${kategoriKegiatan}" method="post">

                            Nama
                            <input type="text"
                                   th:field="*{nama}"
                                   name="nama" class="form-control" id="nama" placeholder="Nama" />

                                Pesan error nanti di sini

                            Keterangan
                            <input type="text"
                                   th:field="*{keterangan}"
                                   name="keterangan" class="form-control" id="keterangan" placeholder="Keterangan" />

                                Pesan error nanti di sini

                                Batal

                            <button type="submit" class="btn btn-default">Simpan</button>

                </form>


text:
  'use strict';

  var Resource = [ '$resource', 'Uri', function ($resource, Uri) {

    return $resource(Uri.appUri('engine://engine/:engine/process-definition/:id/:action'), {
      id: '@id'
    }, {
      queryStatistics: {
        method: 'GET', isArray: true, params: {
          id: 'statistics'
        }
      },
      queryActivityStatistics: {
        method: 'GET', isArray: true, params: {
          action: 'statistics'
        }
      },
      getBpmn20Xml: {
        method: 'GET', params: { action: 'xml' }, cache: true }
    });
  }];

  module.exports = Resource;


text:
namespace dart {
namespace bin {

// This function extracts OSVersion from SystemVersion.plist.
// The format of input should be:
//   <key>ProductVersion</key>
//   <string>10.15.4</string>
// Returns the string representation of OSVersion. For example, "10.15.4" will
// be returned in the previous example.
char* ExtractsOSVersionFromString(char* str);

}  // namespace bin
}  // namespace dart

#endif  // RUNTIME_BIN_PLATFORM_MACOS_H_


text:
require 'spec_helper'

[Slack::RealTime::Stores::Store, Slack::RealTime::Stores::Starter].each do |store_class|
  cassette = store_class == Slack::RealTime::Stores::Store ? 'web/rtm_start' : 'web/rtm_connect'
  RSpec.describe store_class, vcr: { cassette_name: cassette } do
    include_context 'connected client', store_class: store_class

    context 'team' do
      it 'sets team data on rtm.start' do
        expect(client.team.name).to eq 'dblock'
        expect(client.team.domain).to eq 'dblockdotorg'
        if store_class == Slack::RealTime::Stores::Store
          expect(client.team.email_domain).to eq 'dblock.org'
          expect(client.team.prefs.invites_only_admins).to be true
          expect(client.team.plan).to eq ''
        end
      end
      it 'team_domain_change' do
        event = Slack::RealTime::Event.new(
          'type' => 'team_domain_change',
          'url' => 'https://my.slack.com',
          'domain' => 'my'
        )
        client.send(:dispatch, event)
        expect(client.team.domain).to eq 'my'
        expect(client.team['url']).to eq 'https://my.slack.com'
      end
      it 'email_domain_changed' do
        event = Slack::RealTime::Event.new(
          'type' => 'email_domain_changed',
          'email_domain' => 'example.com'
        )
        client.send(:dispatch, event)
        expect(client.team.email_domain).to eq 'example.com'
      end
      it 'team_pref_change' do
        event = Slack::RealTime::Event.new(
          'type' => 'team_pref_change',
          'name' => 'invites_only_admins',
          'value' => false
        )
        client.send(:dispatch, event)
        expect(client.team.prefs.invites_only_admins).to be false
      end
      it 'team_rename' do
        event = Slack::RealTime::Event.new(
          'type' => 'team_rename',
          'name' => 'New Team Name Inc.'
        )
        client.send(:dispatch, event)
        expect(client.team.name).to eq 'New Team Name Inc.'
      end
      it 'team_plan_change' do
        event = Slack::RealTime::Event.new(
          'type' => 'team_plan_change',
          'plan' => 'std'
        )
        client.send(:dispatch, event)
        expect(client.team.plan).to eq 'std'
      end
    end
  end
end


text:
======================
 Interact with errors
======================

There are a couple of things that you can do with Flycheck errors in a buffer:

* You can navigate to errors, and go to the next or previous error.
* You can display errors to read their error messages.
* You can put error messages and IDs into the kill ring.

This section documents the corresponding commands and their customisation
options.

Navigate errors
===============

By default Flycheck hooks into Emacs' standard error navigation on :kbd:`M-g n`
(`next-error`) and :kbd:`M-g p` (`previous-error`).  When :mode:`flycheck` is
enabled these commands will jump to the next and previous Flycheck error
respectively.  See :infonode:`(emacs)Compilation Mode` for more information
about these commands.

This way you don't need to learn special keybindings to navigate Flycheck
errors; navigation should just work out of the box.

.. note::

   Visible compilation buffers such as buffers from ``M-x compile``, ``M-x
   grep``, etc. still take *precedence* over Flycheck's errors.

The exact behaviour of these error navigation features is very context-dependent
and can be very confusing at times so you can disable this integration:

.. defcustom:: flycheck-standard-error-navigation

   Whether to integrate Flycheck errors into Emacs' standard error navigation.
   Defaults to ``t``, set to ``nil`` to disable.

   .. important::

      When changing the value you must disable :mode:`flycheck` and enable it
      again for the change to take effect in any buffers where :mode:`flycheck`
      is enabled.

Flycheck provides an independent set of navigation commands which will always
navigate Flycheck errors in the current buffer, regardless of visible
compilation buffers and `flycheck-standard-error-navigation`:

.. define-key:: C-c ! n
                M-x flycheck-next-error

   Jump to the next error.

   With prefix argument jump forwards by as many errors as specified by the
   prefix argument, e.g. :kbd:`M-3 C-c ! n` will move to the 3rd error from the
   current point.  With negative prefix argument move to previous errors
   instead.  Signal an error if there are no more Flycheck errors.

.. define-key:: C-c ! p
                M-x flycheck-previous-error

   Jump to the previous Flycheck error.

   With prefix argument jump backwards by as many errors as specified by the
   prefix argument, e.g. :kbd:`M-3 C-c ! p` will move to the 3rd error before
   the current point.  With negative prefix argument move to next errors
   instead.  Signal an error if there are no more Flycheck errors.

.. define-key:: M-x flycheck-first-error

   Jump to the first Flycheck error.

   With prefix argument, jump forwards to by as many errors as specified by the
   prefix argument, e.g. :kbd:`M-3 M-x flycheck-first-error` moves to the 3rd
   error from the beginning of the buffer.  With negative prefix argument move
   to the last error instead.

By default error navigation jumps to all errors but you can choose to skip over
errors with low levels:

.. defcustom:: flycheck-navigation-minimum-level

   The minimum levels of errors to consider for navigation.

   If set to an error level only navigate to errors whose level is as least as
   severe as this one. If ``nil`` navigate to all errors.

Display errors
==============

Whenever you move point to an error location Flycheck automatically displays all
Flycheck errors at point after a short delay which you can customise:

.. defcustom:: flycheck-display-errors-delay

   The number of seconds to wait before displaying the error at point. Floating
   point numbers can express fractions of seconds.

By default Flycheck shows the error messages in the minibuffer or in a separate
buffer if the minibuffer is too small to hold the whole error message but this
behaviour is entirely customisable:

.. defcustom:: flycheck-display-errors-function

   A function to display errors.

   The function is given the list of Flycheck errors to display as sole argument
   and shall display these errors to the user in some way.

Flycheck provides two built-in functions for this option:

.. defun:: flycheck-display-error-messages errors
           flycheck-display-error-messages-unless-error-list errors

   Show error messages and IDs in the echo area or in a separate buffer if the
   echo area is too small (using `display-message-or-buffer` which see).  The
   latter only displays errors when the :ref:`error list <flycheck-error-list>`
   is not visible.  To enable it add the following to your :term:`init file`:

   .. code-block:: elisp

      (setq flycheck-display-errors-function
            #'flycheck-display-error-messages-unless-error-list)

.. seealso::

   :flyc:`flycheck-pos-tip`
      A Flycheck extension to display errors in a GUI popup.

Additionally Flycheck shows errors in a GUI tooltip whenever you hover an error
location with the mouse pointer.  By default the tooltip contains the messages
and IDs of all errors under the pointer, but the contents are customisable:

.. defcustom:: flycheck-help-echo-function

   A function to create the contents of the tooltip.

   The function is given a list of Flycheck errors to display as sole argument
   and shall return a single string to use as the contents of the tooltip.

Explain errors
==============

Flycheck also has the ability to display explanations for errors, provided the
error checker is capable of producing these explanations.  Currently, only the
`rust` and `rust-cargo` checkers produce explanations.

.. define-key:: C-c ! e
                M-x flycheck-explain-error-at-point

   Display an explanation for the first explainable error at point.

Kill errors
===========

You can put errors into the kill ring with `C-c ! w`:

.. define-key:: C-c ! w
                M-x flycheck-copy-errors-as-kill

   Copy all messages of the errors at point into the kill ring.

.. define-key:: C-u C-c ! w
                C-u M-x flycheck-copy-errors-as-kill

   Like `C-c ! w` but with error IDs.

.. define-key:: M-0 C-c ! w
                M-0 M-x flycheck-copy-errors-as-kill

   Like `C-c ! w` but do not copy the error messages but only the error IDs.


text:
import { OptionsService } from '../services/options.service';
import { TreeOption } from '../shared/models/tree-option';
import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'rcos-workspace',
  templateUrl: './workspace.component.html',
  styleUrls: ['./workspace.component.css']
})
export class WorkspaceComponent implements OnInit {

  constructor(private optionsservice: OptionsService) { }

  @Input() useroptions: TreeOption[];

  ngOnInit() {
    this.useroptions = this.optionsservice.getOptions();
  }

}


text:
import csv
from pyExcelerator import *

def read_csv(filename):
    with open(filename+".csv") as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            process_row(row)

def process_row(row):
    print(row)
    name_parts = row['Teacher'].split(' ', 1)
    name_form = name_parts[0].replace('.', '')
    name = name_parts[1]
    room = row['Room']
    grade = row['Grade']
    sheet_name = name_form + '_' + name + '_' + grade + '_' + room
    filename = "teachers/" + sheet_name + ".xls"
    print(filename)
    workbook = Workbook()
    worksheet = workbook.add_sheet(sheet_name)
    worksheet.write(0, 0, 'First Name')
    worksheet.write(0, 1, 'Last Name')
    worksheet.write(0, 2, 'Project Type')
    worksheet.write(0, 3, 'Project Title')
    worksheet.write(0, 4, 'Project Description')
    worksheet.write(0,10, '('+sheet_name+')')
    workbook.save(filename)

read_csv("teachers")


text:
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using GoogleCloudExtension.CopyablePrompt;
using GoogleCloudExtension.GCloud;
using GoogleCloudExtension.LinkPrompt;
using GoogleCloudExtension.Services;
using System;
using System.Threading.Tasks;

namespace GoogleCloudExtension.Utils
{
    internal static class GCloudWrapperUtils
    {
        /// <summary>
        /// Override to use for testing.
        /// </summary>
        internal static Action<string, string, string> ShowCopyablePromptOverride { private get; set; }

        private static Action<string, string, string> ShowCopyablePrompt =>
            ShowCopyablePromptOverride ?? CopyablePromptDialogWindow.PromptUser;

        private static IGCloudWrapper GCloudWrapper =>
            GoogleCloudExtensionPackage.Instance.GetMefService<IGCloudWrapper>();

        /// <summary>
        /// Verify that the Cloud SDK is installed and at the right version. Optionally also verify that the given
        /// component is installed.
        /// </summary>
        /// <param name="component">The component to check, optional.</param>
        /// <returns>True if the Cloud SDK installation is valid.</returns>
        public static async Task<bool> VerifyGCloudDependenciesAsync(GCloudComponent component = GCloudComponent.None)
        {
            GCloudValidationResult result = await GCloudWrapper.ValidateGCloudAsync(component);
            if (result.IsValid)
            {
                return true;
            }

            if (!result.IsCloudSdkInstalled)
            {
                LinkPromptDialogWindow.PromptUser(
                        Resources.GcloudMissingGcloudErrorTitle,
                        Resources.GcloudMissingCloudSdkErrorMessage,
                        new LinkInfo(link: "https://cloud.google.com/sdk/", caption: Resources.GcloudInstallLinkCaption));
            }
            else if (result.IsObsolete)
            {
                UserPromptService.Default.ErrorPrompt(
                    message: string.Format(
                        Resources.GCloudWrapperUtilsOldCloudSdkMessage,
                        result.CloudSdkVersion,
                        GCloud.GCloudWrapper.GCloudSdkMinimumVersion),
                    title: Resources.GCloudWrapperUtilsOldCloudSdkTitle);
            }
            else
            {
                ShowCopyablePrompt(
                    Resources.GcloudMissingComponentTitle,
                    string.Format(Resources.GcloudMissingComponentErrorMessage, component),
                    string.Format(Resources.GcloudMissingComponentInstallCommand, component.ToString().ToLower()));
            }

            return false;
        }
    }
}


text:
using Newtonsoft.Json;

namespace Acklann.Plaid.Management
{
    /// <summary>
    /// Represents a response from plaid's drop-in authentication module.
    /// </summary>
    public class PlaidLinkResponse
    {
        /// <summary>
        /// Gets or sets the public_token.
        /// </summary>
        /// <value>The public token.</value>
        [JsonProperty("public_token")]
        public string PublicToken { get; set; }

        /// <summary>
        /// Gets or sets the link session identifier.
        /// </summary>
        /// <value>The link session identifier.</value>
        [JsonProperty("link_session_id")]
        public string LinkSessionId { get; set; }

        /// <summary>
        /// Gets or sets the accounts info.
        /// </summary>
        /// <value>The accounts.</value>
        [JsonProperty("accounts")]
        public AccountInfo[] Accounts { get; set; }

        /// <summary>
        /// Gets or sets the institution.
        /// </summary>
        /// <value>The institution.</value>
        [JsonProperty("institution")]
        public InstitutionInfo Institution { get; set; }

        /// <summary>
        /// Represents an <see cref="Entity.Account"/> metadata.
        /// </summary>
        public struct AccountInfo
        {
            /// <summary>
            /// Gets or sets the <see cref="Entity.Account"/> identifier.
            /// </summary>
            /// <value>The identifier.</value>
            [JsonProperty("id")]
            public string Id { get; set; }

            /// <summary>
            /// Gets or sets the <see cref="Entity.Account"/> name.
            /// </summary>
            /// <value>The name.</value>
            [JsonProperty("name")]
            public string Name { get; set; }
        }

        /// <summary>
        /// Represents an <see cref="Entity.Institution"/> metadata.
        /// </summary>
        public struct InstitutionInfo
        {
            /// <summary>
            /// Gets or sets the <see cref="Entity.Institution"/> identifier.
            /// </summary>
            /// <value>The identifier.</value>
            [JsonProperty("institution_id")]
            public string Id { get; set; }

            /// <summary>
            /// Gets or sets the <see cref="Entity.Institution"/> name.
            /// </summary>
            /// <value>The name.</value>
            [JsonProperty("name")]
            public string Name { get; set; }
        }
    }
}


text:
/*
import * as React from 'react'
import {Box} from '../../../../../../common-adapters/index'
import * as Sb from '../../../../../../stories/storybook'
import UnfurlPromptList from '.'

const common = {
  onAccept: Sb.action('onAccept'),
  onAlways: Sb.action('onAlways'),
  onNever: Sb.action('onNever'),
  onNotnow: Sb.action('onNotnow'),
  onOnetime: Sb.action('onOnetime'),
}

const props = {prompts: ['cnn.com', 'github.com', 'wsj.com'].map(domain => ({domain, ...common}))}

const load = () => {
  Sb.storiesOf('Chat/Unfurl/Prompt-List', module)
    .addDecorator(story => <Box style={{maxWidth: 600}}>{story()}</Box>)
    .add('Default', () => <UnfurlPromptList {...props} />)
}

export default load
*/

export default {}


text:
package rreeggkk.nuclearsciences.common.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apfloat.Apfloat;
import org.apfloat.ApfloatMath;

import rreeggkk.nuclearsciences.common.Constants;
import rreeggkk.nuclearsciences.common.nuclear.element.AIsotope;

public class NuclearMaterialUtil {
	public static void calculateOutputs(Map<AIsotope<?,?>, Apfloat> feed, Apfloat feedMass, Apfloat totalFeedMass, Map<AIsotope<?,?>, Apfloat> product, Map<AIsotope<?,?>, Apfloat> tails, AIsotope<?,?> iso, double productAssay, double tailsAssay, Apfloat productMass, Apfloat tailsMass) {

		//Apfloat totalMass = productMass.add(tailsMass);

		Apfloat isoProd = productMass.multiply(new Apfloat(productAssay, Constants.PRECISION));
		Apfloat isoTail = tailsMass.multiply(new Apfloat(tailsAssay, Constants.PRECISION));

		for (Entry<AIsotope<?,?>, Apfloat> e : feed.entrySet()) {
			if (e.getKey() == iso) {
				product.put(e.getKey(), isoProd);
				tails.put(e.getKey(), isoTail);
				e.setValue(e.getValue().subtract(isoTail).subtract(isoProd).precision(Constants.PRECISION));
			} else {
				product.put(e.getKey(), e.getValue().divide(totalFeedMass).multiply(productMass.multiply(new Apfloat(1).subtract(new Apfloat(productAssay, Constants.PRECISION)))));
				tails.put(e.getKey(), e.getValue().divide(totalFeedMass).multiply(tailsMass.multiply(new Apfloat(1).subtract(new Apfloat(tailsAssay, Constants.PRECISION)))));
				e.setValue(e.getValue().subtract(product.get(e.getKey())).subtract(tails.get(e.getKey())).precision(Constants.PRECISION));
			}
		}
	}

	public static HashMap<String, Apfloat> sumMaps(Map<String, Apfloat> map1, Map<String, Apfloat> map2) {
		HashMap<String, Apfloat> newMap = new HashMap<String, Apfloat>();

		newMap.putAll(map1);

		for (Entry<String, Apfloat> e : map2.entrySet()) {
			newMap.put(e.getKey(), e.getValue().add(newMap.getOrDefault(e.getKey(), new Apfloat(0))).precision(Constants.PRECISION));
		}

		return newMap;
	}

	public static HashMap<AIsotope<?,?>, Apfloat> sumMassMaps(Map<AIsotope<?,?>, Apfloat> map1, Map<AIsotope<?,?>, Apfloat> map2) {
		HashMap<AIsotope<?,?>, Apfloat> newMap = new HashMap<AIsotope<?,?>, Apfloat>();

		newMap.putAll(map1);

		for (Entry<AIsotope<?,?>, Apfloat> e : map2.entrySet()) {
			newMap.put(e.getKey(), e.getValue().add(newMap.getOrDefault(e.getKey(), new Apfloat(0))).precision(Constants.PRECISION));
		}

		return newMap;
	}

	public static <T> boolean areCloseEnough(Map<T, Apfloat> map1, Map<T, Apfloat> map2) {
		return areCloseEnough(map1, map2, new Apfloat("1E-112", Constants.PRECISION));
	}

	public static <T> boolean areCloseEnough(Map<T, Apfloat> map1, Map<T, Apfloat> map2, Apfloat epsilon) {
		HashMap<T, Apfloat> newMap = new HashMap<T, Apfloat>();

		newMap.putAll(map1);

		for (Entry<T, Apfloat> e : map2.entrySet()) {
			if (!newMap.containsKey(e.getKey())) {
				return false;
			}
			newMap.put(e.getKey(), ApfloatMath.abs(e.getValue().subtract(newMap.getOrDefault(e.getKey(), new Apfloat(0))).precision(Constants.PRECISION)));
		}

		return newMap.values().stream().allMatch((v)->v.compareTo(epsilon)<=0);
	}

	public static double getCaptureCrossSection(AIsotope<?,?> iso, int energy) {
		double fast = Math.min(iso.getThermalCapture()/36, 0.08);
		double k = (Math.sqrt(iso.getThermalCapture()/fast) - 1)/energy;

		return iso.getThermalCapture()/((k*energy + 1)*(k*energy + 1));
	}

	public static double getFissionCrossSection(AIsotope<?,?> iso, int energy) {
		return Math.pow(iso.getThermalFission(), 1/(2*energy));
	}
}


text:
module ArticlesHelper
  def cache_key_for_articles
    count = Article.count
    max_updated_at = Article.maximum(:updated_at).try(:utc).try(:to_s, :number)
    "articles/all-#{count}-#{max_updated_at}"
  end
end


text:
import path from 'path'
import {fileURLToPath} from 'url'
import NodePolyfillPlugin from 'node-polyfill-webpack-plugin'
import glob from 'glob'

const __dirname = path.dirname(fileURLToPath(import.meta.url))

const testEntries = glob.sync("./src/**/test__*.coffee").reduce((acc, val) => {
			const filenameRegex = /test__([\w\d_-]*)\.coffee$/i
			acc[val.match(filenameRegex)[1]] = val
			return acc
		}, {})

export default {
	entry: testEntries,
	mode: 'development',

	// Best practice:
	// - Använd 'inline-cheap-module-source-map' som ger rätt radnr i coffee filer och om det kastas ett fel,
	//	 läs i stack trace och försök hitta .coffee filen och radnummret i din kod som är intressant
	//
	// - Om du inte lyckas lista ut vilken rad i .coffee som orsakar felet, byt temporärt till
	//   'cheap-module-source-map' åtgärda felet och byt sen tillbaks
	//
	devtool: 'inline-cheap-module-source-map',
	// devtool: 'cheap-module-source-map',

	// Alla testade för referes och för att kunna kopiera in och snabbt byta till för att testa
	// se sumb.coffee och sumb.test.coffee i git-historik
	// devtool: 'eval', // a.err rad 9 js eval
	// devtool: 'eval-cheap-source-map', // a.err rad 9 js eval
	// devtool: 'eval-cheap-module-source-map', // a.err rad 9 js eval - snabbare än ovan
	// devtool: 'eval-source-map', // a.err rad 9 js eval -
	// devtool: 'cheap-source-map', // a.err rad 7 .js + .js.map + .js.map + Skriver ut rad för error i js! <---- Bra
	// devtool: 'cheap-module-source-map', // a.err rad 7 .js + .js.map + Skriver ut rad för error i js! <---- Bra
	// devtool: 'source-map', // a.err rad 7 .js + .js.map  + Skriver ut rad för error i js! <---- Bra
	// devtool: 'source-map', // (production), 3.err rad 6 .js + .js.map
	// devtool: 'inline-cheap-module-source-map', // a.err rad 6 .js + klarar if <---- Rätt rad men dålig error
	// devtool: 'inline-source-map', // a.err rad 6 .js
	// devtool: 'eval-nosources-cheap-source-map', // a.err rad 9
	// devtool: 'eval-nosources-cheap-module-source-map', // a.err rad 9
	// devtool: 'eval-nosources-source-map', // a.err rad 9
	// devtool: 'inline-nosources-cheap-source-map', // a.arr rad 7
	// devtool: 'inline-nosources-cheap-module-source-map', // a.arr rad 6 .js + klarar if <---- Rätt rad men dålig error
	// orkar inte testa fler

	output: {
		filename: '[name].test.js',
		path: path.resolve(__dirname, 'temp'),
		clean: true,
	},
	plugins: [
		new NodePolyfillPlugin()
	],
	watch: true,
	module: {
		rules: [
			{
				include: [
					path.resolve(__dirname),
					path.resolve(__dirname, '../comon'),
				],
				exclude: /node_modules|packages/,
				test: /\.coffee$/,
				use: [
					{loader: 'coffee-loader'},
					{loader: path.resolve(__dirname, '../hack/loaders/keywordCoffeeLoader.js')},
				]
			},
		],
	},
	target: 'node',
	resolve: {
		extensions: ['.js', '.coffee'],
		alias: {
			comon: path.resolve(__dirname, '../comon')
		}
	},
}


text:
FROM ruby:2.5.3-alpine
LABEL maintainer="dev+sharemeow@producthunt.com"

RUN apk add --no-cache \
      dbus \
      fontconfig \
      gcc \
      git \
      libc-dev \
      make \
      ttf-freefont \
      xvfb \
    && apk add --no-cache -X http://dl-3.alpinelinux.org/alpine/edge/testing/ wkhtmltopdf

WORKDIR /app/

ADD Gemfile* /app/

RUN bundle install --deployment --without development test \
    && rm -rf ~/.bundle/cache

ADD . /app/

ENV RACK_ENV production
ENV DISPLAY=:0.0
ENV PORT 80
CMD Xvfb :0 -screen 0 1024x768x24 -ac +extension GLX +render -noreset & bundle exec puma -C config/puma.rb


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FF000000"
        android:pathData="M6,17h3l2,-4V7H5v6h3zm8,0h3l2,-4V7h-6v6h3z"/>
</vector>
<!-- From: file:/Users/Juleelala/AndroidStudioProjects/CSE110/Tuber/src/main/res/drawable-anydpi-v21/ic_format_quote_black_24dp.xml -->