text:
id: tutorial-webpack
title: Tutorial – webpack
layout: docs
category: Quick Start
permalink: docs/tutorial-webpack.html
next: tutorial-jquery
---

Jest can be used in projects that use webpack to manage assets, styles, and compilation.
webpack _does_ offers some unique challenges over other tools because it
integrates directly with your application to allow managing stylesheets,
assets like images and fonts, along with the expansive ecosystem of compile-to-JavaScript
languages and tools.

Let's start with a common sort of webpack config file and translate it to a Jest setup.

```js
// webpack.config.js
{
  module: {
    loaders: [
      { test: /\\.jsx?$/, loader: 'babel', exclude: ['node_modules'] },
      { test: /\\.css$/,  loader: "style-loader!css-loader" },
      { test: /\\.gif$/, loader: "url-loader" },
      { test: /\\.(ttf|eot|svg)$/, loader: "file-loader" },
    ]
  },
  resolve: {
    extensions: ['', 'js', 'jsx'],
    moduleDirectories: ['node_modules', 'bower_components', 'shared']
    root: '/shared/vendor/modules',
    alias: {
      react: './vendor/react-master',
      config$: './configs/app-config.js',
    },
  }
}
```

Any JavaScript specific compilation (in this case via Babel) can be handled with the Jest
`scriptPreprocessor` option. If you are using `babel-jest`, this will work automatically.

Next let's configure Jest to gracefully handle asset files such as stylesheets and images.
Since these files aren't particularly useful in tests anyway we can safely mock them out.

```js
// package.json
{
  "jest": {
    "moduleNameMapper": {
      "^.+\\.(css|less)$": "<rootDir>/test/styleMock.js",
      "^.+\\.(gif|ttf|eot|svg)$": "<rootDir>/test/fileMock.js"
    }
  }
}
```

And the mock file's themselves:

```js
// test/styleMock.js

// Return an object to emulate css modules (if you are using them)
module.exports = {};
```

Alternatively, you can use an [ES2015 Proxy](https://github.com/keyanzhang/identity-obj-proxy)
(`npm install --save-dev identity-obj-proxy` or create your own) to mock [CSS Modules](https://github.com/css-modules/css-modules); then all your className
lookups on the styles object will be returned as-is (e.g., `styles.foobar === 'foobar'`).

Notice that Proxy is enabled in Node.js `v6.*` by default; if you are not on Node `v6.*` yet,
make sure you invoke Jest using `node --harmony_proxies node_modules/.bin/jest`.

```js
// test/styleMock.js

// Return a Proxy to emulate css modules (if you are using them)

var idObj = require('identity-obj-proxy');
module.exports = idObj;
```

```js
// test/fileMock.js

// Return an empty string or other mock path to emulate the url that
// webpack provides via the file-loader
module.exports = '';
```

We've told Jest to ignore files matching a stylesheet or image extension, and instead,
require our mock files. You can adjust the regular expression to match the
file types your webpack config handles.

Now that Jest knows how to process our files, we need to tell it how to _find_ them.
For webpack's `moduleDirectories`, and `extensions` options there are direct analogs in Jest.

*Note: the `modulesDirectories` option in webpack is called `moduleDirectories` in Jest.*

```js
// package.json
{
  "jest": {
    "moduleFileExtensions": ["js", "jsx"],
    "moduleDirectories": ["node_modules", "bower_components", "shared"],

    "moduleNameMapper": {
      "^.+\\.(css|less)$": "<rootDir>/test/styleMock.js",
      "^.+\\.(gif|ttf|eot|svg)$": "<rootDir>/test/fileMock.js"
    }
  }
}
```

Similarly webpack's `resolve.root` option functions like setting the `NODE_PATH`
env variable, which you can set, or make use of the `modulePaths` option.

```js
// package.json
{
  "jest": {
    "modulePaths": [
      "/shared/vendor/modules"
    ],
    "moduleFileExtensions": ["js", "jsx"],
    "moduleDirectories": ["node_modules", "bower_components", "shared"],
    "moduleNameMapper": {
      "^.+\\.(css|less)$": "<rootDir>/test/styleMock.js",
      "^.+\\.(gif|ttf|eot|svg)$": "<rootDir>/test/fileMock.js"
    }
  }
}
```

And finally we just have the webpack `alias` left to handle. For that we can make use
of the `moduleNameMapper` option again.

```js
// package.json
{
  "jest": {
    "modulePaths": [
      "/shared/vendor/modules"
    ],
    "moduleFileExtensions": ["js", "jsx"],
    "moduleDirectories": ["node_modules", "bower_components", "shared"],

    "moduleNameMapper": {
      "^react": "<rootDir>/vendor/react-master",
      "^config$": "<rootDir>/configs/app-config.js",

      "^.+\\.(css|less)$": "<rootDir>/test/styleMock.js",
      "^.+\\.(gif|ttf|eot|svg)$": "<rootDir>/test/fileMock.js"
    }
  }
}
```

That's it! webpack is a complex and flexible tool, so you may have to make some adjustments
to handle your specific application's needs. Luckily for most projects, Jest should be more than
flexible enough to handle your webpack config.

*Note: For more complex webpack configurations, you may also want to investigate
projects such as: [babel-plugin-webpack-loaders](https://github.com/istarkov/babel-plugin-webpack-loaders).*

## webpack 2

webpack 2 offers native support for ES modules. However, Jest runs in Node, and
thus requires ES modules to be transpiled to CommonJS modules. As such, if you
are using webpack 2, you most likely will want to configure Babel to transpile
ES modules to CommonJS modules only in the `test` environment.

```js
// .babelrc
{
  "presets": [
    ["es2015", {"modules": false}]
  ],

  "env": {
    "test": {
      "plugins": ["transform-es2015-modules-commonjs"]
    }
  }
}
```


text:
function _zulu_list_usage() {
  builtin echo $(_zulu_color yellow "Usage:")
  builtin echo "  zulu list [options]"
  builtin echo
  builtin echo $(_zulu_color yellow "Options:")
  builtin echo "  -a, --all            List all packages in the index"
  builtin echo "  -d, --describe       Include package description in output"
  builtin echo "  -h, --help           Output this help text and exit"
  builtin echo "  -i, --installed      List only installed packages (default)"
  builtin echo "  -n, --not-installed  List non-installed packages"
  builtin echo "  -s, --simple         Hide the 'package installed' indicator"
  builtin echo "  -t, --type <type>    Limit results to packages of <type>"
  builtin echo "      --branch         Print the current branch (if one is checked out)"
  builtin echo "      --tag            Print the current tag (if one is checked out)"
}

###
# Output a list of packages
###
function _zulu_list_packages() {
  local base index files json packages package type name description pad lim

  base=${ZULU_DIR:-"${ZDOTDIR:-$HOME}/.zulu"}
  config=${ZULU_CONFIG_DIR:-"${ZDOTDIR:-$HOME}/.config/zulu"}
  index="$base/index/packages"

  for package in $(command ls $index); do
    # If --installed is passed but the package is not installed,
    # then skip past it
    if [[ -n $installed ]] && ! _zulu_info_is_installed $package; then
      continue
    fi

    # If --not-installed is passed but the package is installed,
    # then skip past it
    if [[ -n $not_installed ]] && _zulu_info_is_installed $package; then
      continue
    fi

    # We only need to read the package's index file if
    # the --type or --describe options are passed
    if [[ -n $package_type || -n $describe ]]; then
      json="$(command cat $index/$package)"
    fi

    # If --type is passed but the package is not of the
    # requested type, then skip past it
    if [[ -n $package_type ]]; then
      type=$(jsonval $json 'type')

      if [[ $type != $package_type ]]; then
        continue
      fi
    fi

    # Prevent ZVM from changing the ZSH version
    local old_ZVM_AUTO_USE=$ZVM_AUTO_USE
    builtin unset ZVM_AUTO_USE

    local suffix=''

    # If --branch is specified, get the current checked-out branch
    # for the package and print it alongside the name
    if [[ -n $branch ]] && _zulu_info_is_installed $package; then
      local oldPWD=$PWD
      builtin cd "$base/packages/$package"

      local current=$(command git status --short --branch -uno --ignore-submodules=all | command head -1 | command awk '{print $2}' 2>/dev/null)
      current=${current%...*}

      if [[ $current != 'HEAD' && $current != 'master' ]]; then
        suffix+=", branch: $current"
      fi

      builtin cd $oldPWD
      builtin unset oldPWD
    fi

    # If --tag is specified, get the current checked-out tag
    # for the package and print it alongside the name
    if [[ -n $tag ]] && _zulu_info_is_installed $package; then
      local oldPWD=$PWD
      builtin cd "$base/packages/$package"

      local commit=$(command git status HEAD -uno --ignore-submodules=all | command head -1 | command awk '{print $4}' 2>/dev/null)

      if [[ -n $commit ]]; then
        suffix+=", tag: $commit"
      fi

      builtin cd $oldPWD
      builtin unset oldPWD
    fi

    # Restore the previous ZVM_AUTO_USE setting
    export ZVM_AUTO_USE=$old_ZVM_AUTO_USE
    builtin unset old_ZVM_AUTO_USE

    # Print out the name of the package, and the installed flag
    # unless --simple is passed
    if [[ -n $simple ]]; then
      name="$package$suffix"
      lim=30
    else
      if _zulu_info_is_installed $package; then
        name="$(_zulu_color green '✔') $package$suffix"
        lim=42
      else
        name="  $package$suffix"
        lim=30
      fi
    fi

    # If --describe is specified, print the description
    if [[ -n $describe ]]; then
      description=$(jsonval $json 'description')
      builtin printf '%s' "$name"
      builtin printf '%*.*s' 0 $(($lim - ${#name} )) "$(builtin printf '%0.1s' " "{1..60})"
      builtin printf '%s\n' "$description"
    else
      builtin echo $name
    fi
  done

  return
}

###
# The main zulu list function
###
function _zulu_list() {
  local help all installed not_installed describe simple package_type branch tag

  # If no arguments are passed, just print a simple list
  # of all installed packages
  if [[ $# -eq 0 ]]; then
    installed=true
    simple=true
    _zulu_list_packages
    return
  fi

  # Parse options
  builtin zparseopts -D \
    h=help -help=help \
    i=installed -installed=installed \
    n=not_installed -not-installed=not_installed \
    a=all -all=all \
    d=describe -describe=describe \
    s=simple -simple=simple \
    t:=package_type -type:=package_type \
    -branch=branch \
    -tag=tag

  # Output help and return if requested
  if [[ -n $help ]]; then
    _zulu_list_usage
    return
  fi

  # Check if the --type option is passed and shift the argument
  if [[ -n $package_type ]]; then
    builtin shift package_type
  fi

  # List the packages
  _zulu_list_packages
}

redpajama_set_name: RedPajamaGithub


text:
from corehq import toggles
from dimagi.utils.couch.cache.cache_core import get_redis_client
from django.conf import settings

class MessagingRuleProgressHelper(object):

    def __init__(self, rule_id):
        self.rule_id = rule_id
        self.client = get_redis_client()

    @property
    def key_expiry(self):
        return 48 * 60 * 60

    @property
    def current_key(self):
        return 'messaging-rule-case-count-current-%s' % self.rule_id

    @property
    def total_key(self):
        return 'messaging-rule-case-count-total-%s' % self.rule_id

    @property
    def rule_initiation_key(self):
        return 'messaging-rule-run-initiated-%s' % self.rule_id

    @property
    def rule_cancellation_key(self):
        return 'messaging-rule-run-canceled-%s' % self.rule_id

    @property
    def completed_shards_key(self):
        return 'messaging-rule-run-shards-completed-%s' % self.rule_id

    @property
    def shard_count_key(self):
        return 'messaging-rule-run-total-shards-%s' % self.rule_id

    def set_rule_initiation_key(self):
        self.client.set(self.rule_initiation_key, 1, timeout=2 * 60 * 60)

    def clear_rule_initiation_key(self):
        self.client.delete(self.rule_initiation_key)

    def rule_initiation_key_is_set(self):
        return self.client.get(self.rule_initiation_key) is not None

    def rule_initiation_key_minutes_remaining(self):
        return (self.client.ttl(self.rule_initiation_key) // 60) or 1

    def set_initial_progress(self, shard_count=0):
        # shard_count is passed when tasks are run per each shard
        self.client.set(self.current_key, 0)
        if shard_count:
            self.client.set(self.shard_count_key, shard_count)
        for key in [self.current_key, self.total_key, self.shard_count_key, self.completed_shards_key]:
            self.client.expire(key, self.key_expiry)
        self.client.delete(self.rule_cancellation_key)
        self.set_rule_initiation_key()

    def set_total_cases_to_be_processed(self, total_cases):
        self.client.set(self.total_key, total_cases)

    def mark_shard_complete(self, db_alias):
        """Mark shard complete
        :returns: True if all shards are complete else false; None if shard
        count is not set.
        """
        shard_count = self.client.get(self.shard_count_key)
        pipe = self.client.client.get_client().pipeline()
        pipe.sadd(self.completed_shards_key, db_alias)
        pipe.scard(self.completed_shards_key)
        ignore, completed_count = pipe.execute()
        self.client.expire(self.shard_count_key, self.key_expiry)
        self.client.expire(self.completed_shards_key, self.key_expiry)
        return None if shard_count is None else completed_count == shard_count

    def set_rule_complete(self):
        self.clear_rule_initiation_key()

    def increment_current_case_count(self, fail_hard=False):
        try:
            self.client.incr(self.current_key)
            self.client.expire(self.current_key, self.key_expiry)
        except Exception:
            if fail_hard:
                raise

    def update_total_key_expiry(self):
        self.client.expire(self.total_key, self.key_expiry)

    def cancel(self):
        """Mark the current task as canceled

        The task is responsible for checking to see if it has been
        canceled and acting accordingly.
        """
        self.client.set(self.rule_cancellation_key, 1, timeout=2 * 60 * 60)

    def is_canceled(self):
        """Check if task has been canceled"""
        return self.client.get(self.rule_cancellation_key) is not None

    @staticmethod
    def _int_or_zero(value):
        try:
            return int(value)
        except (TypeError, ValueError):
            return 0

    def get_progress_pct(self):
        current = self.get_cases_processed()
        total = self.get_total_cases_to_process()

        if not current or not total:
            return 0

        if current >= total:
            return 100

        return int(round(100.0 * current / total, 0))

    def get_cases_processed(self):
        return self._int_or_zero(self.client.get(self.current_key))

    def get_total_cases_to_process(self):
        return self._int_or_zero(self.client.get(self.total_key))


text:
package com.sung.hee.user.dao;

import com.sung.hee.ent.model.SHEnt;
import com.sung.hee.user.model.SHUser;

import java.util.List;

public interface SHUserDAO {
    void regi(SHUser user) throws Exception;

    SHUser login(SHUser user);

    List<SHUser> userlist();

    int getID(SHUser user);

    String getPWD(SHUser user);

    void emailCerti(SHUser user);

    List<SHUser> getEntUserlist(SHEnt ent);

    void inPoint(SHUser user) throws Exception;

    void dePoint(SHUser user) throws Exception;

    void pwdUpdate(SHUser shUser);

    SHUser getIsSnS(SHUser shUser);
}


text:
package de.alpharogroup.wicket.components.velocity;

import org.apache.wicket.Component;

import de.alpharogroup.xml.tag.SimpleTag;

/**
 * The Class WicketField encapsulates a wicket component and can create its own html tag for this
 * component. It can be used with velocity to create dynamic panel without create html templates for
 * it.
 *
 * @param <C>
 *            the generic type for the Component
 */
public class WicketField<C extends Component> extends SimpleTag
{

	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 1L;

	/** The Constant WICKET_ID for the corresponding html attribute. */
	public static final String WICKET_ID = "wicket:id";

	/** The component. */
	private C component;

	/**
	 * Gets the component.
	 *
	 * @return the component
	 */
	public C getComponent()
	{
		return component;
	}

	/**
	 * Gets the wicket id.
	 *
	 * @return the wicket id
	 */
	public String getWicketId()
	{
		return getAttributes().get(WICKET_ID);
	}

	/**
	 * Sets the component.
	 *
	 * @param component
	 *            the new component
	 */
	public void setComponent(final C component)
	{
		this.component = component;
	}

}


text:
/**
 * @author mrdoob / http://mrdoob.com/
 */

var APP = {

	Player: function () {

		var renderer = new THREE.WebGLRenderer( { antialias: true } );
		renderer.setPixelRatio( window.devicePixelRatio );
		renderer.outputEncoding = THREE.sRGBEncoding;

		var loader = new THREE.ObjectLoader();
		var camera, scene;

		var vrButton = VRButton.createButton( renderer );

		var events = {};

		var dom = document.createElement( 'div' );
		dom.appendChild( renderer.domElement );

		this.dom = dom;

		this.width = 500;
		this.height = 500;

		this.load = function ( json ) {

			var project = json.project;

			renderer.shadowMap.enabled = project.shadows === true;
			renderer.xr.enabled = project.vr === true;

			this.setScene( loader.parse( json.scene ) );
			this.setCamera( loader.parse( json.camera ) );

			events = {
				init: [],
				start: [],
				stop: [],
				keydown: [],
				keyup: [],
				mousedown: [],
				mouseup: [],
				mousemove: [],
				touchstart: [],
				touchend: [],
				touchmove: [],
				update: []
			};

			var scriptWrapParams = 'player,renderer,scene,camera';
			var scriptWrapResultObj = {};

			for ( var eventKey in events ) {

				scriptWrapParams += ',' + eventKey;
				scriptWrapResultObj[ eventKey ] = eventKey;

			}

			var scriptWrapResult = JSON.stringify( scriptWrapResultObj ).replace( /\"/g, '' );

			for ( var uuid in json.scripts ) {

				var object = scene.getObjectByProperty( 'uuid', uuid, true );

				if ( object === undefined ) {

					console.warn( 'APP.Player: Script without object.', uuid );
					continue;

				}

				var scripts = json.scripts[ uuid ];

				for ( var i = 0; i < scripts.length; i ++ ) {

					var script = scripts[ i ];

					var functions = ( new Function( scriptWrapParams, script.source + '\nreturn ' + scriptWrapResult + ';' ).bind( object ) )( this, renderer, scene, camera );

					for ( var name in functions ) {

						if ( functions[ name ] === undefined ) continue;

						if ( events[ name ] === undefined ) {

							console.warn( 'APP.Player: Event type not supported (', name, ')' );
							continue;

						}

						events[ name ].push( functions[ name ].bind( object ) );

					}

				}

			}

			dispatch( events.init, arguments );

		};

		this.setCamera = function ( value ) {

			camera = value;
			camera.aspect = this.width / this.height;
			camera.updateProjectionMatrix();

		};

		this.setScene = function ( value ) {

			scene = value;

		};

		this.setSize = function ( width, height ) {

			this.width = width;
			this.height = height;

			if ( camera ) {

				camera.aspect = this.width / this.height;
				camera.updateProjectionMatrix();

			}

			if ( renderer ) {

				renderer.setSize( width, height );

			}

		};

		function dispatch( array, event ) {

			for ( var i = 0, l = array.length; i < l; i ++ ) {

				array[ i ]( event );

			}

		}

		var time, prevTime;

		function animate() {

			time = performance.now();

			try {

				dispatch( events.update, { time: time, delta: time - prevTime } );

			} catch ( e ) {

				console.error( ( e.message || e ), ( e.stack || "" ) );

			}

			renderer.render( scene, camera );

			prevTime = time;

		}

		this.play = function () {

			if ( renderer.xr.enabled ) dom.append( vrButton );

			prevTime = performance.now();

			document.addEventListener( 'keydown', onDocumentKeyDown );
			document.addEventListener( 'keyup', onDocumentKeyUp );
			document.addEventListener( 'mousedown', onDocumentMouseDown );
			document.addEventListener( 'mouseup', onDocumentMouseUp );
			document.addEventListener( 'mousemove', onDocumentMouseMove );
			document.addEventListener( 'touchstart', onDocumentTouchStart );
			document.addEventListener( 'touchend', onDocumentTouchEnd );
			document.addEventListener( 'touchmove', onDocumentTouchMove );

			dispatch( events.start, arguments );

			renderer.setAnimationLoop( animate );

		};

		this.stop = function () {

			if ( renderer.xr.enabled ) vrButton.remove();

			document.removeEventListener( 'keydown', onDocumentKeyDown );
			document.removeEventListener( 'keyup', onDocumentKeyUp );
			document.removeEventListener( 'mousedown', onDocumentMouseDown );
			document.removeEventListener( 'mouseup', onDocumentMouseUp );
			document.removeEventListener( 'mousemove', onDocumentMouseMove );
			document.removeEventListener( 'touchstart', onDocumentTouchStart );
			document.removeEventListener( 'touchend', onDocumentTouchEnd );
			document.removeEventListener( 'touchmove', onDocumentTouchMove );

			dispatch( events.stop, arguments );

			renderer.setAnimationLoop( null );

		};

		this.dispose = function () {

			renderer.dispose();

			camera = undefined;
			scene = undefined;

		};

		//

		function onDocumentKeyDown( event ) {

			dispatch( events.keydown, event );

		}

		function onDocumentKeyUp( event ) {

			dispatch( events.keyup, event );

		}

		function onDocumentMouseDown( event ) {

			dispatch( events.mousedown, event );

		}

		function onDocumentMouseUp( event ) {

			dispatch( events.mouseup, event );

		}

		function onDocumentMouseMove( event ) {

			dispatch( events.mousemove, event );

		}

		function onDocumentTouchStart( event ) {

			dispatch( events.touchstart, event );

		}

		function onDocumentTouchEnd( event ) {

			dispatch( events.touchend, event );

		}

		function onDocumentTouchMove( event ) {

			dispatch( events.touchmove, event );

		}

	}

};

export { APP };


text:
package com.amazonaws.services.kinesisfirehose.model.transform;

import static com.amazonaws.util.StringUtils.UTF8;
import static com.amazonaws.util.StringUtils.COMMA_SEPARATOR;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.regex.Pattern;

import com.amazonaws.AmazonClientException;
import com.amazonaws.Request;
import com.amazonaws.DefaultRequest;
import com.amazonaws.http.HttpMethodName;
import com.amazonaws.services.kinesisfirehose.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;

/**
 * CreateDeliveryStreamRequest Marshaller
 */
public class CreateDeliveryStreamRequestMarshaller
        implements
        Marshaller<Request<CreateDeliveryStreamRequest>, CreateDeliveryStreamRequest> {

    public Request<CreateDeliveryStreamRequest> marshall(
            CreateDeliveryStreamRequest createDeliveryStreamRequest) {

        if (createDeliveryStreamRequest == null) {
            throw new AmazonClientException(
                    "Invalid argument passed to marshall(...)");
        }

        Request<CreateDeliveryStreamRequest> request = new DefaultRequest<CreateDeliveryStreamRequest>(
                createDeliveryStreamRequest, "AmazonKinesisFirehose");
        request.addHeader("X-Amz-Target",
                "Firehose_20150804.CreateDeliveryStream");

        request.setHttpMethod(HttpMethodName.POST);

        request.setResourcePath("");

        try {
            StringWriter stringWriter = new StringWriter();
            JSONWriter jsonWriter = new JSONWriter(stringWriter);

            jsonWriter.object();

            if (createDeliveryStreamRequest.getDeliveryStreamName() != null) {
                jsonWriter.key("DeliveryStreamName").value(
                        createDeliveryStreamRequest.getDeliveryStreamName());
            }

            if (createDeliveryStreamRequest.getS3DestinationConfiguration() != null) {
                jsonWriter.key("S3DestinationConfiguration");
                S3DestinationConfigurationJsonMarshaller
                        .getInstance()
                        .marshall(
                                createDeliveryStreamRequest
                                        .getS3DestinationConfiguration(),
                                jsonWriter);
            }

            if (createDeliveryStreamRequest
                    .getRedshiftDestinationConfiguration() != null) {
                jsonWriter.key("RedshiftDestinationConfiguration");
                RedshiftDestinationConfigurationJsonMarshaller
                        .getInstance()
                        .marshall(
                                createDeliveryStreamRequest
                                        .getRedshiftDestinationConfiguration(),
                                jsonWriter);
            }

            jsonWriter.endObject();

            String snippet = stringWriter.toString();
            byte[] content = snippet.getBytes(UTF8);
            request.setContent(new StringInputStream(snippet));
            request.addHeader("Content-Length",
                    Integer.toString(content.length));
            request.addHeader("Content-Type", "application/x-amz-json-1.1");
        } catch (Throwable t) {
            throw new AmazonClientException(
                    "Unable to marshall request to JSON: " + t.getMessage(), t);
        }

        return request;
    }

}


text:
@interface DPPrototypeTests : XCTestCase

@end

@implementation DPPrototypeTests

- (void)testPrototypeShallowCopy {
    DPResume *resume1 = [[DPResumeShallowCopy alloc] initWithName:@"大鸟"];
    [resume1 setPersonalInfoWithSex:@"男" age:@"29"];
    [resume1 setWorkExperienceWithWorkDate:@"1998-2000" company:@"XX 公司"];
    NSLog(@"Retain count is %ld", CFGetRetainCount((__bridge CFTypeRef)resume1));

    DPResume *resume2 = [resume1 copy];
    [resume2 setWorkExperienceWithWorkDate:@"1998-2006" company:@"YY 企业"];
    NSLog(@"Retain count is %ld", CFGetRetainCount((__bridge CFTypeRef)resume2));

    DPResume *resume3 = [resume1 copy];
    [resume3 setPersonalInfoWithSex:@"男" age:@"24"];
    [resume3 setWorkExperienceWithWorkDate:@"1998-2003" company:@"ZZ 企业"];
    NSLog(@"Retain count is %ld", CFGetRetainCount((__bridge CFTypeRef)resume3));

    [resume1 display];
    [resume2 display];
    [resume3 display];
}

- (void)testPrototypeDeepCopy {
    DPResume *resume1 = [[DPResumeDeepCopy alloc] initWithName:@"大鸟"];
    [resume1 setPersonalInfoWithSex:@"男" age:@"29"];
    [resume1 setWorkExperienceWithWorkDate:@"1998-2000" company:@"XX 公司"];
    NSLog(@"Retain count is %ld", CFGetRetainCount((__bridge CFTypeRef)resume1));

    DPResume *resume2 = [resume1 copy];
    [resume2 setWorkExperienceWithWorkDate:@"1998-2006" company:@"YY 企业"];
    NSLog(@"Retain count is %ld", CFGetRetainCount((__bridge CFTypeRef)resume2));

    DPResume *resume3 = [resume1 copy];
    [resume3 setPersonalInfoWithSex:@"男" age:@"24"];
    [resume3 setWorkExperienceWithWorkDate:@"1998-2003" company:@"ZZ 企业"];
    NSLog(@"Retain count is %ld", CFGetRetainCount((__bridge CFTypeRef)resume3));

    [resume1 display];
    [resume2 display];
    [resume3 display];
}

@end


text:
Edit your profile

<?php echo form_open_multipart('edit');?>
<?php echo isset($register_success) ? '
' . $register_success . '
' : ''; ?>
<?php echo isset($register_error) ? '
' . $register_error . '
' : ''; ?>

            Email :
            <input class="u-full-width" type="email" placeholder="test@mailbox.com" id="u_email" name="u_email" value="<?= $userData['u_email']; ?>">
            <?php echo form_error('u_email','
','
'); ?>

            Name :
            <input class="u-full-width" type="text" placeholder="Anton" id="u_name" name="u_name" value="<?= ucfirst($userData['u_name']); ?>">
            <?php echo form_error('u_name','
','
'); ?>

            Surname :
            <input class="u-full-width" type="text" placeholder="Shamseev" id="u_surname" name="u_surname" value="<?= ucfirst($userData['u_surname']); ?>">
            <?php echo form_error('u_surname','
','
'); ?>

            Date of Birth :
            <input class="u-full-width" type="date" placeholder="Shamseev" id="u_dob" name="u_dob" value="<?= date('Y-m-d', strtotime($userData['u_dob'])); ?>">
            <?php echo form_error('u_dob','
','
'); ?>

                Phone :
                <input class="u-full-width" type="text" placeholder="+xx(xxx)xxx-xxx-x" id="u_phone" name="u_phone" value="<?= $userData['u_phone']; ?>">
                <?php echo form_error('u_phone','
','
'); ?>

                Country or State :
                <input class="u-full-width" type="text" placeholder="Ukraine" id="u_country" name="u_country" value="<?= ucfirst($userData['u_country']); ?>">
                <?php echo form_error('u_country','
','
'); ?>

                City :
                <input class="u-full-width" type="text" placeholder="Zaporizhzhya" id="u_city" name="u_city" value="<?= ucfirst($userData['u_city']); ?>">
                <?php echo form_error('u_city','
','
'); ?>

            Address :
            <input class="u-full-width" type="text" placeholder="Severnoe Shosse" id="u_address" name="u_address" value="<?= ucfirst($userData['u_address']); ?>">
            <?php echo form_error('u_address','
','
'); ?>

            Post code :
            <input class="u-full-width" type="text" placeholder="69006" id="u_post_code" name="u_post_code" value="<?= $userData['u_post_code']; ?>">
            <?php echo form_error('u_post_code','
','
'); ?>

            Password :
            <input class="u-full-width" type="password" id="u_pwd" name="u_pwd">
            <?php echo form_error('u_pwd','
','
'); ?>

            Confirm Password :
            <input class="u-full-width" type="password" id="u_pwd_confirm" name="u_pwd_confirm">
            <?php echo form_error('u_pwd_confirm','
','
'); ?>

        Choose Image
        <input class="button-default" type="file" name="u_avatar" id="u_avatar" />

<input class="button-default" type="submit" value="Save changes" name="submit-edit" id="submit-edit">
<?php echo anchor(site_url('profile'),'Back','class="button back-link"'); ?>
<?php form_close();?>


text:
/* $NetBSD: ixgbe_netbsd.c,v 1.1 2011/08/12 21:55:29 dyoung Exp $ */
/*
 * Copyright (c) 2011 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Coyote Point Systems, Inc.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <sys/param.h>

#include <sys/atomic.h>
#include <sys/bus.h>
#include <sys/condvar.h>
#include <sys/cpu.h>
#include <sys/kmem.h>
#include <sys/mbuf.h>
#include <sys/mutex.h>
#include <sys/queue.h>
#include <sys/workqueue.h>

#include "ixgbe_netbsd.h"

void
ixgbe_dma_tag_destroy(ixgbe_dma_tag_t *dt)
{
	kmem_free(dt, sizeof(*dt));
}

int
ixgbe_dma_tag_create(bus_dma_tag_t dmat, bus_size_t alignment,
    bus_size_t boundary, bus_size_t maxsize, int nsegments,
    bus_size_t maxsegsize, int flags, ixgbe_dma_tag_t **dtp)
{
	ixgbe_dma_tag_t *dt;

	*dtp = NULL;

	if ((dt = kmem_zalloc(sizeof(*dt), KM_SLEEP)) == NULL)
		return ENOMEM;

	dt->dt_dmat = dmat;
	dt->dt_alignment = alignment;
	dt->dt_boundary = boundary;
	dt->dt_maxsize = maxsize;
	dt->dt_nsegments = nsegments;
	dt->dt_maxsegsize = maxsegsize;
	dt->dt_flags = flags;
	*dtp = dt;

	return 0;
}

void
ixgbe_dmamap_destroy(ixgbe_dma_tag_t *dt, bus_dmamap_t dmam)
{
	bus_dmamap_destroy(dt->dt_dmat, dmam);
}

void
ixgbe_dmamap_sync(ixgbe_dma_tag_t *dt, bus_dmamap_t dmam, int ops)
{
        bus_dmamap_sync(dt->dt_dmat, dmam, 0, dt->dt_maxsize, ops);
}

void
ixgbe_dmamap_unload(ixgbe_dma_tag_t *dt, bus_dmamap_t dmam)
{
	bus_dmamap_unload(dt->dt_dmat, dmam);
}

int
ixgbe_dmamap_create(ixgbe_dma_tag_t *dt, int flags, bus_dmamap_t *dmamp)
{
	return bus_dmamap_create(dt->dt_dmat, dt->dt_maxsize, dt->dt_nsegments,
	    dt->dt_maxsegsize, dt->dt_boundary, flags, dmamp);
}

static void
ixgbe_putext(ixgbe_extmem_t *em)
{
	ixgbe_extmem_head_t *eh = em->em_head;

	mutex_enter(&eh->eh_mtx);

	TAILQ_INSERT_HEAD(&eh->eh_freelist, em, em_link);

	mutex_exit(&eh->eh_mtx);

	return;
}

static ixgbe_extmem_t *
ixgbe_getext(ixgbe_extmem_head_t *eh, size_t size)
{
	ixgbe_extmem_t *em;

	mutex_enter(&eh->eh_mtx);

	TAILQ_FOREACH(em, &eh->eh_freelist, em_link) {
		if (em->em_size >= size)
			break;
	}

	if (em != NULL)
		TAILQ_REMOVE(&eh->eh_freelist, em, em_link);

	mutex_exit(&eh->eh_mtx);

	return em;
}

static ixgbe_extmem_t *
ixgbe_newext(ixgbe_extmem_head_t *eh, bus_dma_tag_t dmat, size_t size)
{
	ixgbe_extmem_t *em;
	int nseg, rc;

	em = kmem_zalloc(sizeof(*em), KM_SLEEP);

	if (em == NULL)
		return NULL;

	rc = bus_dmamem_alloc(dmat, size, PAGE_SIZE, 0, &em->em_seg, 1, &nseg,
	    BUS_DMA_WAITOK);

	if (rc != 0)
		goto post_zalloc_err;

	rc = bus_dmamem_map(dmat, &em->em_seg, 1, size, &em->em_vaddr,
	    BUS_DMA_WAITOK);

	if (rc != 0)
		goto post_dmamem_err;

	em->em_dmat = dmat;
	em->em_size = size;
	em->em_head = eh;

	return em;
post_dmamem_err:
	bus_dmamem_free(dmat, &em->em_seg, 1);
post_zalloc_err:
	kmem_free(em, sizeof(*em));
	return NULL;
}

void
ixgbe_jcl_reinit(ixgbe_extmem_head_t *eh, bus_dma_tag_t dmat, int nbuf,
    size_t size)
{
	int i;
	ixgbe_extmem_t *em;

	if (!eh->eh_initialized) {
		TAILQ_INIT(&eh->eh_freelist);
		mutex_init(&eh->eh_mtx, MUTEX_DEFAULT, IPL_NET);
		eh->eh_initialized = true;
	}

	while ((em = ixgbe_getext(eh, 0)) != NULL) {
		KASSERT(em->em_vaddr != NULL);
		bus_dmamem_unmap(dmat, em->em_vaddr, em->em_size);
		bus_dmamem_free(dmat, &em->em_seg, 1);
		memset(em, 0, sizeof(*em));
		kmem_free(em, sizeof(*em));
	}

	for (i = 0; i < nbuf; i++) {
		if ((em = ixgbe_newext(eh, dmat, size)) == NULL) {
			printf("%s: only %d of %d jumbo buffers allocated\n",
			    __func__, i, nbuf);
			break;
		}
		ixgbe_putext(em);
	}
}

static void
ixgbe_jcl_free(struct mbuf *m, void *buf, size_t size, void *arg)
{
	ixgbe_extmem_t *em = arg;

	KASSERT(em->em_size == size);

	ixgbe_putext(em);
	/* this is an abstraction violation, but it does not lead to a
	 * double-free
	 */
	if (__predict_true(m != NULL)) {
		KASSERT(m->m_type != MT_FREE);
		m->m_type = MT_FREE;
		pool_cache_put(mb_cache, m);
	}
}

/* XXX need to wait for the system to finish with each jumbo mbuf and
 * free it before detaching the driver from the device.
 */
struct mbuf *
ixgbe_getjcl(ixgbe_extmem_head_t *eh, int nowait /* M_DONTWAIT */,
    int type /* MT_DATA */, int flags /* M_PKTHDR */, size_t size)
{
	ixgbe_extmem_t *em;
	struct mbuf *m;

	if ((flags & M_PKTHDR) != 0)
		m = m_gethdr(nowait, type);
	else
		m = m_get(nowait, type);

	if (m == NULL)
		return NULL;

	em = ixgbe_getext(eh, size);
	if (em == NULL) {
		m_freem(m);
		return NULL;
	}

	MEXTADD(m, em->em_vaddr, em->em_size, M_DEVBUF, &ixgbe_jcl_free, em);

	if ((m->m_flags & M_EXT) == 0) {
		ixgbe_putext(em);
		m_freem(m);
		return NULL;
	}

	return m;
}


text:
$:.unshift File.dirname(__FILE__)
require 'exception'
require 'tuple'

class Module
  def ivar_as_index(hash)
    # do nothing
  end

  public :include
end

module Rubinius
  class AtExit
    def self.unshift(x) end
  end
end

# -- special logic for Array --

class Array
  alias :old_inspect :inspect

  def inspect()
    "RUBY_LITERAL" + old_inspect
  end
end

class Object
  remove_const :Array
  def disable_long_return!() end
end

require 'kernel/bootstrap/array'
require 'kernel/core/array'


text:
/* Rate limiting */
  app.enable('trust proxy')
  app.use('/rest/user/reset-password', new RateLimit({
    windowMs: 5 * 60 * 1000,
    max: 100,
    keyGenerator ({ headers, ip }) { return headers['Forwarded'] || ip }
  }))


text:
layout: post
title: mercurial-sure-why-not
---
Some of the new super cool things on the block are Distributed Version
Control Systems and being somebody that is into super cool new things I
figured I would spend some time and get to know them.

A couple months ago [Steve](http://stevenkuhn.net) and I had a
hack-a-thon weekend and he introduced me to [Git](http://git-scm.com/).
I have to say that I didn't really like Git.  I found it a bit
cumbersome and confusing.  Honestly, that is probably more my fault than
Git's because I had no idea how DVCSs worked and Git is a little to
powerful to be put in the hands of a novice.  Needless to say handing me
Git was like handing me a .45 and pointing it at my foot.  It was only a
matter of time until I shot myself.

So after blowing off both of my feet and a few other appendages I wrote
DVCS off as a bad idea.  Luckily [Joel
Spolsky](http://www.joelonsoftware.com/) wrote a very awesome [intro to
Mercurial](http://hginit.com/) that peeked my interest again.  Reading
the intro filled in a lot of the blanks in my mental model of how DVCS
works.  I suggest you spend some time reading the intro and then do as I
did and go purchase the really awesome [Mastering
Mercurial](http://tekpub.com/preview/hg) series from TekPub.  Once you
watch that I think you'll find Mercurial (and Git) a very compelling SCM
solution.  I found it compelling enough to get a
[Kiln](http://kilnhg.com) account and try it out on a real honest to
goodness (private) project.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:id="@+id/trasparent_activity_start"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Transparent Activity"
        android:onClick="onTransparentActivity"
         />
    <Button
        android:id="@+id/page_example_activity_start"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="PageExample Activity"
        android:onClick="onPageExampleActivity"
        />
</LinearLayout>


text:
FOUNDATION_EXPORT double Pods_MTablesView_TestsVersionNumber;
FOUNDATION_EXPORT const unsigned char Pods_MTablesView_TestsVersionString[];


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PFM.DataAccessLayer.Enumerations
{
    public enum PaymentMethod
    {
        CB = 1,
        Cash = 2,
        DirectDebit = 3,
        Transfer = 4,
        InternalTransfer = 5
    }
}


text:
<?php
/**
 * @author Krzysztof Gzocha <krzysztof.gzocha@xsolve.pl>
 */
namespace Team3\PayU\Order\Autocomplete;

use Team3\PayU\PayUException;

class OrderAutocompleteException extends PayUException
{
}


text:
namespace PR {
template <class T>
class PR_LIB_CORE AbstractDatabase {
public:
	using ObjectList = std::vector<std::shared_ptr<T>>;

	AbstractDatabase()			= default;
	virtual ~AbstractDatabase() = default;

	inline void shrinkToFit() { mObjects.shrink_to_fit(); }

	inline const ObjectList& getAll() const { return mObjects; }
	inline size_t size() const { return mObjects.size(); }

	// Access with ID is always provided

	inline std::shared_ptr<T> get(uint32 id) const { return this->mObjects[id]; }
	inline bool has(uint32 id) const { return id < this->mObjects.size(); }

	inline std::shared_ptr<T> getSafe(uint32 id) const { return has(id) ? get(id) : nullptr; }

protected:
	inline uint32 nextID() const { return (uint32)size(); }

	ObjectList mObjects;
};

/// Special class which only allows anonymous creation
template <class T>
class PR_LIB_CORE AnonymousDatabase : public AbstractDatabase<T> {
public:
	AnonymousDatabase()			 = default;
	virtual ~AnonymousDatabase() = default;

	inline uint32 add(const std::shared_ptr<T>& mat)
	{
		const uint32 id = this->nextID();
		this->mObjects.emplace_back(mat);
		return id;
	}
};

/// Special class which only allows named creation
template <class T>
class PR_LIB_CORE NamedDatabase : public AbstractDatabase<T> {
public:
	using NamedObjectList = std::unordered_map<std::string, uint32>;

	NamedDatabase()			 = default;
	virtual ~NamedDatabase() = default;

	inline uint32 add(const std::string& name, const std::shared_ptr<T>& mat)
	{
		const uint32 id = this->nextID();
		this->mObjects.emplace_back(mat);
		mNamedObjects[name] = id;
		return id;
	}

	using AbstractDatabase<T>::get;
	using AbstractDatabase<T>::has;

	inline uint32 getID(const std::string& name) const { return (mNamedObjects.count(name) != 0) ? mNamedObjects.at(name) : PR_INVALID_ID; }
	inline std::shared_ptr<T> get(const std::string& name) const { return (mNamedObjects.count(name) != 0) ? this->get(mNamedObjects.at(name)) : nullptr; }
	inline bool has(const std::string& name) const { return get(name) != nullptr; }

	inline const NamedObjectList& getAllNamed() const { return mNamedObjects; }

protected:
	NamedObjectList mNamedObjects;
};

/// Special class which allows anonymous and named creation
template <class T>
class PR_LIB_CORE MixedDatabase : public NamedDatabase<T> {
public:
	MixedDatabase()			 = default;
	virtual ~MixedDatabase() = default;

	using NamedDatabase<T>::add;
	inline uint32 add(const std::shared_ptr<T>& mat)
	{
		const uint32 id = this->nextID();
		this->mObjects.emplace_back(mat);
		return id;
	}
};
} // namespace PR


text:
(function(){

	'use strict';

	angular.module('myApp')

		.factory('FSDataService', FSDataService);

		FSDataService.$inject = ['$http'];

		function FSDataService($http){

			var FourSquareService = {

				checkForVenues: checkForVenues,

				getVenueLocationsByType: getVenueLocationsByType,

				getVenue: getVenue,

				getVenuePhotos: getVenuePhotos,

				getSimilarVenues: getSimilarVenues

			};

			return FourSquareService;

			function checkForVenues(foodType, ll) {

				//checks for validity of search term
				return $http.get('/api/venues/' + foodType + '/' + ll)
					.then(function( response ){

						//checks if there are available venues
						//sent back from the server
						if( response.data.response.groups[0].items.length > 0 ) {
							return true;
						} else {
							return false;
						}
					})
					.catch(function(error){
						if(error) {
							return error;
						}
					});

			}

			function getVenueLocationsByType(foodType, ll){
				return $http.get('/api/venues/' + foodType + '/' + ll)
					.then(function(response){
						if(response) {
							var venues = response.data.response.groups[0].items;
							return venues;
						}
					})
					.catch(function(error){
						if(error) {
							return error;

						}
					});

			}

			function getVenue(venueId){

				return $http.get('/api/venue/' + venueId);

			}

			function getVenuePhotos(venueId){

				return $http.get('/api/venue/photos/' + venueId);
			}

			function getSimilarVenues(venueId){

				return $http.get('/api/venue/similar/' + venueId);

			}

		}

}());


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
MessagePropertiesType
</TITLE>

<META NAME="date" CONTENT="2011-07-19">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.jboss.shrinkwrap.descriptor.api.jboss51

Interface MessagePropertiesType<T>

All Superinterfaces:
org.jboss.shrinkwrap.descriptor.api.Child<T>

All Known Implementing Classes:
MessagePropertiesTypeImpl

public interface MessagePropertiesType<T>
extends org.jboss.shrinkwrap.descriptor.api.Child<T>

This interface defines the contract for the  message-propertiesType  xsd type

 Original Documentation:

 Element for defining JMS message properties (e.g. persistence, priority)

 for a consumer bean Used in: consumer

Since:

Generation date :2011-07-19T22:54:35.59+02:00

Author:

Ralf Battenfeld

Method Summary

 java.lang.String
getClazz()

          Returns the class element

 java.lang.String
getDelivery()

          Returns the delivery element

 java.lang.Integer
getPriority()

          Returns the priority element

 MethodType<MessagePropertiesType<T>>
method()

          If not already created, a new method element will be created and returned.

 MessagePropertiesType<T>
removeClazz()

          Removes the class element

 MessagePropertiesType<T>
removeDelivery()

          Removes the delivery element

 MessagePropertiesType<T>
removeMethod()

          Removes the method element

 MessagePropertiesType<T>
removePriority()

          Removes the priority element

 MessagePropertiesType<T>
setClazz(java.lang.String clazz)

          If not already created, a new class element with the given value will be created.

 MessagePropertiesType<T>
setDelivery(java.lang.String delivery)

          If not already created, a new delivery element with the given value will be created.

 MessagePropertiesType<T>
setPriority(java.lang.Integer priority)

          If not already created, a new priority element with the given value will be created.

Methods inherited from interface org.jboss.shrinkwrap.descriptor.api.Child

up

Method Detail

setClazz

MessagePropertiesType<T> setClazz(java.lang.String clazz)

If not already created, a new class element with the given value will be created.
 Otherwise, the existing class element will be updated with the given value.

Returns:
the current instance of MessagePropertiesType<T>

removeClazz

MessagePropertiesType<T> removeClazz()

Removes the class element

Returns:
the current instance of MessagePropertiesType<T>

getClazz

java.lang.String getClazz()

Returns the class element

Returns:
the node defined for the element class

removeMethod

MessagePropertiesType<T> removeMethod()

Removes the method element

Returns:
the current instance of MessagePropertiesType<T>

method

MethodType<MessagePropertiesType<T>> method()

If not already created, a new method element will be created and returned.
 Otherwise, the existing method element will be returned.

Returns:
the node defined for the element method

setDelivery

MessagePropertiesType<T> setDelivery(java.lang.String delivery)

If not already created, a new delivery element with the given value will be created.
 Otherwise, the existing delivery element will be updated with the given value.

Returns:
the current instance of MessagePropertiesType<T>

removeDelivery

MessagePropertiesType<T> removeDelivery()

Removes the delivery element

Returns:
the current instance of MessagePropertiesType<T>

getDelivery

java.lang.String getDelivery()

Returns the delivery element

Returns:
the node defined for the element delivery

setPriority

MessagePropertiesType<T> setPriority(java.lang.Integer priority)

If not already created, a new priority element with the given value will be created.
 Otherwise, the existing priority element will be updated with the given value.

Returns:
the current instance of MessagePropertiesType<T>

removePriority

MessagePropertiesType<T> removePriority()

Removes the priority element

Returns:
the current instance of MessagePropertiesType<T>

getPriority

java.lang.Integer getPriority()

Returns the priority element

Returns:
the node defined for the element priority

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>org.devbox.karaf</groupId>
        <artifactId>assembly</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <artifactId>custom-distro</artifactId>
    <packaging>karaf-assembly</packaging>

    <name>K-D-E :: Assembly :: Custom Distro</name>

    <dependencies>
        <dependency>
            <groupId>org.apache.karaf.features</groupId>
            <artifactId>framework</artifactId>
            <version>${karaf.version}</version>
            <type>kar</type>
        </dependency>
        <dependency>
            <groupId>org.apache.karaf.features</groupId>
            <artifactId>standard</artifactId>
            <version>${karaf.version}</version>
            <classifier>features</classifier>
            <type>xml</type>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.camel.karaf</groupId>
            <artifactId>apache-camel</artifactId>
            <version>${camel.version}</version>
            <classifier>features</classifier>
            <type>xml</type>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>custom-feature</artifactId>
            <version>${project.version}</version>
            <classifier>features</classifier>
            <type>xml</type>
            <scope>runtime</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.karaf.tooling</groupId>
                <artifactId>karaf-maven-plugin</artifactId>
                <configuration>
                    <bootFeatures>
                        <feature>standard</feature>
                        <feature>management</feature>
                        <feature>custom-feature</feature>
                    </bootFeatures>
                    <installedFeatures>
                        <feature>camel</feature>
                        <feature>camel-blueprint</feature>
                        <feature>camel-core</feature>
                    </installedFeatures>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
layout: post
title: Writing Angular code in ES5
relatedLinks:
  - title: Exploring Angular 2 - Article Series
    url: /exploring-angular-2
  - title: The difference between decorators and annotations
    url: /angular/2015/05/03/the-difference-between-annotations-and-decorators.html
  - title: Builing a zippy component in Angular 2
    url: /angular/2015/03/27/building-a-zippy-component-in-angular-2.html
  - title: Even better ES5 code for Angular 2
    url: /angular/2015/07/06/even-better-es5-code-for-angular-2.html
  - title: Angular ES5 Demo
    url: 'http://plnkr.co/edit/XmZkHzl407z93R5Kf0pv?p=preview'
date: 2015-05-09T00:00:00.000Z
update_date: 2016-12-16T00:00:00.000Z
summary: >-
  Ever wondered what it's like to write Angular 2 in ES5? Check out this
  article!
categories:
  - angular
tags:
  - angular2
topic: upgrade
author: pascal_precht
demos:
  - url: 'http://plnkr.co/edit/BUYnsbW7WX6FTjlK7mUh?p=preview'
    title: Hello World app in ES5
  - url: 'https://plnkr.co/edit/l2kmT4w0uQMzuwHk4nc6?p=preview'
    title: Hello World app with service injection
related_posts:
  - RxJS Master Class and courseware updates
  - Advanced caching with RxJS
  - Custom Overlays with Angular's CDK - Part 2
  - Custom Overlays with Angular's CDK
  - Easy Dialogs with Angular Material
  - A web animations deep dive with Angular
related_videos:
  - '175255006'
  - '193524896'
  - '189792758'
  - '189785428'
  - '175218351'
  - '189618526'

---

It's no news anymore that Angular 2.x was written in TypeScript in order to take advantage of language features like types and meta data annotations through decorators. Taking a first look at Angular examples that are written in TypeScript, can feel a bit unfamiliar and unclear to developers that don't have experience with that language. Even constructs like classes that ECMAScript 2015 brings to the table can be scary enough to keep developers from learning Angular.

That's why developers with more experience will tell us that we don't have to write TypeScript or just ES6 if we don't want to. We can just stick with ES5. Cool, fine. But how do we do that? In one of our last articles we've explored the [difference between annotations and decorators](/angular/2015/05/03/the-difference-between-annotations-and-decorators.html) and to what they translate to in ES5.

In this article, we will use that information, to actually write Angular code in ES5 with the latest version released at the time of writing (2.x).

## Getting started with Angular in ES5

If you've read our article on [building a zippy component](/angular/2015/03/27/building-a-zippy-component-in-angular-2.html) in Angular, you might know that nowadays, there's quite a bit of work to do, in order to get started if you want to write your application in ES6/TypeScript and take advantage of it's module system.

In ES5 we don't have a module system yet. So ideally, we should be able to just take a JavaScript file from somewhere, that has all the Angular code in it, so we can embed it in our website. We don't have to care about transpiling, concatenating, deciding on a module system (AMD, Common, System, ...), or anything else. We can just fetch a bundled file that comes with the ready-to-use code.

The easiest way to get hold of Angular ES5 bundles is npmcdn. Here's what we need to embed to get started with ES5 and Angular:

```html
<script src="https://npmcdn.com/@angular/core@2.0.0-rc.5/bundles/core.umd.js"></script>
<script src="https://npmcdn.com/@angular/common@2.0.0-rc.5/bundles/common.umd.js"></script>
<script src="https://npmcdn.com/@angular/compiler@2.0.0-rc.5/bundles/compiler.umd.js"></script>
<script src="https://npmcdn.com/@angular/platform-browser@2.0.0-rc.5/bundles/platform-browser.umd.js"></script>
<script src="https://npmcdn.com/@angular/platform-browser-dynamic@2.0.0-rc.5/bundles/platform-browser-dynamic.umd.js"></script>
```

Whereas `@2.0.0-rc.5` is the version number we specify. So that part might change depending on what we want to do.

Now the next question comes up: How can we access and use given annotations and/or decorators? Usually, in ES2015, we would import them from the framework but now there's no way for us to import them.

Well, it turns out that the bundled version exposes an `ng.core` object on the current global scope or reuses an existing one, which has all annotations added to it. In our [last article](http://blog.thoughtram.io/angular/2015/05/03/the-difference-between-annotations-and-decorators.html) we've learned that annotations are just classes, which in the end are just functions. And those functions are called as constructor functions to add meta data to our components. That means, all we have to do is to call those annotation constructors manually and assign them to our component's `annotations` property.

Let's start off with a simple component that has a template:

```js
var HelloComponent = function () {

};

HelloComponent.annotations = [
  new ng.core.Component({
    selector: 'hello-cmp',
    template: 'Hello World!'
  })
];
```

That's it. We have a constructor function that has a component annotation and a view annotation. The TypeScript equivalent would look something like this:

```js
@Component({
  selector: 'hello-cmp',
  template: 'Hello World!'
})
class HelloComponent {

}
```

## Bootstrapping an Angular app in ES5

When we come to the point that we want to bootstrap our application, we need to define an `NgModule` that has everything attached to it that is needed to make our app run, and bootstrap it on a dedicated platform (e.g. browser, webworker or server).

Let's go ahead and create such a module first. `ng.core.NgModule` can be used to create the needed metadata on a constructor function. Just like with our `HelloComponent`, we create an `AppModule` function like this:

```js
var AppModule = function () {

};
```

Next, we add `NgModule` annotations to it:

```js
AppModule.annotations = [
  new ng.core.NgModule({
    imports: [ng.platformBrowser.BrowserModule],
    declarations: [HelloComponent],
    bootstrap: [HelloComponent]
  })
];
```

Similar to TypeScript world, we have to import the `BrowserModule` from the `ng.platformBrowser` package, so we can bootstrap our module in the browser environment. Next, we declare all directives and components that are used inside this module, which in our case, is only the `HelloComponent`. Last but not least, we tell Angular which component to bootstrap when the module is bootstrapped.

We need to make sure that all of the DOM is loaded before we bootstrap our module. Adding an event listener for the `DOMContentLoaded` event and call `bootstrap` once triggered, will help here. When the event is fired, we can call `platformBrowserDynamic().bootstrapModule(AppModule)` to bootstrap our app:

```js
document.addEventListener('DOMContentLoaded', function () {
  ng.platformBrowserDynamic
    .platformBrowserDynamic().bootstrapModule(AppModule);
});
```

And of course, the corresponding application template looks like this:

```html
<body>
  <hello-component></hello-component>
</body>
```

Great we've just bootstrapped our Angular application written in ES5! Was it that hard?

## Injecting services in ES5

Let's say we want to add a `GreetingService` to our component. The `@Component` annotation takes a property `viewProviders` to define injectable types for this particular component. This is easy to add. First we build the service. A service in Angular can be just a class, which translates to just a function, which is also just an object in JavaScript.

```js
var GreetingService = function () {}

GreetingService.prototype.greeting = function () {
  return 'Hello';
};
```

Next we tell our component about it's injectable types:

```js
HelloComponent.annotations = [
  new ng.Component({
    selector: 'hello-cmp',
    providers: [GreetingService]
  }),
  ...
];
```

This basically tells our component that it should return an instance of `GreetingService` when somebody asks for `GreetingService`. Nobody asked for it yet, so let's change that. First we need something we want to inject into our component's constructor:

```js
var HelloComponent = function (greetingService) {
  this.greeting = greetingService.greeting();
};
```

To make our component explicitly ask for something that is a `GreetingService`, or in other words, to tell the injector that our `greetingService` parameter should be an instance of `GreetingService`, we need to add a parameter annotation accordingly:

```js
HelloComponent.parameters = [[new ng.core.Inject(GreetingService)]];
```

If you wonder why we define a nested array, this is because one constructor parameter can have more than one associated annotation.

Cool, so it turns out that writing Angular code is actually not weird at all. In addition to that, it kind of gets clear that writing Angular code in ES5 requires more typing. But again, in the end it's up to the application author which language or transpiler to use.

There's even a [better syntax](/angular/2015/07/06/even-better-es5-code-for-angular-2.html), that makes writing and reading Angular code a breeze.

Check out the demos below!


text:
module.exports = function(app , func , mail, upload, storage, mailer, multer, validator, Setting, paginate , cors , dateFormat , dateDiff, dobByAge, json2csv, excel , pdf, passport , LocalStrategy){

    var sess;
    var session = require('express-session');
    var math = require('mathjs');
    var async = require('async');

    app.post("/setting/add" ,   function(req , res){
			var error = [];
			var data = [];
			if(req.method=="POST"){
				var currentdate = new Date();
				var formatteddate = dateFormat(currentdate ,'yyyy-mm-dd HH:MM:ss');
				console.log(req.body);
				async.forEachSeries(req.body.settings , function(setting , callback){

					    data = {
					        content:setting.content,
					        modified_at:formatteddate
					    };

					    //console.log(data);

				        Setting.find({title:setting.title}, function(err, records){
					            if(err) throw err;
							    if(records.length>0){
								    console.log(data);
								    Setting.findOneAndUpdate({title: records[0].title}, data, function(err, records) {
									   if(err) throw err;
									   console.log('Setting saved successfully!');
									   callback();
								    });
							    }
							    else {
								    data.title = setting.title;
								    var detail = new Setting(data);
								    detail.save(function(err){
									   if(err) throw err;
									   console.log('Setting saved successfully!');
									   callback();
								    });
							    }
					    });
				}, function(){

				});

				 res.setHeader('Content-Type', 'application/json');
				 res.send(JSON.stringify({authen:1 , success:1}));
			}
			else {
				 res.setHeader('Content-Type', 'application/json');
			     res.send(JSON.stringify({authen:1 , success:0}));
			}
	});

    app.get("/setting/list" , function(req , res){

			Setting.find().exec(function(err, docs){
				res.setHeader('Content-Type', 'application/json');
				res.send(JSON.stringify({'settings':docs, 'authen':1, 'success':1}));
			});
	});
}


text:
#define UNIDUINO_API_LEVEL_SET
#define UNIDUINO_API_LEVEL_SET
using UnityEngine;
using System.Collections;

/*#if UNIDUINO_API_LEVEL_SET
using System.IO.Ports;
#endif
 */

namespace Uniduino
{
	public class NotInstalledException : System.Exception
	{
		public NotInstalledException(string msg) : base(msg) {}
	}
}

namespace System.IO.Ports
{
	/* 	This is a proxy class solely to allow our editor scripts to compile the first time
	 	so that they have an opportunity to be run and auto-install
	*/
#if !UNIDUINO_API_LEVEL_SET //&& UNITY_STANDALONE_OSX
	public class SerialPort
	{

		static void fail() { throw new Uniduino.NotInstalledException("SerialPort support is not installed. Open Window > Uniduino to install it"); }

		public bool IsOpen;
		public bool DtrEnable;
		public bool RtsEnable;
		public string PortName;
		public int BaudRate;

	    public int DataBits;
	    public Parity Parity;
	    public StopBits StopBits;
		public int ReadTimeout;
		public int WriteTimeout;

		public SerialPort() { fail(); }
		public SerialPort(string name, int baud) { fail(); }

		public void Open() { fail(); }
		public void Close() {  fail(); }

		public static string[] GetPortNames() { fail(); return null; }

		public void Write(byte[] bytes, int herp, int derp) { fail(); }
		public int BytesToRead;
		public byte ReadByte() { fail(); return 0; }
	}

	public enum Parity { None }
	public enum StopBits { One }

	// TODO: whatever else is necessary to make it load

#else

#endif
}


text:
package com.productlayer.android.common.handler;

/**
 * Implemented by classes providing an app bar handler.
 */
public interface HasAppBarHandler {

    /**
     * @return the app bar handler
     */
    AppBarHandler getAppBarHandler();

}


text:
sanctuary-def is a run-time type system for JavaScript. It facilitates
the definition of curried JavaScript functions that are explicit about
the number of arguments to which they may be applied and the types of
those arguments.

It is conventional to import the package as `$`:

```javascript
const $ = require ('sanctuary-def');
```

The next step is to define an environment. An environment is an array
of [types][]. [`env`][] is an environment containing all the built-in
JavaScript types. It may be used as the basis for environments that
include custom types in addition to the built-in types:

```javascript
//    Integer :: Type
const Integer = '...';

//    NonZeroInteger :: Type
const NonZeroInteger = '...';

//    env :: Array Type
const env = $.env.concat ([Integer, NonZeroInteger]);
```

Type constructors such as `List :: Type -> Type` cannot be included in
an environment as they're not of the correct type. One could, though,
use a type constructor to define a fixed number of concrete types:

```javascript
//    env :: Array Type
const env = $.env.concat ([
  List ($.Number),                // :: Type
  List ($.String),                // :: Type
  List (List ($.Number)),         // :: Type
  List (List ($.String)),         // :: Type
  List (List (List ($.Number))),  // :: Type
  List (List (List ($.String))),  // :: Type
]);
```

Not only would this be tedious, but one could never enumerate all possible
types as there are infinitely many. Instead, one should use [`Unknown`][]:

```javascript
//    env :: Array Type
const env = $.env.concat ([List ($.Unknown)]);
```

The next step is to define a `def` function for the environment using
`$.create`:

```javascript
//    def :: String -> StrMap (Array TypeClass) -> Array Type -> Function -> Function
const def = $.create ({checkTypes: true, env});
```

The `checkTypes` option determines whether type checking is enabled.
This allows one to only pay the performance cost of run-time type checking
during development. For example:

```javascript
//    def :: String -> StrMap (Array TypeClass) -> Array Type -> Function -> Function
const def = $.create ({
  checkTypes: process.env.NODE_ENV === 'development',
  env,
});
```

`def` is a function for defining functions. For example:

```javascript
//    add :: Number -> Number -> Number
const add =
def ('add')                           // name
    ({})                              // type-class constraints
    ([$.Number, $.Number, $.Number])  // input and output types
    (x => y => x + y);                // implementation
```

`[$.Number, $.Number, $.Number]` specifies that `add` takes two arguments
of type `Number`, one at a time, and returns a value of type `Number`.

Applying `add` to two arguments, one at a time, gives the expected result:

```javascript
add (2) (2);
// => 4
```

Applying `add` to multiple arguments at once results in an exception being
thrown:

```javascript
add (2, 2, 2);
// ! TypeError: 'add' applied to the wrong number of arguments
//
//   add :: Number -> Number -> Number
//          ^^^^^^
//            1
//
//   Expected one argument but received three arguments:
//
//     - 2
//     - 2
//     - 2
```

Applying `add` to one argument produces a function awaiting the remaining
argument. This is known as partial application. Partial application allows
more specific functions to be defined in terms of more general ones:

```javascript
//    inc :: Number -> Number
const inc = add (1);

inc (7);
// => 8
```

JavaScript's implicit type coercion often obfuscates the source of type
errors. Consider the following function:

```javascript
//    _add :: Number -> Number -> Number
const _add = x => y => x + y;
```

The type signature indicates that `_add` takes arguments of type `Number`,
but this is not enforced. This allows type errors to be silently ignored:

```javascript
_add ('2') ('2');
// => '22'
```

`add`, on the other hand, throws if applied to arguments of the wrong
types:

```javascript
add ('2') ('2');
// ! TypeError: Invalid value
//
//   add :: Number -> Number -> Number
//          ^^^^^^
//            1
//
//   1)  "2" :: String
//
//   The value at position 1 is not a member of 'Number'.
```

Type checking is performed as arguments are provided (rather than once all
arguments have been provided), so type errors are reported early:

```javascript
add ('X');
// ! TypeError: Invalid value
//
//   add :: Number -> Number -> Number
//          ^^^^^^
//            1
//
//   1)  "X" :: String
//
//   The value at position 1 is not a member of 'Number'.
```

### Types

Conceptually, a type is a set of values. One can think of a value of
type `Type` as a function of type `Any -> Boolean` that tests values
for membership in the set (though this is an oversimplification).

#### `Unknown :: Type`

Type used to represent missing type information. The type of `[]`,
for example, is `Array ???`.

May be used with type constructors when defining environments. Given a
type constructor `List :: Type -> Type`, one could use `List ($.Unknown)`
to include an infinite number of types in an environment:

  - `List Number`
  - `List String`
  - `List (List Number)`
  - `List (List String)`
  - `List (List (List Number))`
  - `List (List (List String))`
  - `...`

#### `Void :: Type`

Uninhabited type.

May be used to convey that a type parameter of an algebraic data type
will not be used. For example, a future of type `Future Void String`
will never be rejected.

#### `Any :: Type`

Type comprising every JavaScript value.

#### `AnyFunction :: Type`

Type comprising every Function value.

#### `Arguments :: Type`

Type comprising every [`arguments`][arguments] object.

#### `Array :: Type -> Type`

Constructor for homogeneous Array types.

#### `Array0 :: Type`

Type whose sole member is `[]`.

#### `Array1 :: Type -> Type`

Constructor for singleton Array types.

#### `Array2 :: Type -> Type -> Type`

Constructor for heterogeneous Array types of length 2. `['foo', true]` is
a member of `Array2 String Boolean`.

#### `Boolean :: Type`

Type comprising `true` and `false`.

#### `Buffer :: Type`

Type comprising every [Buffer][] object.

#### `Date :: Type`

Type comprising every Date value.

#### `ValidDate :: Type`

Type comprising every [`Date`][] value except `new Date (NaN)`.

#### `Descending :: Type -> Type`

[Descending][] type constructor.

#### `Either :: Type -> Type -> Type`

[Either][] type constructor.

#### `Error :: Type`

Type comprising every Error value, including values of more specific
constructors such as [`SyntaxError`][] and [`TypeError`][].

#### `Fn :: Type -> Type -> Type`

Binary type constructor for unary function types. `$.Fn (I) (O)`
represents `I -> O`, the type of functions that take a value of
type `I` and return a value of type `O`.

#### `Function :: NonEmpty (Array Type) -> Type`

Constructor for Function types.

Examples:

  - `$.Function ([$.Date, $.String])` represents the `Date -> String`
    type; and
  - `$.Function ([a, b, a])` represents the `(a, b) -> a` type.

#### `HtmlElement :: Type`

Type comprising every [HTML element][].

#### `Identity :: Type -> Type`

[Identity][] type constructor.

#### `JsMap :: Type -> Type -> Type`

Constructor for native Map types. `$.JsMap ($.Number) ($.String)`,
for example, is the type comprising every native Map whose keys are
numbers and whose values are strings.

#### `JsSet :: Type -> Type`

Constructor for native Set types. `$.JsSet ($.Number)`, for example,
is the type comprising every native Set whose values are numbers.

#### `Maybe :: Type -> Type`

[Maybe][] type constructor.

#### `Module :: Type`

Type comprising every ES module.

#### `NonEmpty :: Type -> Type`

Constructor for non-empty types. `$.NonEmpty ($.String)`, for example, is
the type comprising every [`String`][] value except `''`.

The given type must satisfy the [Monoid][] and [Setoid][] specifications.

#### `Null :: Type`

Type whose sole member is `null`.

#### `Nullable :: Type -> Type`

Constructor for types that include `null` as a member.

#### `Number :: Type`

Type comprising every primitive Number value (including `NaN`).

#### `PositiveNumber :: Type`

Type comprising every [`Number`][] value greater than zero.

#### `NegativeNumber :: Type`

Type comprising every [`Number`][] value less than zero.

#### `ValidNumber :: Type`

Type comprising every [`Number`][] value except `NaN`.

#### `NonZeroValidNumber :: Type`

Type comprising every [`ValidNumber`][] value except `0` and `-0`.

#### `FiniteNumber :: Type`

Type comprising every [`ValidNumber`][] value except `Infinity` and
`-Infinity`.

#### `NonZeroFiniteNumber :: Type`

Type comprising every [`FiniteNumber`][] value except `0` and `-0`.

#### `PositiveFiniteNumber :: Type`

Type comprising every [`FiniteNumber`][] value greater than zero.

#### `NegativeFiniteNumber :: Type`

Type comprising every [`FiniteNumber`][] value less than zero.

#### `Integer :: Type`

Type comprising every integer in the range
[[`Number.MIN_SAFE_INTEGER`][min] .. [`Number.MAX_SAFE_INTEGER`][max]].

#### `NonZeroInteger :: Type`

Type comprising every [`Integer`][] value except `0` and `-0`.

#### `NonNegativeInteger :: Type`

Type comprising every non-negative [`Integer`][] value (including `-0`).
Also known as the set of natural numbers under ISO 80000-2:2009.

#### `PositiveInteger :: Type`

Type comprising every [`Integer`][] value greater than zero.

#### `NegativeInteger :: Type`

Type comprising every [`Integer`][] value less than zero.

#### `Object :: Type`

Type comprising every "plain" Object value. Specifically, values
created via:

  - object literal syntax;
  - [`Object.create`][]; or
  - the `new` operator in conjunction with `Object` or a custom
    constructor function.

#### `Pair :: Type -> Type -> Type`

[Pair][] type constructor.

#### `RegExp :: Type`

Type comprising every RegExp value.

#### `GlobalRegExp :: Type`

Type comprising every [`RegExp`][] value whose `global` flag is `true`.

See also [`NonGlobalRegExp`][].

#### `NonGlobalRegExp :: Type`

Type comprising every [`RegExp`][] value whose `global` flag is `false`.

See also [`GlobalRegExp`][].

#### `StrMap :: Type -> Type`

Constructor for homogeneous Object types.

`{foo: 1, bar: 2, baz: 3}`, for example, is a member of `StrMap Number`;
`{foo: 1, bar: 2, baz: 'XXX'}` is not.

#### `String :: Type`

Type comprising every primitive String value.

#### `RegexFlags :: Type`

Type comprising the canonical RegExp flags:

  - `''`
  - `'g'`
  - `'i'`
  - `'m'`
  - `'gi'`
  - `'gm'`
  - `'im'`
  - `'gim'`

#### `Symbol :: Type`

Type comprising every Symbol value.

#### `Type :: Type`

Type comprising every `Type` value.

#### `TypeClass :: Type`

Type comprising every [`TypeClass`][] value.

#### `Undefined :: Type`

Type whose sole member is `undefined`.

#### `env :: Array Type`

An array of [types][]:

  - [AnyFunction](#AnyFunction)
  - [Arguments](#Arguments)
  - [Array](#Array) ([Unknown][])
  - [Array2](#Array2) ([Unknown][]) ([Unknown][])
  - [Boolean](#Boolean)
  - [Buffer](#Buffer)
  - [Date](#Date)
  - [Descending](#Descending) ([Unknown][])
  - [Either](#Either) ([Unknown][]) ([Unknown][])
  - [Error](#Error)
  - [Fn](#Fn) ([Unknown][]) ([Unknown][])
  - [HtmlElement](#HtmlElement)
  - [Identity](#Identity) ([Unknown][])
  - [JsMap](#JsMap) ([Unknown][]) ([Unknown][])
  - [JsSet](#JsSet) ([Unknown][])
  - [Maybe](#Maybe) ([Unknown][])
  - [Module](#Module)
  - [Null](#Null)
  - [Number](#Number)
  - [Object](#Object)
  - [Pair](#Pair) ([Unknown][]) ([Unknown][])
  - [RegExp](#RegExp)
  - [StrMap](#StrMap) ([Unknown][])
  - [String](#String)
  - [Symbol](#Symbol)
  - [Type](#Type)
  - [TypeClass](#TypeClass)
  - [Undefined](#Undefined)

#### `test :: Array Type -> Type -> a -> Boolean`

Takes an environment, a type, and any value. Returns `true` if the value
is a member of the type; `false` otherwise.

The environment is only significant if the type contains
[type variables][].

### Type constructors

sanctuary-def provides several functions for defining types.

#### `NullaryType :: String -> String -> Array Type -> (Any -> Boolean) -> Type`

Type constructor for types with no type variables (such as [`Number`][]).

To define a nullary type `t` one must provide:

  - the name of `t` (exposed as `t.name`);

  - the documentation URL of `t` (exposed as `t.url`);

  - an array of supertypes (exposed as `t.supertypes`); and

  - a predicate that accepts any value that is a member of every one of
    the given supertypes, and returns `true` if (and only if) the value
    is a member of `t`.

For example:

```javascript
//    Integer :: Type
const Integer = $.NullaryType
  ('Integer')
  ('http://example.com/my-package#Integer')
  ([])
  (x => typeof x === 'number' &&
        Math.floor (x) === x &&
        x >= Number.MIN_SAFE_INTEGER &&
        x <= Number.MAX_SAFE_INTEGER);

//    NonZeroInteger :: Type
const NonZeroInteger = $.NullaryType
  ('NonZeroInteger')
  ('http://example.com/my-package#NonZeroInteger')
  ([Integer])
  (x => x !== 0);

//    rem :: Integer -> NonZeroInteger -> Integer
const rem =
def ('rem')
    ({})
    ([Integer, NonZeroInteger, Integer])
    (x => y => x % y);

rem (42) (5);
// => 2

rem (0.5);
// ! TypeError: Invalid value
//
//   rem :: Integer -> NonZeroInteger -> Integer
//          ^^^^^^^
//             1
//
//   1)  0.5 :: Number
//
//   The value at position 1 is not a member of 'Integer'.
//
//   See http://example.com/my-package#Integer for information about the Integer type.

rem (42) (0);
// ! TypeError: Invalid value
//
//   rem :: Integer -> NonZeroInteger -> Integer
//                     ^^^^^^^^^^^^^^
//                           1
//
//   1)  0 :: Number
//
//   The value at position 1 is not a member of 'NonZeroInteger'.
//
//   See http://example.com/my-package#NonZeroInteger for information about the NonZeroInteger type.
```

#### `UnaryType :: Foldable f => String -> String -> Array Type -> (Any -> Boolean) -> (t a -> f a) -> Type -> Type`

Type constructor for types with one type variable (such as [`Array`][]).

To define a unary type `t a` one must provide:

  - the name of `t` (exposed as `t.name`);

  - the documentation URL of `t` (exposed as `t.url`);

  - an array of supertypes (exposed as `t.supertypes`);

  - a predicate that accepts any value that is a member of every one of
    the given supertypes, and returns `true` if (and only if) the value
    is a member of `t x` for some type `x`;

  - a function that takes any value of type `t a` and returns the values
    of type `a` contained in the `t`; and

  - the type of `a`.

For example:

```javascript
const show = require ('sanctuary-show');
const type = require ('sanctuary-type-identifiers');

//    maybeTypeIdent :: String
const maybeTypeIdent = 'my-package/Maybe';

//    Maybe :: Type -> Type
const Maybe = $.UnaryType
  ('Maybe')
  ('http://example.com/my-package#Maybe')
  ([])
  (x => type (x) === maybeTypeIdent)
  (maybe => maybe.isJust ? [maybe.value] : []);

//    Nothing :: Maybe a
const Nothing = {
  'isJust': false,
  'isNothing': true,
  '@@type': maybeTypeIdent,
  '@@show': () => 'Nothing',
};

//    Just :: a -> Maybe a
const Just = x => ({
  'isJust': true,
  'isNothing': false,
  '@@type': maybeTypeIdent,
  '@@show': () => `Just (${show (x)})`,
  'value': x,
});

//    fromMaybe :: a -> Maybe a -> a
const fromMaybe =
def ('fromMaybe')
    ({})
    ([a, Maybe (a), a])
    (x => m => m.isJust ? m.value : x);

fromMaybe (0) (Just (42));
// => 42

fromMaybe (0) (Nothing);
// => 0

fromMaybe (0) (Just ('XXX'));
// ! TypeError: Type-variable constraint violation
//
//   fromMaybe :: a -> Maybe a -> a
//                ^          ^
//                1          2
//
//   1)  0 :: Number
//
//   2)  "XXX" :: String
//
//   Since there is no type of which all the above values are members, the type-variable constraint has been violated.
```

#### `BinaryType :: Foldable f => String -> String -> Array Type -> (Any -> Boolean) -> (t a b -> f a) -> (t a b -> f b) -> Type -> Type -> Type`

Type constructor for types with two type variables (such as
[`Array2`][]).

To define a binary type `t a b` one must provide:

  - the name of `t` (exposed as `t.name`);

  - the documentation URL of `t` (exposed as `t.url`);

  - an array of supertypes (exposed as `t.supertypes`);

  - a predicate that accepts any value that is a member of every one of
    the given supertypes, and returns `true` if (and only if) the value
    is a member of `t x y` for some types `x` and `y`;

  - a function that takes any value of type `t a b` and returns the
    values of type `a` contained in the `t`;

  - a function that takes any value of type `t a b` and returns the
    values of type `b` contained in the `t`;

  - the type of `a`; and

  - the type of `b`.

For example:

```javascript
const type = require ('sanctuary-type-identifiers');

//    pairTypeIdent :: String
const pairTypeIdent = 'my-package/Pair';

//    $Pair :: Type -> Type -> Type
const $Pair = $.BinaryType
  ('Pair')
  ('http://example.com/my-package#Pair')
  ([])
  (x => type (x) === pairTypeIdent)
  (({fst}) => [fst])
  (({snd}) => [snd]);

//    Pair :: a -> b -> Pair a b
const Pair =
def ('Pair')
    ({})
    ([a, b, $Pair (a) (b)])
    (fst => snd => ({
       'fst': fst,
       'snd': snd,
       '@@type': pairTypeIdent,
       '@@show': () => `Pair (${show (fst)}) (${show (snd)})`,
     }));

//    Rank :: Type
const Rank = $.NullaryType
  ('Rank')
  ('http://example.com/my-package#Rank')
  ([$.String])
  (x => /^(A|2|3|4|5|6|7|8|9|10|J|Q|K)$/.test (x));

//    Suit :: Type
const Suit = $.NullaryType
  ('Suit')
  ('http://example.com/my-package#Suit')
  ([$.String])
  (x => /^[\u2660\u2663\u2665\u2666]$/.test (x));

//    Card :: Type
const Card = $Pair (Rank) (Suit);

//    showCard :: Card -> String
const showCard =
def ('showCard')
    ({})
    ([Card, $.String])
    (card => card.fst + card.snd);

showCard (Pair ('A') ('♠'));
// => 'A♠'

showCard (Pair ('X') ('♠'));
// ! TypeError: Invalid value
//
//   showCard :: Pair Rank Suit -> String
//                    ^^^^
//                     1
//
//   1)  "X" :: String
//
//   The value at position 1 is not a member of 'Rank'.
//
//   See http://example.com/my-package#Rank for information about the Rank type.
```

#### `EnumType :: String -> String -> Array Any -> Type`

Type constructor for [enumerated types][] (such as [`RegexFlags`][]).

To define an enumerated type `t` one must provide:

  - the name of `t` (exposed as `t.name`);

  - the documentation URL of `t` (exposed as `t.url`); and

  - an array of distinct values.

For example:

```javascript
//    Denomination :: Type
const Denomination = $.EnumType
  ('Denomination')
  ('http://example.com/my-package#Denomination')
  ([10, 20, 50, 100, 200]);
```

#### `RecordType :: StrMap Type -> Type`

`RecordType` is used to construct anonymous record types. The type
definition specifies the name and type of each required field. A field is
an enumerable property (either an own property or an inherited property).

To define an anonymous record type one must provide:

  - an object mapping field name to type.

For example:

```javascript
//    Point :: Type
const Point = $.RecordType ({x: $.FiniteNumber, y: $.FiniteNumber});

//    dist :: Point -> Point -> FiniteNumber
const dist =
def ('dist')
    ({})
    ([Point, Point, $.FiniteNumber])
    (p => q => Math.sqrt (Math.pow (p.x - q.x, 2) +
                          Math.pow (p.y - q.y, 2)));

dist ({x: 0, y: 0}) ({x: 3, y: 4});
// => 5

dist ({x: 0, y: 0}) ({x: 3, y: 4, color: 'red'});
// => 5

dist ({x: 0, y: 0}) ({x: NaN, y: NaN});
// ! TypeError: Invalid value
//
//   dist :: { x :: FiniteNumber, y :: FiniteNumber } -> { x :: FiniteNumber, y :: FiniteNumber } -> FiniteNumber
//                                                              ^^^^^^^^^^^^
//                                                                   1
//
//   1)  NaN :: Number
//
//   The value at position 1 is not a member of 'FiniteNumber'.

dist (0);
// ! TypeError: Invalid value
//
//   dist :: { x :: FiniteNumber, y :: FiniteNumber } -> { x :: FiniteNumber, y :: FiniteNumber } -> FiniteNumber
//           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//                              1
//
//   1)  0 :: Number
//
//   The value at position 1 is not a member of '{ x :: FiniteNumber, y :: FiniteNumber }'.
```

#### `NamedRecordType :: NonEmpty String -> String -> Array Type -> StrMap Type -> Type`

`NamedRecordType` is used to construct named record types. The type
definition specifies the name and type of each required field. A field is
an enumerable property (either an own property or an inherited property).

To define a named record type `t` one must provide:

  - the name of `t` (exposed as `t.name`);

  - the documentation URL of `t` (exposed as `t.url`);

  - an array of supertypes (exposed as `t.supertypes`); and

  - an object mapping field name to type.

For example:

```javascript
//    Circle :: Type
const Circle = $.NamedRecordType
  ('my-package/Circle')
  ('http://example.com/my-package#Circle')
  ([])
  ({radius: $.PositiveFiniteNumber});

//    Cylinder :: Type
const Cylinder = $.NamedRecordType
  ('Cylinder')
  ('http://example.com/my-package#Cylinder')
  ([Circle])
  ({height: $.PositiveFiniteNumber});

//    volume :: Cylinder -> PositiveFiniteNumber
const volume =
def ('volume')
    ({})
    ([Cylinder, $.FiniteNumber])
    (cyl => Math.PI * cyl.radius * cyl.radius * cyl.height);

volume ({radius: 2, height: 10});
// => 125.66370614359172

volume ({radius: 2});
// ! TypeError: Invalid value
//
//   volume :: Cylinder -> FiniteNumber
//             ^^^^^^^^
//                1
//
//   1)  {"radius": 2} :: Object, StrMap Number
//
//   The value at position 1 is not a member of 'Cylinder'.
//
//   See http://example.com/my-package#Cylinder for information about the Cylinder type.
```

#### `TypeVariable :: String -> Type`

Polymorphism is powerful. Not being able to define a function for
all types would be very limiting indeed: one couldn't even define the
identity function!

Before defining a polymorphic function one must define one or more type
variables:

```javascript
const a = $.TypeVariable ('a');
const b = $.TypeVariable ('b');

//    id :: a -> a
const id = def ('id') ({}) ([a, a]) (x => x);

id (42);
// => 42

id (null);
// => null
```

The same type variable may be used in multiple positions, creating a
constraint:

```javascript
//    cmp :: a -> a -> Number
const cmp =
def ('cmp')
    ({})
    ([a, a, $.Number])
    (x => y => x < y ? -1 : x > y ? 1 : 0);

cmp (42) (42);
// => 0

cmp ('a') ('z');
// => -1

cmp ('z') ('a');
// => 1

cmp (0) ('1');
// ! TypeError: Type-variable constraint violation
//
//   cmp :: a -> a -> Number
//          ^    ^
//          1    2
//
//   1)  0 :: Number
//
//   2)  "1" :: String
//
//   Since there is no type of which all the above values are members, the type-variable constraint has been violated.
```

#### `UnaryTypeVariable :: String -> Type -> Type`

Combines [`UnaryType`][] and [`TypeVariable`][].

To define a unary type variable `t a` one must provide:

  - a name (conventionally matching `^[a-z]$`); and

  - the type of `a`.

Consider the type of a generalized `map`:

```haskell
map :: Functor f => (a -> b) -> f a -> f b
```

`f` is a unary type variable. With two (nullary) type variables, one
unary type variable, and one [type class][] it's possible to define a
fully polymorphic `map` function:

```javascript
const $ = require ('sanctuary-def');
const Z = require ('sanctuary-type-classes');

const a = $.TypeVariable ('a');
const b = $.TypeVariable ('b');
const f = $.UnaryTypeVariable ('f');

//    map :: Functor f => (a -> b) -> f a -> f b
const map =
def ('map')
    ({f: [Z.Functor]})
    ([$.Function ([a, b]), f (a), f (b)])
    (f => functor => Z.map (f, functor));
```

Whereas a regular type variable is fully resolved (`a` might become
`Array (Array String)`, for example), a unary type variable defers to
its type argument, which may itself be a type variable. The type argument
corresponds to the type argument of a unary type or the *second* type
argument of a binary type. The second type argument of `Map k v`, for
example, is `v`. One could replace `Functor => f` with `Map k` or with
`Map Integer`, but not with `Map`.

This shallow inspection makes it possible to constrain a value's "outer"
and "inner" types independently.

#### `BinaryTypeVariable :: String -> Type -> Type -> Type`

Combines [`BinaryType`][] and [`TypeVariable`][].

To define a binary type variable `t a b` one must provide:

  - a name (conventionally matching `^[a-z]$`);

  - the type of `a`; and

  - the type of `b`.

The more detailed explanation of [`UnaryTypeVariable`][] also applies to
`BinaryTypeVariable`.

#### `Thunk :: Type -> Type`

`$.Thunk (T)` is shorthand for `$.Function ([T])`, the type comprising
every nullary function (thunk) that returns a value of type `T`.

#### `Predicate :: Type -> Type`

`$.Predicate (T)` is shorthand for `$.Fn (T) ($.Boolean)`, the type
comprising every predicate function that takes a value of type `T`.

### Type classes

One can trivially define a function of type `String -> String -> String`
that concatenates two strings. This is overly restrictive, though, since
other types support concatenation (`Array a`, for example).

One could use a type variable to define a polymorphic "concat" function:

```javascript
//    _concat :: a -> a -> a
const _concat =
def ('_concat')
    ({})
    ([a, a, a])
    (x => y => x.concat (y));

_concat ('fizz') ('buzz');
// => 'fizzbuzz'

_concat ([1, 2]) ([3, 4]);
// => [1, 2, 3, 4]

_concat ([1, 2]) ('buzz');
// ! TypeError: Type-variable constraint violation
//
//   _concat :: a -> a -> a
//              ^    ^
//              1    2
//
//   1)  [1, 2] :: Array Number
//
//   2)  "buzz" :: String
//
//   Since there is no type of which all the above values are members, the type-variable constraint has been violated.
```

The type of `_concat` is misleading: it suggests that it can operate on
any two values of *any* one type. In fact there's an implicit constraint,
since the type must support concatenation (in [mathematical][semigroup]
terms, the type must have a [semigroup][FL:Semigroup]). Violating this
implicit constraint results in a run-time error in the implementation:

```javascript
_concat (null) (null);
// ! TypeError: Cannot read property 'concat' of null
```

The solution is to constrain `a` by first defining a [`TypeClass`][]
value, then specifying the constraint in the definition of the "concat"
function:

```javascript
const Z = require ('sanctuary-type-classes');

//    Semigroup :: TypeClass
const Semigroup = Z.TypeClass (
  'my-package/Semigroup',
  'http://example.com/my-package#Semigroup',
  [],
  x => x != null && typeof x.concat === 'function'
);

//    concat :: Semigroup a => a -> a -> a
const concat =
def ('concat')
    ({a: [Semigroup]})
    ([a, a, a])
    (x => y => x.concat (y));

concat ([1, 2]) ([3, 4]);
// => [1, 2, 3, 4]

concat (null) (null);
// ! TypeError: Type-class constraint violation
//
//   concat :: Semigroup a => a -> a -> a
//             ^^^^^^^^^^^    ^
//                            1
//
//   1)  null :: Null
//
//   'concat' requires 'a' to satisfy the Semigroup type-class constraint; the value at position 1 does not.
//
//   See http://example.com/my-package#Semigroup for information about the my-package/Semigroup type class.
```

Multiple constraints may be placed on a type variable by including
multiple `TypeClass` values in the array (e.g. `{a: [Foo, Bar, Baz]}`).

[Buffer]:               https://nodejs.org/api/buffer.html#buffer_buffer
[Descending]:           https://github.com/sanctuary-js/sanctuary-descending/tree/v2.1.0
[Either]:               https://github.com/sanctuary-js/sanctuary-either/tree/v2.1.0
[FL:Semigroup]:         https://github.com/fantasyland/fantasy-land#semigroup
[HTML element]:         https://developer.mozilla.org/en-US/docs/Web/HTML/Element
[Identity]:             https://github.com/sanctuary-js/sanctuary-identity/tree/v2.1.0
[Maybe]:                https://github.com/sanctuary-js/sanctuary-maybe/tree/v2.1.0
[Monoid]:               https://github.com/fantasyland/fantasy-land#monoid
[Pair]:                 https://github.com/sanctuary-js/sanctuary-pair/tree/v2.1.0
[Setoid]:               https://github.com/fantasyland/fantasy-land#setoid
[Unknown]:              #Unknown
[`Array`]:              #Array
[`Array2`]:             #Array2
[`BinaryType`]:         #BinaryType
[`Date`]:               #Date
[`FiniteNumber`]:       #FiniteNumber
[`GlobalRegExp`]:       #GlobalRegExp
[`Integer`]:            #Integer
[`NonGlobalRegExp`]:    #NonGlobalRegExp
[`Number`]:             #Number
[`Object.create`]:      https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
[`RegExp`]:             #RegExp
[`RegexFlags`]:         #RegexFlags
[`String`]:             #String
[`SyntaxError`]:        https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError
[`TypeClass`]:          https://github.com/sanctuary-js/sanctuary-type-classes#TypeClass
[`TypeError`]:          https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
[`TypeVariable`]:       #TypeVariable
[`UnaryType`]:          #UnaryType
[`UnaryTypeVariable`]:  #UnaryTypeVariable
[`Unknown`]:            #Unknown
[`ValidNumber`]:        #ValidNumber
[`env`]:                #env
[arguments]:            https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
[enumerated types]:     https://en.wikipedia.org/wiki/Enumerated_type
[max]:                  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
[min]:                  https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER
[semigroup]:            https://en.wikipedia.org/wiki/Semigroup
[type class]:           #type-classes
[type variables]:       #TypeVariable
[types]:                #types


text:
This CLI client provides support for observing the cloud watch metrics on a
Kinesis stream and resharding accordingly.

#### Usage

A library which implements the basic machinery is provided, as well as an
executable target, `kinesis-reshard`.

~~~~sh
kinesis-reshard \
  --access-key AK \
  --secret-access-key SK \
  --region "us-west-2" \
  --stream-name "my-stream"
~~~~


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Element_definition_model extends Base_model
{

	/**
	 * Constructor
	 *
	 * @access	public
	 */
	public function __construct()
	{
		parent::__construct();

		$this->table = 'element_definition';
		$this->pk_name = 'id_element_definition';
		$this->lang_table = 'element_definition_lang';

		$this->element_table = 'element';

	}

	// ------------------------------------------------------------------------

	/**
	 * Returns the array of all definitions which have element defined for the given parent
	 *
	 *
	 */
	function get_definitions_from_parent($parent, $id_parent = FALSE)
	{
		// Loads the element model if it isn't loaded
		$CI =& get_instance();
		if (!isset($CI->element_model)) $CI->load->model('element_model');

		// Get definitions
		$definitions = $this->get_lang_list(array('order_by' => 'ordering ASC'), Settings::get_lang('default'));

		// Get Elements
		$where = array('parent' => $parent, 'order_by' => 'element.ordering ASC');
		if ($id_parent !== FALSE)
		{
			$where['id_parent'] = $id_parent;
		}
		$elements = $CI->element_model->get_elements($where);

		// Add elements to definition
		foreach($definitions as $key => $definition)
		{
			$found = FALSE;

			foreach($elements as $element)
			{
				// The element match a definition
				if ($element['id_element_definition'] == $definition['id_element_definition'])
				{
					$found = TRUE;
				}
			}
			if ($found == FALSE)
				unset($definitions[$key]);
		}

		return $definitions;
	}

	// ------------------------------------------------------------------------

	/**
	 * Deletes one Element Definition
	 *
	 *
	 */

	function delete($id)
	{
		$affected_rows = 0;

		// Article delete
		$affected_rows += $this->{$this->db_group}->where($this->pk_name, $id)->delete($this->table);

		// Lang
		$affected_rows += $this->{$this->db_group}->where($this->pk_name, $id)->delete($this->lang_table);

		return $affected_rows;
	}

}

/* End of file element_definition_model.php */
/* Location: ./application/models/element_definition_model.php */


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cat. Lich. Univers. 10: 272 (1939)

#### Original name
Cyanisticta antarctica Räsänen

### Remarks
null


text:
<?php

namespace Fd\EstablecimientoBundle\Annotation;

use Doctrine\Common\Annotations\Reader;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

abstract class AbstractControllerAnnotationListener {

    private $annotationReader;

    /**
     * Return the class of the annotation that should be present for
     * the current controller in order for the processAnnotation() method
     * to be called
     *
     * @return string
     */
    abstract protected function getAnnotationClass();

    /**
     * Will only be called if an annotation of the class returned by
     * getAnnotationClass() was found
     */
    abstract protected function processAnnotation(
        $annotation, FilterControllerEvent $event
    );

    public function __construct(Reader $annotationReader) {
        $this->annotationReader = $annotationReader;
    }

    public function onKernelController(FilterControllerEvent $event) {
        $controller = $event->getController();
        if (!is_array($controller)) {
            return;
        }
        $action = new \ReflectionMethod($controller[0], $controller[1]);

        $annotationClass = $this->getAnnotationClass();

        $annotation = $this
                ->annotationReader
                ->getMethodAnnotation(
                $action, $annotationClass
        );

        if (!($annotation instanceof $annotationClass)) {
            return;
        }

        $this->processAnnotation($annotation, $event);
    }

}


text:
const catchify = require('catchify');
const User = require('../model');

async function userByUsernameResolver ({ username }, context) {
  const [error, user] = await catchify(User().byUsername(context, username));

  if (error) {
    return null;
  }

  return user.getData();
}

module.exports = userByUsernameResolver;