text:
export const StringUtils = {
  startsWith: (str: string, searchStrings: string[]): boolean => {
    for (let i = 0; i < searchStrings.length; i++) {
      const searchString = searchStrings[i];
      if (str.startsWith(searchString)) {
        return true;
      }
    }
    return false;
  },
  hash: (str: string): number => {
    let hash: number = 0;
    if (str.length === 0) return hash;

    for (let i = 0; i < str.length; i++) {
      const char: number = str.charCodeAt(i);
      hash = ((hash << 5) - hash) + char;
      hash = hash & hash;
    }
    return hash;
  }
};


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

<TITLE>
SpaceResolver.SpaceHandlingBreakPosition (Apache FOP 2.1 API)
</TITLE>

<META NAME="date" CONTENT="2016-01-07">

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

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.fop.layoutmgr

Class SpaceResolver.SpaceHandlingBreakPosition

java.lang.Object
  org.apache.fop.layoutmgr.Position
      org.apache.fop.layoutmgr.SpaceResolver.SpaceHandlingBreakPosition

Enclosing class:
SpaceResolver

public static class SpaceResolver.SpaceHandlingBreakPosition
extends Position

Position class for break possibilities. It is used to notify layout manager about the
 effective spaces and conditional lengths.

Constructor Summary

SpaceResolver.SpaceHandlingBreakPosition(SpaceResolver resolver,
                                         BreakElement breakPoss)

          Main constructor.

Method Summary

 Position
getOriginalBreakPosition()

 Position
getPosition()

          Overridden by NonLeafPosition to return the Position of its child LM.

 SpaceResolver
getSpaceResolver()

 void
notifyBreakSituation(boolean isBreakSituation,
                     RelSide side)

          Notifies all affected layout managers about the current situation in the part to be
 handled for area generation.

 java.lang.String
toString()

Methods inherited from class org.apache.fop.layoutmgr.Position

generatesAreas, getIndex, getLM, getLM, getPosition, getShortLMName, setIndex

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Constructor Detail

SpaceResolver.SpaceHandlingBreakPosition

public SpaceResolver.SpaceHandlingBreakPosition(SpaceResolver resolver,
                                                BreakElement breakPoss)

Main constructor.

Parameters:
resolver - the space resolver that provides the info about the actual situation
breakPoss - the original break possibility that creates this Position

Method Detail

getSpaceResolver

public SpaceResolver getSpaceResolver()

Returns:
the space resolver

notifyBreakSituation

public void notifyBreakSituation(boolean isBreakSituation,
                                 RelSide side)

Notifies all affected layout managers about the current situation in the part to be
 handled for area generation.

Parameters:
isBreakSituation - true if this is a break situation.
side - defines to notify about the situation whether before or after the break.
             May be null if isBreakSituation is null.

toString

public java.lang.String toString()

Overrides:
toString in class Position

getOriginalBreakPosition

public Position getOriginalBreakPosition()

Returns:
the original Position instance set at the BreakElement that this Position was
         created for.

getPosition

public Position getPosition()

Overridden by NonLeafPosition to return the Position of its child LM.

Overrides:
getPosition in class Position

Returns:
a position or null

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

fop 2.1

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright 1999-2016 The Apache Software Foundation. All Rights Reserved.

redpajama_set_name: RedPajamaGithub


text:
import os
import logging
import cv2
import numpy as np
from .image import ImageProcessor
from .pipeline import Pipeline
from .douglaspeucker import reduce_pointset
from mesher.voxel import Point

class Camera:
    def __init__(self, port, shape, position, viewAngle, save, processDirectory=None):
        """ Create a new Camera object
        port      = path to the camera
        shape     = (W,H), camera shape Width x Heigth
        position  = [X, Y, Z], camera position
        rotation  = [Rx, Ry, Rz], rotation order (Y->X'->Z")
        viewAngle = <angle>, view angle in degree
        save      = tuple (path where save pictures, extension) or None
        processDirectory = path to the directory of pictures to process (when don't use the scanner)
        """

        logging.debug("Create Camera %s (%.2f, %.2f) @ %s, viewAngle = %.2f" %(port, shape[0], shape[1], position, viewAngle))

        self.camId     = int(port[-1])
        self.shape     = shape
        self.position  = np.array(position, dtype=np.float32)
        self.distance  = float(shape[0]/2)/np.tan(np.radians(viewAngle)/2)
        self.rotation  = None
        self.save      = save
        self.processDirectory = processDirectory
        self.buffered  = ("", None)
        self.rotationMatrix = np.matrix(np.eye(3))

        if(self.processDirectory == None):
            cam = cv2.VideoCapture(self.camId)
            cam.read()
            cam.release()

    def calibrate(self, turnTable, (x,y)):
        ''' Compute Camera rotation from expected and observed turnTable (x,y) center
            Rotation around the Z-axis is not supported
        '''
        # Unit vector pointing to the original turntable center
        origUnitVect = turnTable.position - self.position
        origUnitVect /= np.linalg.norm(origUnitVect)

        # Unit vector pointing to the current turntable center
        currentUnitVect = np.array([x,y,self.distance], dtype=float)
        currentUnitVect /= np.linalg.norm(currentUnitVect)

        Yzx = self.getAngle(
            currentUnitVect[0], # x"
            origUnitVect[0],    # x
            -origUnitVect[2])   # -z
        logging.debug('Yzx = %5.2f' % np.degrees(Yzx))

        Xyz = self.getAngle(
            currentUnitVect[1], # y"
            origUnitVect[1],    # y
            -origUnitVect[0]*np.sin(Yzx)-origUnitVect[2]*np.cos(Yzx)) # x*sin(Yzx)+z*cos(Yzx)
        logging.debug('Xyz = %5.2f' % np.degrees(Xyz))

        # Rotate first around Y/vertical axis, then X/horizontal axis
        self.rotationMatrix = np.matrix([[ np.cos(Yzx),             0,           -np.sin(Yzx)            ],
                                         [-np.sin(Xyz)*np.sin(Yzx), np.cos(Yzx), -np.sin(Xyz)*np.cos(Yzx)],
                                         [ np.cos(Xyz)*np.sin(Yzx), np.sin(Xyz),  np.cos(Xyz)*np.cos(Yzx)]])

    def getAngle(self, a, b, c):
        ''' Solve a = b*cos(angle)+c*sin(angle) equation with angle [-pi/2:pi/2]
        '''
        # Above equation is equivalent to:
        #     a/norm([b,c]) = cos(u)*cos(angle)+ sin(u)*sin(angle)
        u = np.arcsin(c/np.linalg.norm((b,c)))
        # or  a/norm([b,c]) = cos(u-angle)
        # or  angle = u - acos(a/norm([b,c])
        angle = u-np.arccos(a/np.linalg.norm((b,c)))
        return ((angle + np.pi/2) % np.pi) - np.pi/2

    def getPicture(self, name, toBuffer=False):
        picture = None
        if(self.processDirectory == None):
            logging.info('Taking a picture')

            if(self.buffered[0] == name):
                picture = self.buffered[1]
            else:
                cam = cv2.VideoCapture(self.camId)
                cam.set(3, self.shape[0])
                cam.set(4, self.shape[1])
                ok, picture = cam.read()
                cam.release()
                if not ok:
                    logging.error("impossible to get a picture from the camera..")
                elif(len(self.save[0]) > 0):
                    cv2.imwrite(os.path.join(self.save[0],name+self.save[1]), picture)

                if(toBuffer):
                    self.buffered = (name, np.copy(picture))
        else:
            logging.info('Reading a picture')
            picture = cv2.imread(os.path.join(self.processDirectory, name+self.save[1]))

        return picture

class Scene:
    def __init__(self, name, camera, laser, turnTable):
        """ Create a new scene object
        name   = the name of the scene for pictures names
        camera = the camera object of the scene
        laser  = the laser object of the scene (only on by scene)
        table  = the turntable object of the scene
        """
        self.name       = name
        self.camera     = camera
        self.laser      = laser
        self.turnTable  = turnTable
        self.imageProcessor = ImageProcessor()
        self.pipeline   = Pipeline(self.getWorldPoint)
        self.result = []

    def __iter__(self):
        if(len(self.result) != 0):
            for item in self.result:
                yield item
        else:
            item = self.pipeline.get()
            while(item != None):
                self.result += item
                yield item
                item = self.pipeline.get()

    def calibrateBackground(self):
        self.laser.switch(True)
        imgLaserOn = self.camera.getPicture("calibration_"+self.name)
        self.laser.switch(False)
        imgLaserOff = self.camera.getPicture("calibration_off", True)

        return self.imageProcessor.setCalibrationMask(imgLaserOn, imgLaserOff)

    def calibrateLaser(self, (x,y), m):
        ''' Compute Laser position and angle from the slope of the laser line on the
            screen and turntable position. This method should be executed after Camera
            calibration to make sure that its rotation matrix is correctly set.
            turnTable = turntable object
            (x,y)     = position of the turntable center (laser line should intersect it)
            m         = slope of the laser line (y=mx+p) on the screen
        '''

        # Define a plane based on the laser line on the screen ...
        laserLineVect = np.array([1, m, 0], dtype=float)
        # ... and the ray pointing to the turntable center (laser line should intersect it)
        turnTableVect = np.array([x,y,self.camera.distance], dtype=float)
        # A plane is described by the following equation a*x+b*y+c*z+d=0
        # (a,b,c) is the cross product of the two director vectors define above
        abcVect = np.cross(laserLineVect, turnTableVect)
        # Rotate vector in world reference as they were defined in Camera reference
        abcVect = (self.camera.rotationMatrix * np.matrix(abcVect).T).A1
        # d is defined by forcing the plane to pass by the camera position
        d       = -np.dot(abcVect, self.camera.position)
        # Intersection of that plane with the Xaxis (a*x+b*turnTable.y+c*0+d=0) is the laser position
        laserX     = -(d+abcVect[1]*self.turnTable.position[1])/abcVect[0]
        # Compute laser angle in (radian) assuming it intersects the turntable center
        laserAngle = np.arctan(laserX/self.turnTable.position[2])

        self.laser.calibrate(np.array([laserX, self.camera.position[1], 0.0], dtype=np.float32), laserAngle)

    def getWorldPoint(self, imgLaserOn, imgLaserOff, step):
        # Intersection of a line and a plane
        # line  : OP = camera.position + lambda * CP
        # plane : OP = laser.position  + alpha * v1  + beta * v2
        #
        # Solve camera.position - laser.position = -lambda * CP + alpha * v1 + beta * v2

        cameraPoints = self.imageProcessor.extractPoints(imgLaserOn, imgLaserOff)

        worldPoints = []
        maxRadius = (self.turnTable.diameter/2)**2

        rotMatrix = self.turnTable.getRotationMatrix(step)

        for pixel in cameraPoints:
            pixel2D = tuple(map(int, pixel))

            # Move zero to image center
            pixel[0]=  pixel[0] - self.camera.shape[0]/2.0
            pixel[1]= -pixel[1] + self.camera.shape[1]/2.0
            # Camera-Ray (CP) vector in camera reference
            CP = np.matrix([pixel[0], pixel[1], self.camera.distance])
            # Rotate Ray in world reference
            CP = self.camera.rotationMatrix * CP.T

            # Create system matrix
            systemMatrix = np.matrix([-CP.A1,self.laser.v1,self.laser.v2]).T
            # Inverse system and get solution (can be optimized by only calculate lambda)
            solution = systemMatrix.I * np.matrix(self.camera.position - self.laser.position).T

            point = self.camera.position + solution.A1[0] * CP.T

            # Normal is laser-point translated in turntable system
            normal = rotMatrix * (self.laser.position - point).T

            # Translate P into turntable reference units and rotate it
            point = rotMatrix * (point - self.turnTable.position).T

            p = Point()

            # Conserve only points on the table
            if point[1] > 0.5 and (point[0]**2 + point[2]**2) < maxRadius:
                x, z, y = np.array(point.T)[0]
                nx, ny, nz = np.array(normal.T)[0]
                # TODO: verify color channels order and indexes order
                b, g, r = imgLaserOff[pixel2D[1]][pixel2D[0]]
                worldPoints.append(Point(
                    x=x, y=y, z=z,
                    r=r, g=g, b=b,
                    nx=nx, ny=ny, nz=nz
                ))
                #logging.debug("%s -> %s" % (str(pixel),str(point.T)))

        return reduce_pointset(worldPoints, 2)

    def runStep(self, step, isLastStep):
        if(step == 0):
            self.pipeline.start()

        name = ("%d_%s" %(step, self.name))
        self.laser.switch(True)
        imgLaserOn = self.camera.getPicture(name, False)

        name = ("%d_%s" %(step, "off"))
        self.laser.switch(False)
        imgLaserOff = self.camera.getPicture(name, True)

        self.pipeline.feed((imgLaserOn, imgLaserOff, step))
        if(isLastStep):
            self.pipeline.terminate()


text:
package org.drools.persistence;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TransactionSynchronizationContainer implements TransactionSynchronization {

    private static Logger logger = LoggerFactory.getLogger( TransactionSynchronizationContainer.class );
    public static final String RESOURCE_KEY = "org.drools.persistence.txsync.container";

    private Set<TransactionSynchronization> synchronizations = new TreeSet<TransactionSynchronization>();

    @Override
    public void beforeCompletion() {
        TransactionSynchronization[] txSyncArray = synchronizations.toArray(new TransactionSynchronization[synchronizations.size()]);

        for (TransactionSynchronization txSync : txSyncArray) {

            txSync.beforeCompletion();
        }
    }

    @Override
    public void afterCompletion(int status) {
        TransactionSynchronization[] txSyncArray = synchronizations.toArray(new TransactionSynchronization[synchronizations.size()]);

        for (TransactionSynchronization txSync : txSyncArray) {

            txSync.afterCompletion(status);
        }
    }

    public void addTransactionSynchronization(TransactionSynchronization txSync) {

        this.synchronizations.add(txSync);
        logger.debug("Adding sync {} total syncs ", txSync, synchronizations.size());
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>KGE: KGE::ClassFactoryXML1Arg< root_t, arg0_t > Class Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

KGE
    0

The KGE Project

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

 All Classes Functions Enumerations

KGE

ClassFactoryXML1Arg

Public Types |
Public Member Functions |
Static Public Member Functions |
Protected Types |
Protected Attributes |
List of all members

KGE::ClassFactoryXML1Arg< root_t, arg0_t > Class Template Reference

Public Types

typedef

CreateFunctorXML1ArgBase

< root_t, arg0_t > 	Functor

Public Member Functions

void 	Register (const Hash &xHash, Functor *pxCreateFunctor)

root_t * 	Create (xml_node< char > &xNode, arg0_t xArg0)

Static Public Member Functions

static ClassFactoryXML1Arg & 	Get ()

Protected Types

typedef unordered_map< Hash,

Functor *, Hash::Hasher > 	FunctorCollection

typedef pair< Hash, Functor * > 	FunctorPair

Protected Attributes

FunctorCollection 	m_xCreateFunctors

The documentation for this class was generated from the following file:

C:/Users/Vit/Documents/GitHub/KGE/KGE/Core/ClassCapabilities/ClassFactory.hpp

<address class="footer">
Generated on Thu Apr 10 2014 21:46:03 for KGE by

 1.8.6
</address>


text:
const { expect } = require('chai');
const nock = require('nock');

const API_URL = 'https://tenant.auth0.com';

const OrganizationsManager = require(`../../src/management/OrganizationsManager`);
const { ArgumentError } = require('rest-facade');

describe('OrganizationsManager', () => {
  /**
   * @type {OrganizationsManager}
   */
  let organizations;

  /**
   * @type {string}
   */
  let token;

  before(() => {
    token = 'TOKEN';
    organizations = new OrganizationsManager({
      headers: { authorization: `Bearer ${token}` },
      baseUrl: API_URL,
    });
  });

  describe('instance', () => {
    const methods = [
      'getByID',
      'getByName',
      'getAll',
      'create',
      'update',
      'delete',
      'getEnabledConnections',
      'getEnabledConnection',
      'addEnabledConnection',
      'updateEnabledConnection',
      'removeEnabledConnection',
      'getMembers',
      'addMembers',
      'removeMembers',
      'getMemberRoles',
      'addMemberRoles',
      'removeMemberRoles',
      'getInvitations',
      'getInvitation',
      'createInvitation',
      'deleteInvitation',
    ];

    methods.forEach((method) => {
      it(`should have a ${method} method`, () => {
        expect(organizations[method]).to.exist.to.be.an.instanceOf(Function);
      });
    });
  });

  describe('#constructor', () => {
    it('should error when no options are provided', () => {
      expect(() => {
        new OrganizationsManager();
      }).to.throw(ArgumentError, 'Must provide manager options');
    });

    it('should throw an error when no base URL is provided', () => {
      expect(() => {
        new OrganizationsManager({});
      }).to.throw(ArgumentError, 'Must provide a base URL for the API');
    });

    it('should throw an error when the base URL is invalid', () => {
      expect(() => {
        new OrganizationsManager({ baseUrl: '' });
      }).to.throw(ArgumentError, 'The provided base URL is invalid');
    });
  });

  describe('#getAll', () => {
    beforeEach(function () {
      this.request = nock(API_URL).get('/organizations').reply(200);
    });

    it('should accept a callback', (done) => {
      organizations.getAll(() => {
        done();
      });
    });

    it('should return a promise if no callback is given', (done) => {
      organizations.getAll().then(done.bind(null, null)).catch(done.bind(null, null));
    });

    it('should pass any errors to the promise catch handler', (done) => {
      nock.cleanAll();

      nock(API_URL).get('/organizations').reply(500);

      organizations.getAll().catch((err) => {
        expect(err).to.exist;
        done();
      });
    });

    it('should pass the body of the response to the "then" handler', (done) => {
      nock.cleanAll();

      const data = [{ test: true }];
      nock(API_URL).get('/organizations').reply(200, data);

      organizations.getAll().then((credentials) => {
        expect(credentials).to.be.an.instanceOf(Array);

        expect(credentials.length).to.equal(data.length);

        expect(credentials[0].test).to.equal(data[0].test);

        done();
      });
    });

    it('should perform a GET request to /api/v2/organizations', function (done) {
      const { request } = this;

      organizations.getAll().then(() => {
        expect(request.isDone()).to.be.true;
        done();
      });
    });

    it('should include the token in the Authorization header', (done) => {
      nock.cleanAll();

      const request = nock(API_URL)
        .get('/organizations')
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.getAll().then(() => {
        expect(request.isDone()).to.be.true;
        done();
      });
    });

    it('should pass the parameters in the query-string', (done) => {
      nock.cleanAll();

      const params = {
        include_fields: true,
        fields: 'test',
      };
      const request = nock(API_URL).get('/organizations').query(params).reply(200);

      organizations.getAll(params).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#getByID', () => {
    beforeEach(function () {
      this.data = {
        id: 'org_123456',
        name: 'organizations',
        display_name: 'My organization',
      };

      this.request = nock(API_URL).get(`/organizations/${this.data.id}`).reply(200, this.data);
    });

    it('should accept a callback', function (done) {
      const params = { id: this.data.id };

      organizations.getByID(params, done.bind(null, null));
    });

    it('should return a promise if no callback is given', function (done) {
      organizations
        .getByID({ id: this.data.id })
        .then(done.bind(null, null))
        .catch(done.bind(null, null));
    });

    it('should perform a GET request to /api/v2/organizations/:id', function (done) {
      const { request } = this;

      organizations.getByID({ id: this.data.id }).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should pass any errors to the promise catch handler', function (done) {
      nock.cleanAll();

      nock(API_URL).get(`/organizations/${this.data.id}`).reply(500);

      organizations.getByID({ id: this.data.id }).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should include the token in the Authorization header', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .get(`/organizations/${this.data.id}`)
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.getByID({ id: this.data.id }).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#getByName', () => {
    beforeEach(function () {
      this.data = {
        id: 'org_123456',
        name: 'organizations',
        display_name: 'My organization',
      };

      this.request = nock(API_URL)
        .get(`/organizations/name/${this.data.name}`)
        .reply(200, this.data);
    });

    it('should accept a callback', function (done) {
      const params = { name: this.data.name };

      organizations.getByName(params, done.bind(null, null));
    });

    it('should return a promise if no callback is given', function (done) {
      organizations
        .getByName({ name: this.data.name })
        .then(done.bind(null, null))
        .catch(done.bind(null, null));
    });

    it('should perform a GET request to /api/v2/organizations/name/:name', function (done) {
      const { request } = this;

      organizations.getByName({ name: this.data.name }).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should pass any errors to the promise catch handler', function (done) {
      nock.cleanAll();

      nock(API_URL).get(`/organizations/${this.data.name}`).reply(500);

      organizations.getByName({ name: this.data.name }).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should include the token in the Authorization header', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .get(`/organizations/name/${this.data.name}`)
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.getByName({ name: this.data.name }).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#create', () => {
    const data = {
      id: 'org_123',
      name: 'org_name',
      display_name: 'My Organization',
    };

    beforeEach(function () {
      this.request = nock(API_URL).post('/organizations').reply(200);
    });

    it('should accept a callback', (done) => {
      organizations.create(data, () => {
        done();
      });
    });

    it('should return a promise if no callback is given', (done) => {
      organizations.create(data).then(done.bind(null, null)).catch(done.bind(null, null));
    });

    it('should pass any errors to the promise catch handler', (done) => {
      nock.cleanAll();

      nock(API_URL).post('/organizations').reply(500);

      organizations.create(data).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should perform a POST request to /api/v2/organizations', function (done) {
      const { request } = this;

      organizations.create(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should pass the data in the body of the request', (done) => {
      nock.cleanAll();

      const request = nock(API_URL).post('/organizations', data).reply(200);

      organizations.create(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should include the token in the Authorization header', (done) => {
      nock.cleanAll();

      const request = nock(API_URL)
        .post('/organizations')
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.create(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#update', () => {
    beforeEach(function () {
      this.data = { id: 'org_123' };

      this.request = nock(API_URL).patch(`/organizations/${this.data.id}`).reply(200, this.data);
    });

    it('should accept a callback', (done) => {
      organizations.update({ id: 'org_123' }, {}, done.bind(null, null));
    });

    it('should return a promise if no callback is given', (done) => {
      organizations
        .update({ id: 'org_123' }, {})
        .then(done.bind(null, null))
        .catch(done.bind(null, null));
    });

    it('should perform a PATCH request to /api/v2/organizations/org_123', function (done) {
      const { request } = this;

      organizations.update({ id: 'org_123' }, {}).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should include the new data in the body of the request', function (done) {
      nock.cleanAll();

      const request = nock(API_URL).patch(`/organizations/${this.data.id}`, this.data).reply(200);

      organizations.update({ id: 'org_123' }, this.data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should pass any errors to the promise catch handler', function (done) {
      nock.cleanAll();

      nock(API_URL).patch(`/organizations/${this.data.id}`).reply(500);

      organizations.update({ id: this.data.id }, this.data).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });
  });

  describe('#delete', () => {
    const id = 'rol_ID';

    beforeEach(function () {
      this.request = nock(API_URL).delete(`/organizations/${id}`).reply(200);
    });

    it('should accept a callback', (done) => {
      organizations.delete({ id }, done.bind(null, null));
    });

    it('should return a promise when no callback is given', (done) => {
      organizations.delete({ id }).then(done.bind(null, null));
    });

    it(`should perform a delete request to /organizations/${id}`, function (done) {
      const { request } = this;

      organizations.delete({ id }).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should pass any errors to the promise catch handler', (done) => {
      nock.cleanAll();

      nock(API_URL).delete(`/organizations/${id}`).reply(500);

      organizations.delete({ id }).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should include the token in the authorization header', (done) => {
      nock.cleanAll();

      const request = nock(API_URL)
        .delete(`/organizations/${id}`)
        .matchHeader('authorization', `Bearer ${token}`)
        .reply(200);

      organizations.delete({ id }).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  //// Connections
  describe('#getEnabledConnections', () => {
    const data = {
      id: 'org_id',
    };

    beforeEach(function () {
      this.request = nock(API_URL).get(`/organizations/${data.id}/enabled_connections`).reply(200);
    });

    it('should accept a callback', (done) => {
      organizations.getEnabledConnections(data, done.bind(null, null));
    });

    it('should return a promise when no callback is given', (done) => {
      organizations.getEnabledConnections(data).then(done.bind(null, null));
    });

    it('should perform a GET request to /api/v2/organizations/org_id/enabled_connections', function (done) {
      const { request } = this;

      organizations.getEnabledConnections(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should pass any errors to the promise catch handler', (done) => {
      nock.cleanAll();

      nock(API_URL).get(`/organizations/${data.id}/enabled_connections`).reply(500);

      organizations.getEnabledConnections(data).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should include the token in the authorization header', (done) => {
      nock.cleanAll();

      const request = nock(API_URL)
        .get(`/organizations/${data.id}/enabled_connections`)
        .matchHeader('authorization', `Bearer ${token}`)
        .reply(200);

      organizations.getEnabledConnections(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#getEnabledConnection', () => {
    const data = {
      id: 'org_id',
      connection_id: 'conn_id',
    };

    beforeEach(function () {
      this.request = nock(API_URL)
        .get(`/organizations/${data.id}/enabled_connections/${data.connection_id}`)
        .reply(200);
    });

    it('should accept a callback', (done) => {
      organizations.getEnabledConnection(data, done.bind(null, null));
    });

    it('should return a promise when no callback is given', (done) => {
      organizations.getEnabledConnection(data).then(done.bind(null, null));
    });

    it('should perform a GET request to /api/v2/organizations/rol_ID/enabled_connections/con_id', function (done) {
      const { request } = this;

      organizations.getEnabledConnection(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should pass any errors to the promise catch handler', (done) => {
      nock.cleanAll();

      nock(API_URL)
        .get(`/organizations/${data.id}/enabled_connections/${data.connection_id}`)
        .reply(500);

      organizations.getEnabledConnection(data).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should include the token in the authorization header', (done) => {
      nock.cleanAll();

      const request = nock(API_URL)
        .get(`/organizations/${data.id}/enabled_connections/${data.connection_id}`)
        .matchHeader('authorization', `Bearer ${token}`)
        .reply(200);

      organizations.getEnabledConnection(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#addEnabledConnection', () => {
    beforeEach(function () {
      this.data = {
        id: 'org_123',
      };
      this.body = { connection_id: '123', assign_membership_on_login: false };

      this.request = nock(API_URL)
        .post(`/organizations/${this.data.id}/enabled_connections`)
        .reply(200);
    });

    it('should accept a callback', function (done) {
      organizations.addEnabledConnection(this.data, {}, () => {
        done();
      });
    });

    it('should return a promise if no callback is given', function (done) {
      organizations
        .addEnabledConnection(this.data, {})
        .then(done.bind(null, null))
        .catch(done.bind(null, null));
    });

    it('should pass any errors to the promise catch handler', function (done) {
      nock.cleanAll();

      nock(API_URL).post(`/organizations/${this.data.id}/enabled_connections`).reply(500);

      organizations.addEnabledConnection(this.data, {}).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should perform a POST request to /api/v2/organizations/org_id/enabled_connections', function (done) {
      const { request } = this;

      organizations.addEnabledConnection(this.data, this.body).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.addEnabledConnection({ id: null }, {}, () => {});
      }).to.throw('The organization ID passed in params cannot be null or undefined');
    });

    it('should return error when id is not a string', () => {
      expect(() => {
        organizations.addEnabledConnection({ id: 123 }, {}, () => {});
      }).to.throw('The organization ID has to be a string');
    });

    it('should pass the data in the body of the request', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .post(`/organizations/${this.data.id}/enabled_connections`, this.body)
        .reply(200);

      organizations.addEnabledConnection(this.data, this.body).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should include the token in the Authorization header', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .post(`/organizations/${this.data.id}/enabled_connections`)
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.addEnabledConnection(this.data, {}).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#updateEnabledConnection', () => {
    beforeEach(function () {
      this.data = {
        id: 'org_123',
        connection_id: '123',
      };
      this.body = { assign_membership_on_login: false };

      this.request = nock(API_URL)
        .patch(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`)
        .reply(200);
    });

    it('should accept a callback', function (done) {
      organizations.updateEnabledConnection(this.data, this.body, () => {
        done();
      });
    });

    it('should return a promise if no callback is given', function (done) {
      organizations
        .updateEnabledConnection(this.data, this.body)
        .then(done.bind(null, null))
        .catch(done.bind(null, null));
    });

    it('should pass any errors to the promise catch handler', function (done) {
      nock.cleanAll();

      nock(API_URL)
        .patch(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`)
        .reply(500);

      organizations.updateEnabledConnection(this.data, this.body).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should perform a PATCH request to /api/v2/organizations/org_id/enabled_connections/conn_id', function (done) {
      const { request } = this;

      organizations.updateEnabledConnection(this.data, this.body).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.updateEnabledConnection({ id: null }, {}, () => {});
      }).to.throw('The organization ID passed in params cannot be null or undefined');
    });

    it('should return error when id is not a string', () => {
      expect(() => {
        organizations.updateEnabledConnection({ id: 123 }, {}, () => {});
      }).to.throw('The organization ID has to be a string');
    });

    it('should return error when connection_id is not sent', () => {
      expect(() => {
        organizations.updateEnabledConnection({ id: 'org_123', connection_id: null }, {}, () => {});
      }).to.throw('The connection ID passed in params cannot be null or undefined');
    });

    it('should return error when connection_id is not a string', () => {
      expect(() => {
        organizations.updateEnabledConnection({ id: 'org_123', connection_id: 123 }, {}, () => {});
      }).to.throw('The connection ID has to be a string');
    });

    it('should pass the data in the body of the request', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .patch(
          `/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`,
          this.body
        )
        .reply(200);

      organizations.updateEnabledConnection(this.data, this.body).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should include the token in the Authorization header', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .patch(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`)
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.updateEnabledConnection(this.data, this.body).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#removeEnabledConnection', () => {
    beforeEach(function () {
      this.data = {
        id: 'org_123',
        connection_id: '123',
      };

      this.request = nock(API_URL)
        .delete(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`, {})
        .reply(200);
    });

    it('should validate empty organizationId', () => {
      expect(() => {
        organizations.removeEnabledConnection({ id: null }, () => {});
      }).to.throw('The organization ID passed in params cannot be null or undefined');
    });

    it('should validate empty connectionId', function () {
      const _this = this;
      expect(() => {
        organizations.removeEnabledConnection({ id: _this.data.id }, () => {});
      }).to.throw('The connection ID passed in params cannot be null or undefined');
    });

    it('should validate non-string organizationId', () => {
      expect(() => {
        organizations.removeEnabledConnection({ id: 123 }, () => {});
      }).to.throw('The organization ID has to be a string');
    });

    it('should validate non-string connectionId', function () {
      const _this = this;
      expect(() => {
        organizations.removeEnabledConnection({ id: _this.data.id, connection_id: 123 }, () => {});
      }).to.throw('The connection ID has to be a string');
    });

    it('should accept a callback', function (done) {
      organizations.removeEnabledConnection(this.data, () => {
        done();
      });
    });

    it('should return a promise if no callback is given', function (done) {
      organizations
        .removeEnabledConnection(this.data)
        .then(done.bind(null, null))
        .catch(done.bind(null, null));
    });

    it('should pass any errors to the promise catch handler', function (done) {
      nock.cleanAll();

      nock(API_URL)
        .delete(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`)
        .reply(500);

      organizations.removeEnabledConnection(this.data, {}).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should perform a DELETE request to /api/v2/organizations/organization_id/enabled_connections/connection_id', function (done) {
      const { request } = this;

      organizations.removeEnabledConnection(this.data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should include the token in the Authorization header', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .delete(`/organizations/${this.data.id}/enabled_connections/${this.data.connection_id}`)
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.removeEnabledConnection(this.data, {}).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  //// Members
  describe('#getMembers', () => {
    const data = {
      id: 'org_id',
    };

    beforeEach(function () {
      this.request = nock(API_URL).get(`/organizations/${data.id}/members`).reply(200);
    });

    it('should accept a callback', (done) => {
      organizations.getMembers(data, done.bind(null, null));
    });

    it('should return a promise when no callback is given', (done) => {
      organizations.getMembers(data).then(done.bind(null, null));
    });

    it('should perform a GET request to /api/v2/organizations/org_ID/members', function (done) {
      const { request } = this;

      organizations.getMembers(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should pass any errors to the promise catch handler', (done) => {
      nock.cleanAll();

      nock(API_URL).get(`/organizations/${data.id}/members`).reply(500);

      organizations.getMembers(data).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should include the token in the authorization header', (done) => {
      nock.cleanAll();

      const request = nock(API_URL)
        .get(`/organizations/${data.id}/members`)
        .matchHeader('authorization', `Bearer ${token}`)
        .reply(200);

      organizations.getMembers(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#addMembers', () => {
    beforeEach(function () {
      this.data = {
        id: 'org_123',
      };
      this.body = ['user_id'];

      this.request = nock(API_URL).post(`/organizations/${this.data.id}/members`, {}).reply(200);
    });

    it('should accept a callback', function (done) {
      organizations.addMembers(this.data, {}, () => {
        done();
      });
    });

    it('should return a promise if no callback is given', function (done) {
      organizations
        .addMembers(this.data, {})
        .then(done.bind(null, null))
        .catch(done.bind(null, null));
    });

    it('should pass any errors to the promise catch handler', function (done) {
      nock.cleanAll();

      nock(API_URL).post(`/organizations/${this.data.id}/members`).reply(500);

      organizations.addMembers(this.data, {}).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should perform a POST request to /api/v2/organizations/org_id/members', function (done) {
      const { request } = this;

      organizations.addMembers(this.data, {}).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.addMembers({ id: null }, {}, () => {});
      }).to.throw('The organization ID passed in params cannot be null or undefined');
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.addMembers({ id: 123 }, {}, () => {});
      }).to.throw('The organization ID has to be a string');
    });

    it('should pass the data in the body of the request', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .post(`/organizations/${this.data.id}/members`, this.body)
        .reply(200);

      organizations.addMembers(this.data, this.body).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should include the token in the Authorization header', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .post(`/organizations/${this.data.id}/members`)
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.addMembers(this.data, {}).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#removeMembers', () => {
    beforeEach(function () {
      this.data = {
        id: 'org_123',
      };

      this.body = ['user_id'];

      this.request = nock(API_URL).delete(`/organizations/${this.data.id}/members`, {}).reply(200);
    });

    it('should validate empty organizationId', () => {
      expect(function () {
        organizations.removeMembers({ id: null }, this.body, () => {});
      }).to.throw('The organization ID passed in params cannot be null or undefined');
    });

    it('should validate non-string organizationId', function () {
      const _this = this;
      expect(() => {
        organizations.removeMembers({ id: 123 }, _this.body, () => {});
      }).to.throw('The organization ID has to be a string');
    });

    it('should return a promise if no callback is given', function (done) {
      organizations
        .removeMembers(this.data, this.body)
        .then(done.bind(null, null))
        .catch(done.bind(null, null));
    });

    it('should pass any errors to the promise catch handler', function (done) {
      nock.cleanAll();

      nock(API_URL).delete(`/organizations/${this.data.id}/members`).reply(500);

      organizations.removeMembers(this.data, this.body).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should perform a DELETE request to /api/v2/organizations/organization_id/members', function (done) {
      const request = nock(API_URL)
        .delete(`/organizations/${this.data.id}/members`, this.body)
        .reply(200);

      organizations.removeMembers(this.data, this.body, () => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should include the token in the Authorization header', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .delete(`/organizations/${this.data.id}/members`, this.body)
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.removeMembers(this.data, this.body).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  //// Roles
  describe('#getMemberRoles', () => {
    const data = {
      id: 'org_id',
      user_id: 'user_123',
    };

    beforeEach(function () {
      this.request = nock(API_URL)
        .get(`/organizations/${data.id}/members/${data.user_id}/roles`)
        .reply(200);
    });

    it('should accept a callback', (done) => {
      organizations.getMemberRoles(data, done.bind(null, null));
    });

    it('should return a promise when no callback is given', (done) => {
      organizations.getMemberRoles(data).then(done.bind(null, null));
    });

    it('should perform a GET request to /api/v2/organizations/org_ID/members/user_id/roles', function (done) {
      const { request } = this;

      organizations.getMemberRoles(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should pass any errors to the promise catch handler', (done) => {
      nock.cleanAll();

      nock(API_URL).get(`/organizations/${data.id}/members/${data.user_id}/roles`).reply(500);

      organizations.getMemberRoles(data).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should include the token in the authorization header', (done) => {
      nock.cleanAll();

      const request = nock(API_URL)
        .get(`/organizations/${data.id}/members/${data.user_id}/roles`)
        .matchHeader('authorization', `Bearer ${token}`)
        .reply(200);

      organizations.getMemberRoles(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#addMemberRoles', () => {
    beforeEach(function () {
      this.data = {
        id: 'org_123',
        user_id: 'user_id',
      };
      this.body = { roles: ['user_id'] };

      this.request = nock(API_URL)
        .post(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, this.body)
        .reply(200);
    });

    it('should accept a callback', function (done) {
      organizations.addMemberRoles(this.data, this.body, () => {
        done();
      });
    });

    it('should return a promise if no callback is given', function (done) {
      organizations
        .addMemberRoles(this.data, this.body)
        .then(done.bind(null, null))
        .catch(done.bind(null, null));
    });

    it('should pass any errors to the promise catch handler', function (done) {
      nock.cleanAll();

      nock(API_URL)
        .post(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`)
        .reply(500);

      organizations.addMemberRoles(this.data, {}).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should perform a POST request to /api/v2/organizations/org_id/members/user_id/roles', function (done) {
      const { request } = this;

      organizations.addMemberRoles(this.data, this.body).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.addMemberRoles({ id: null }, {}, () => {});
      }).to.throw('The organization ID passed in params cannot be null or undefined');
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.addMemberRoles({ id: 123 }, {}, () => {});
      }).to.throw('The organization ID has to be a string');
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.addMemberRoles({ id: 'org_123', user_id: null }, {}, () => {});
      }).to.throw('The user ID passed in params cannot be null or undefined');
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.addMemberRoles({ id: 'org_123', user_id: 123 }, {}, () => {});
      }).to.throw('The user ID has to be a string');
    });

    it('should pass the data in the body of the request', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .post(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, this.body)
        .reply(200);

      organizations.addMemberRoles(this.data, this.body).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should include the token in the Authorization header', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .post(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`)
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.addMemberRoles(this.data, {}).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#removeMemberRoles', () => {
    beforeEach(function () {
      this.data = {
        id: 'org_123',
        user_id: 'user_123',
      };

      this.body = { roles: ['user_id'] };

      this.request = nock(API_URL)
        .delete(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, {})
        .reply(200);
    });

    it('should validate empty organizationId', () => {
      expect(function () {
        organizations.removeMemberRoles({ id: null }, this.body, () => {});
      }).to.throw('The organization ID passed in params cannot be null or undefined');
    });

    it('should validate non-string organizationId', function () {
      const _this = this;
      expect(() => {
        organizations.removeMemberRoles({ id: 123 }, _this.body, () => {});
      }).to.throw('The organization ID has to be a string');
    });

    it('should return a promise if no callback is given', function (done) {
      organizations
        .removeMemberRoles(this.data, this.body)
        .then(done.bind(null, null))
        .catch(done.bind(null, null));
    });

    it('should pass any errors to the promise catch handler', function (done) {
      nock.cleanAll();

      nock(API_URL)
        .delete(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`)
        .reply(500);

      organizations.removeMemberRoles(this.data, this.body).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.removeMemberRoles({ id: 'org_123', user_id: null }, {}, () => {});
      }).to.throw('The user ID passed in params cannot be null or undefined');
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.removeMemberRoles({ id: 'org_123', user_id: 123 }, {}, () => {});
      }).to.throw('The user ID has to be a string');
    });

    it('should perform a DELETE request to /api/v2/organizations/organization_id/members/user_id/roles', function (done) {
      const request = nock(API_URL)
        .delete(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, this.body)
        .reply(200);

      organizations.removeMemberRoles(this.data, this.body, () => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should include the token in the Authorization header', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .delete(`/organizations/${this.data.id}/members/${this.data.user_id}/roles`, this.body)
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.removeMemberRoles(this.data, this.body).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  //// Invites
  describe('#getInvitations', () => {
    const data = {
      id: 'org_id',
    };

    beforeEach(function () {
      this.request = nock(API_URL).get(`/organizations/${data.id}/invitations`).reply(200);
    });

    it('should accept a callback', (done) => {
      organizations.getInvitations(data, done.bind(null, null));
    });

    it('should return a promise when no callback is given', (done) => {
      organizations.getInvitations(data).then(done.bind(null, null));
    });

    it('should perform a GET request to /api/v2/organizations/org_ID/invitations', function (done) {
      const { request } = this;

      organizations.getInvitations(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should pass any errors to the promise catch handler', (done) => {
      nock.cleanAll();

      nock(API_URL).get(`/organizations/${data.id}/invitations`).reply(500);

      organizations.getInvitations(data).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should include the token in the authorization header', (done) => {
      nock.cleanAll();

      const request = nock(API_URL)
        .get(`/organizations/${data.id}/invitations`)
        .matchHeader('authorization', `Bearer ${token}`)
        .reply(200);

      organizations.getInvitations(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#getInvitation', () => {
    const data = {
      id: 'org_id',
      invitation_id: 'inv_123',
    };

    beforeEach(function () {
      this.request = nock(API_URL)
        .get(`/organizations/${data.id}/invitations/${data.invitation_id}`)
        .reply(200);
    });

    it('should accept a callback', (done) => {
      organizations.getInvitation(data, done.bind(null, null));
    });

    it('should return a promise when no callback is given', (done) => {
      organizations.getInvitation(data).then(done.bind(null, null));
    });

    it('should perform a GET request to /api/v2/organizations/rol_ID/invitations/inv_id', function (done) {
      const { request } = this;

      organizations.getInvitation(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should pass any errors to the promise catch handler', (done) => {
      nock.cleanAll();

      nock(API_URL).get(`/organizations/${data.id}/invitations/${data.invitation_id}`).reply(500);

      organizations.getInvitation(data).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.getInvitation({ id: null }, () => {});
      }).to.throw('The organization ID passed in params cannot be null or undefined');
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.getInvitation({ id: 123 }, () => {});
      }).to.throw('The organization ID has to be a string');
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.getInvitation({ id: 'org_123', invitation_id: null }, () => {});
      }).to.throw('The invitation ID passed in params cannot be null or undefined');
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.getInvitation({ id: 'org_123', invitation_id: 123 }, () => {});
      }).to.throw('The invitation ID has to be a string');
    });

    it('should include the token in the authorization header', (done) => {
      nock.cleanAll();

      const request = nock(API_URL)
        .get(`/organizations/${data.id}/invitations/${data.invitation_id}`)
        .matchHeader('authorization', `Bearer ${token}`)
        .reply(200);

      organizations.getInvitation(data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#createInvitation', () => {
    beforeEach(function () {
      this.data = {
        id: 'org_123',
      };
      this.body = {
        invitee: 'inv',
        client_id: 'cid',
      };

      this.request = nock(API_URL)
        .post(`/organizations/${this.data.id}/invitations`, {})
        .reply(200);
    });

    it('should accept a callback', function (done) {
      organizations.createInvitation(this.data, {}, () => {
        done();
      });
    });

    it('should return a promise if no callback is given', function (done) {
      organizations
        .createInvitation(this.data, {})
        .then(done.bind(null, null))
        .catch(done.bind(null, null));
    });

    it('should pass any errors to the promise catch handler', function (done) {
      nock.cleanAll();

      nock(API_URL).post(`/organizations/${this.data.id}/invitations`).reply(500);

      organizations.createInvitation(this.data, {}).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should perform a POST request to /api/v2/organizations/org_id/invitations', function (done) {
      const { request } = this;

      organizations.createInvitation(this.data, {}).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.createInvitation({ id: null }, {}, () => {});
      }).to.throw('The organization ID passed in params cannot be null or undefined');
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.createInvitation({ id: 123 }, {}, () => {});
      }).to.throw('The organization ID has to be a string');
    });

    it('should pass the data in the body of the request', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .post(`/organizations/${this.data.id}/invitations`, this.body)
        .reply(200);

      organizations.createInvitation(this.data, this.body).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should include the token in the Authorization header', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .post(`/organizations/${this.data.id}/invitations`)
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.createInvitation(this.data, {}).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });

  describe('#deleteInvitation', () => {
    beforeEach(function () {
      this.data = {
        id: 'org_123',
        invitation_id: 'inv_123',
      };

      this.request = nock(API_URL)
        .delete(`/organizations/${this.data.id}/invitations/${this.data.invitation_id}`, {})
        .reply(200);
    });

    it('should validate empty organizationId', () => {
      expect(() => {
        organizations.deleteInvitation({ id: null }, () => {});
      }).to.throw('The organization ID passed in params cannot be null or undefined');
    });

    it('should validate non-string organizationId', () => {
      expect(() => {
        organizations.deleteInvitation({ id: 123 }, () => {});
      }).to.throw('The organization ID has to be a string');
    });

    it('should return a promise if no callback is given', function (done) {
      organizations
        .removeMembers(this.data)
        .then(done.bind(null, null))
        .catch(done.bind(null, null));
    });

    it('should pass any errors to the promise catch handler', function (done) {
      nock.cleanAll();

      nock(API_URL)
        .delete(`/organizations/${this.data.id}/invitations/${this.data.invitation_id}`, {})
        .reply(500);

      organizations.deleteInvitation(this.data).catch((err) => {
        expect(err).to.exist;

        done();
      });
    });

    it('should perform a DELETE request to /api/v2/organizations/organization_id/invitations/inv_id', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .delete(`/organizations/${this.data.id}/invitations/${this.data.invitation_id}`, {})
        .reply(200);

      organizations.deleteInvitation(this.data, () => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.deleteInvitation({ id: 'org_123', invitation_id: null }, () => {});
      }).to.throw('The invitation ID passed in params cannot be null or undefined');
    });

    it('should return error when id is not sent', () => {
      expect(() => {
        organizations.deleteInvitation({ id: 'org_123', invitation_id: 123 }, () => {});
      }).to.throw('The invitation ID has to be a string');
    });

    it('should include the token in the Authorization header', function (done) {
      nock.cleanAll();

      const request = nock(API_URL)
        .delete(`/organizations/${this.data.id}/invitations/${this.data.invitation_id}`, {})
        .matchHeader('Authorization', `Bearer ${token}`)
        .reply(200);

      organizations.deleteInvitation(this.data).then(() => {
        expect(request.isDone()).to.be.true;

        done();
      });
    });
  });
});


text:
. 'C:\tools\poshgit\dahlbyk-posh-git-fadc4dd\profile.example.ps1'

Start-SshAgent
cd C:\Users\Kevin\Source\Repos


text:
<?php
/**
 * Kohana_Sniffs_WhiteSpace_ParenthesesSniff.
 *
 * PHP version 5
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Matthew Turland <matt@ishouldbecoding.com>
 * @license   http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
 * @version   CVS: $Id$
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */

/**
 * Throws errors if spaces are used improperly around constructs,
 * parentheses, and some operators.
 *
 * @category  PHP
 * @package   PHP_CodeSniffer
 * @author    Matthew Turland <matt@ishouldbecoding.com>
 * @license   http://matrix.squiz.net/developer/tools/php_cs/licence BSD Licence
 * @version   Release: @release_version@
 * @link      http://pear.php.net/package/PHP_CodeSniffer
 */
class Kohana_Sniffs_WhiteSpace_ParenthesesSniff implements PHP_CodeSniffer_Sniff
{
    /**
     * Returns an array of tokens this test wants to listen for.
     *
     * @return array
     */
    public function register()
    {
        return array(
            T_IF,
            T_ELSE,
            T_ELSEIF,
            T_SWITCH,
            T_WHILE,
            T_FOR,
            T_FOREACH,
            T_OPEN_PARENTHESIS,
            T_CLOSE_PARENTHESIS,
            T_BITWISE_AND,
            T_BOOLEAN_NOT
        );
    }

    /**
     * Processes this test, when one of its tokens is encountered.
     *
     * @param PHP_CodeSniffer_File $phpcsFile All the tokens found in the
     *        document
     * @param int $stackPtr Position of the current token in the stack passed
     *        in $tokens
     * @return void
     */
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
    {
        $tokens = $phpcsFile->getTokens();

        switch ($tokens[$stackPtr]['type']) {
            case 'T_ELSE':
                $nextPtr = $phpcsFile->findNext(T_WHITESPACE, $stackPtr + 1, null, true);
                if ($tokens[$nextPtr]['type'] != 'T_IF') {
                    break;
                }
            case 'T_IF':
            case 'T_ELSEIF':
            case 'T_SWITCH':
            case 'T_WHILE':
            case 'T_FOR':
            case 'T_FOREACH':
                if ($tokens[$stackPtr + 1]['type'] != 'T_WHITESPACE'
                    || $tokens[$stackPtr + 1]['content'] != ' ') {
                    $error = 'Construct names should be separated from opening parentheses by a single space';
                    $phpcsFile->addError($error, $stackPtr);
                }
                break;

            case 'T_OPEN_PARENTHESIS':
                $prevPtr = $phpcsFile->findPrevious(T_WHITESPACE, $stackPtr - 1, null, true);
                if ($tokens[$stackPtr + 1]['type'] == 'T_WHITESPACE'
                    && !in_array($tokens[$prevPtr]['type'], array('T_STRING', 'T_ARRAY'))
                    && !in_array($tokens[$stackPtr + 2]['type'], array('T_BITWISE_AND', 'T_BOOLEAN_NOT', 'T_ARRAY_CAST', 'T_BOOL_CAST', 'T_DOUBLE_CAST', 'T_INT_CAST', 'T_OBJECT_CAST', 'T_STRING_CAST', 'T_UNSET_CAST'))) {
                    $error = 'Whitespace after an opening parenthesis is only allowed when !, &, or a typecasting operator immediately follows';
                    $phpcsFile->addError($error, $stackPtr);
                }
                break;

            case 'T_CLOSE_PARENTHESIS':
                $opener = $tokens[$stackPtr]['parenthesis_opener'];
                $prevPtr = $phpcsFile->findPrevious(T_WHITESPACE, $opener - 1, null, true);
                if (!in_array($tokens[$prevPtr]['type'], array('T_STRING', 'T_ARRAY'))
                    && $tokens[$stackPtr - 1]['type'] == 'T_WHITESPACE') {
                    $error = 'Whitespace before a closing parenthesis is not allowed';
                    $phpcsFile->addError($error, $stackPtr);
                }
                break;

            case 'T_BITWISE_AND':
            case 'T_BOOLEAN_NOT':
                $before = $tokens[$stackPtr - 1];
                $after = $tokens[$stackPtr + 1];
                if ($before['type'] != 'T_WHITESPACE'
                    || $before['content'] != ' '
                    || $after['type'] != 'T_WHITESPACE'
                    || $after['content'] != ' ') {
                    $error = 'A single space is required on either side of ! and & operators';
                    $phpcsFile->addError($error, $stackPtr);
                }
                break;
        }
    }
}

?>


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

import {
  ARRAY_LITERAL,
  ARRAY_PATTERN,
  ASSIGNMENT_ELEMENT,
  BINDING_ELEMENT,
  BINDING_IDENTIFIER,
  BLOCK,
  CALL_EXPRESSION,
  COMPUTED_PROPERTY_NAME,
  IDENTIFIER_EXPRESSION,
  LITERAL_EXPRESSION,
  MEMBER_EXPRESSION,
  MEMBER_LOOKUP_EXPRESSION,
  OBJECT_LITERAL,
  OBJECT_PATTERN,
  OBJECT_PATTERN_FIELD,
  PAREN_EXPRESSION,
  VARIABLE_DECLARATION_LIST
} from '../syntax/trees/ParseTreeType.js';
import {
  AssignmentElement,
  BindingElement,
  Catch,
  ForInStatement,
  ForOfStatement,
  ForOnStatement
} from '../syntax/trees/ParseTrees.js';
import {TempVarTransformer} from './TempVarTransformer.js';
import {
  EQUAL,
  LET,
  VAR
} from '../syntax/TokenType.js';
import {
  createAssignmentExpression,
  createBindingIdentifier,
  createBlock,
  createCommaExpression,
  createExpressionStatement,
  createFunctionBody,
  createIdentifierExpression,
  createMemberExpression,
  createMemberLookupExpression,
  createParenExpression,
  createVariableDeclaration,
  createVariableDeclarationList,
  createVariableStatement
} from './ParseTreeFactory.js';
import {parseExpression} from './PlaceholderParser.js';
import {prependStatements} from './PrependStatements.js'

/**
 * Collects assignments in the desugaring of a pattern.
 */
class Desugaring {
  /**
   * @param {ParseTree} rvalue
   */
  constructor(rvalue) {
    this.rvalue = rvalue;
    this.expressions = [];
    this.pendingExpressions = [];
  }

  createIterator(iterId) {
    this.pendingExpressions.push(parseExpression
        `${iterId} = ${this.rvalue}[Symbol.iterator]()`);
  }

  createInitializer(expression) {
    if (this.pendingExpressions.length === 0) return expression;
    let expressions = this.pendingExpressions;
    this.pendingExpressions = [];
    expressions.push(expression);
    return createParenExpression(createCommaExpression(expressions));
  }

  skipHole(iterId) {
    this.pendingExpressions.push(parseExpression `${iterId}.next()`);
  }
}

/**
 * Collects assignments as assignment expressions. This is the
 * desugaring for assignment expressions.
 */
class AssignmentExpressionDesugaring extends Desugaring {
  /**
   * @param {ParseTree} rvalue
   */
  constructor(rvalue) {
    super(rvalue);
  }

  /**
   * @param {AssignmentElement|IdentifierExpression} lvalue
   * @param {ParseTree} rvalue
   */
  assign(lvalue, rvalue) {
    lvalue = lvalue instanceof AssignmentElement ? lvalue.assignment : lvalue;
    rvalue = this.createInitializer(rvalue);
    this.expressions.push(createAssignmentExpression(lvalue, rvalue));
  }

  createAssignmentExpression(tempId, rvalue) {
    let expressions = this.expressions;
    expressions.unshift(createAssignmentExpression(tempId, rvalue));
    expressions.push(...this.pendingExpressions, tempId);
    return createParenExpression(createCommaExpression(expressions));
  }
}

/**
 * Collects assignments as variable declarations. This is the
 * desugaring for 'var', 'const' declarations.
 */
class VariableDeclarationDesugaring extends Desugaring {
  /**
   * @param {ParseTree} rvalue
   */
  constructor(rvalue) {
    super(rvalue);
  }

  /**
   * @param {BindingElement|IdentifierExpression} lvalue
   * @param {ParseTree} rvalue
   */
  assign(lvalue, rvalue) {
    let binding = lvalue instanceof BindingElement ?
        lvalue.binding : createBindingIdentifier(lvalue);
    rvalue = this.createInitializer(rvalue);
    this.expressions.push(createVariableDeclaration(binding, rvalue));
  }

  get declarations() {
    return this.expressions;
  }
}

/**
 * Desugars destructuring assignment.
 *
 * @see harmony:destructuring
 */
export class DestructuringTransformer extends TempVarTransformer {
  /**
   * @param {UniqueIdentifierGenerator} identifierGenerator
   */
  constructor(identifierGenerator, reporter, options) {
    super(identifierGenerator, reporter, options);
    this.parameterDeclarations = null;
  }

  /**
   * @param {ArrayPattern} tree
   * @return {ParseTree}
   */
  transformArrayPattern(tree) {
    // Patterns should be desugared by their parent nodes.
    throw new Error('unreachable');
  }

  /**
   * @param {ObjectPattern} tree
   * @return {ParseTree}
   */
  transformObjectPattern(tree) {
    // Patterns should be desugared by their parent nodes.
    throw new Error('unreachable');
  }

  /**
   * Transforms:
   *   [a, ...b]] = x
   * From an assignment expression into:
   *
   *  ($__0 = x,
   *   a = ($__1 = $__0[Symbol.iterator](),
   *       ($__2 = $__1.next()).done ? void 0 : $__2.value),
   *   b = $traceurRuntime.iteratorToArray($__1),
   *   $__0);
   *
   * Nested patterns are desugared by recursive calls to transform.
   *
   * @param {BinaryExpression} tree
   * @return {ParseTree}
   */
  transformBinaryExpression(tree) {
    this.pushTempScope();

    let rv;
    if (tree.operator.type === EQUAL && tree.left.isPattern()) {
      rv = this.transformAny(this.desugarAssignment_(tree.left, tree.right));
    } else {
      rv = super.transformBinaryExpression(tree);
    }

    this.popTempScope();
    return rv;
  }

  /**
   * @param {ParseTree} lvalue
   * @param {ParseTree} rvalue
   * @return {ParseTree}
   */
  desugarAssignment_(lvalue, rvalue) {
    let tempId = createIdentifierExpression(this.addTempVar());
    let desugaring = new AssignmentExpressionDesugaring(tempId);
    this.desugarPattern_(desugaring, lvalue);
    return desugaring.createAssignmentExpression(tempId, rvalue);
  }

  /**
   * Transforms:
   *   [a, [b, c]] = x
   * From a variable declaration list into:
   *   tmp = x, a = x[0], [b, c] = x[1]
   *
   * We do it this way (as opposed to a block with a declaration and
   * initialization statements) so that we can translate const
   * declarations, which must be initialised at declaration.
   *
   * Nested patterns are desugared by recursive calls to transform.
   *
   * @param {VariableDeclarationList} tree
   * @return {ParseTree}
   */
  transformVariableDeclarationList(tree) {
    if (!this.destructuringInDeclaration_(tree)) {
      // No lvalues to desugar.
      return super.transformVariableDeclarationList(tree);
    }

    // Desugar one level of patterns.
    let desugaredDeclarations = [];
    tree.declarations.forEach((declaration) => {
      if (declaration.lvalue.isPattern()) {
        desugaredDeclarations.push(
            ...this.desugarVariableDeclaration_(declaration));
      } else {
        desugaredDeclarations.push(declaration);
      }
    });

    // Desugar more.
    let transformedTree = this.transformVariableDeclarationList(
        createVariableDeclarationList(
            tree.declarationType,
            desugaredDeclarations));

    return transformedTree;
  }

  transformForInStatement(tree) {
    return this.transformForInOrOfOrOn_(tree,
                                        super.transformForInStatement,
                                        ForInStatement);
  }

  transformForOfStatement(tree) {
    return this.transformForInOrOfOrOn_(tree,
                                        super.transformForOfStatement,
                                        ForOfStatement);
  }

  transformForOnStatement(tree) {
    return this.transformForInOrOfOrOn_(tree,
                                        super.transformForOnStatement,
                                        ForOnStatement);
  }

  /**
   * Transforms for-in and for-of loops.
   * @param  {ForInStatement|ForOfStatement} tree The for-in or for-of loop.
   * @param  {Function} superMethod The super method to call if no pattern is
   *     present.
   * @param  {Function} constr The constructor used to create the transformed
   *     tree.
   * @return {ForInStatement|ForOfStatement} The transformed tree.
   * @private
   */
  transformForInOrOfOrOn_(tree, superMethod, constr) {
    if (!tree.initializer.isPattern() &&
        (tree.initializer.type !== VARIABLE_DECLARATION_LIST ||
         !this.destructuringInDeclaration_(tree.initializer))) {
      return superMethod.call(this, tree);
    }

    this.pushTempScope();

    let declarationType, lvalue;
    if (tree.initializer.isPattern()) {
      declarationType = null;
      lvalue = tree.initializer;
    } else {
      declarationType = tree.initializer.declarationType;
      lvalue = tree.initializer.declarations[0].lvalue;
    }

    // for (var pattern in coll) {
    //
    // =>
    //
    // for (var $tmp in coll) {
    //   var pattern = $tmp;
    //
    // And when the initializer is an assignment expression.
    //
    // for (pattern in coll) {
    //
    // =>
    //
    // for (var $tmp in coll) {
    //   pattern = $tmp;

    let statements = [];
    let binding = this.desugarBinding_(lvalue, statements, declarationType);
    let initializer = createVariableDeclarationList(VAR,
        binding, null);

    let collection = this.transformAny(tree.collection);
    let body = this.transformAny(tree.body);
    if (body.type === BLOCK)
      statements.push(...body.statements);
    else
      statements.push(body);
    body = createBlock(statements);

    this.popTempScope();

    return new constr(tree.location, initializer, collection, body);
  }

  transformAssignmentElement(tree) {
    // Patterns should be desugared by their parent nodes.
    throw new Error('unreachable');
  }

  transformBindingElement(tree) {
    // If this has an initializer the default parameter transformer moves the
    // pattern into the function body and it will be taken care of by the
    // variable pass.
    if (!tree.binding.isPattern() || tree.initializer)
      return tree;

    // function f(pattern) { }
    //
    // =>
    //
    // function f($tmp) {
    //   var pattern = $tmp;
    // }

    // We only get here for formal parameters. Variable declarations are handled
    // further up in the transformer without calling transformBindingElement.

    if (this.parameterDeclarations === null) {
      this.parameterDeclarations = [];
      this.pushTempScope();  // Popped in the function body.
    }

    let varName = this.getTempIdentifier();
    let binding = createBindingIdentifier(varName);
    let initializer = createIdentifierExpression(varName);
    let decl = createVariableDeclaration(tree.binding, initializer);

    this.parameterDeclarations.push(decl);

    return new BindingElement(null, binding, null);
  }

  transformFunctionBody(tree) {
    if (this.parameterDeclarations === null)
      return super.transformFunctionBody(tree);

    let list = createVariableDeclarationList(VAR, this.parameterDeclarations);
    let statement = createVariableStatement(list);
    let statements = prependStatements(tree.statements, statement);
    let newBody = createFunctionBody(statements);

    this.parameterDeclarations = null;

    let result = super.transformFunctionBody(newBody);
    this.popTempScope();
    return result;
  }

  transformCatch(tree) {
    if (!tree.binding.isPattern())
      return super.transformCatch(tree);

    // catch(pattern) {
    //
    // =>
    //
    // catch ($tmp) {
    //   let pattern = $tmp

    let body = this.transformAny(tree.catchBody);
    let statements = [];
    let kind = this.options.blockBinding ? LET : VAR;
    let binding = this.desugarBinding_(tree.binding, statements, kind);
    statements.push(...body.statements);
    return new Catch(tree.location, binding, createBlock(statements));
  }

  /**
   * Helper for transformations that transforms a binding to a temp binding
   * as well as a statement added into a block. For example, this is used by
   * function, for-in/of and catch.
   * @param  {ParseTree} bindingTree The tree with the binding pattern.
   * @param  {Array} statements Array that we add the assignment/variable
   *     declaration to.
   * @param {TokenType?} declarationType The kind of variable declaration to
   *     generate or null if an assignment expression is to be used.
   * @return {BindingIdentifier} The binding tree.
   */
  desugarBinding_(bindingTree, statements, declarationType) {
    let varName = this.getTempIdentifier();
    let binding = createBindingIdentifier(varName);
    let idExpr = createIdentifierExpression(varName);

    let desugaring;
    if (declarationType === null)
      desugaring = new AssignmentExpressionDesugaring(idExpr);
    else
      desugaring = new VariableDeclarationDesugaring(idExpr);

    this.desugarPattern_(desugaring, bindingTree);

    if (declarationType === null) {
      statements.push(createExpressionStatement(
          createCommaExpression(desugaring.expressions)));
    } else {
      statements.push(
          createVariableStatement(
              // Desugar more.
              this.transformVariableDeclarationList(
                  createVariableDeclarationList(
                      declarationType,
                      desugaring.declarations))));
    }

    return binding;
  }

  /**
   * @param {VariableDeclarationList} tree
   * @return {boolean}
   */
  destructuringInDeclaration_(tree) {
    return tree.declarations.some(
        (declaration) => declaration.lvalue.isPattern());
  }

  /**
   * @param {VariableDeclaration} tree
   * @return {Array.<VariableDeclaration>}
   */
  desugarVariableDeclaration_(tree) {
    let tempRValueName = this.getTempIdentifier();
    let tempRValueIdent = createIdentifierExpression(tempRValueName);
    let desugaring;
    let initializer;

    // Don't use parens for these cases:
    // - tree.initializer is assigned to a temporary.
    // - tree.initializer normally doesn't need parens for member access.
    // Don't use temporary if:
    // - there is only one value to assign (and no initializer).
    switch (tree.initializer.type) {
      // Paren not necessary.
      case ARRAY_LITERAL:
      case CALL_EXPRESSION:
      case IDENTIFIER_EXPRESSION:
      case LITERAL_EXPRESSION:
      case MEMBER_EXPRESSION:
      case MEMBER_LOOKUP_EXPRESSION:
      case OBJECT_LITERAL:
      case PAREN_EXPRESSION:
        initializer = tree.initializer;
    }

    // [1] Try first using a temporary (used later as the base rvalue).
    desugaring = new VariableDeclarationDesugaring(tempRValueIdent);
    desugaring.assign(desugaring.rvalue, tree.initializer);
    let initializerFound = this.desugarPattern_(desugaring, tree.lvalue);

    // [2] Was the temporary necessary? Then return.
    if (initializerFound || desugaring.declarations.length > 2) {
      return desugaring.declarations;
    }

    if (!initializer) {
      initializer = createParenExpression(tree.initializer);
    }

    // [3] Redo everything without the temporary.
    desugaring = new VariableDeclarationDesugaring(initializer);
    this.desugarPattern_(desugaring, tree.lvalue);

    return desugaring.declarations;
  }

  /**
   * @param {Desugaring} desugaring
   * @param {ParseTree} tree
   * @return {boolean} True if any of the patterns have an initializer.
   */
  desugarPattern_(desugaring, tree) {
    let initializerFound = false;
    let pattern;
    switch (tree.type) {
      case ARRAY_PATTERN: {
        pattern = tree;
        this.pushTempScope();
        let iterId = createIdentifierExpression(this.addTempVar());
        let iterObjectId = createIdentifierExpression(this.addTempVar());
        desugaring.createIterator(iterId);

        for (let i = 0; i < pattern.elements.length; i++) {
          let lvalue = pattern.elements[i];
          if (lvalue === null) {
            // A skip, for example [a,,c]
            desugaring.skipHole(iterId);
            continue;
          } else if (lvalue.isSpreadPatternElement()) {
            // Rest of the array, for example [x, ...y] = [1, 2, 3]
            desugaring.assign(
                lvalue.lvalue,
                parseExpression `$traceurRuntime.iteratorToArray(${iterId})`);
          } else {
            if (lvalue.initializer) {
              initializerFound = true;
            }
            desugaring.assign(
                lvalue,
                this.createConditionalIterExpression(iterObjectId, iterId,
                                                     lvalue.initializer));
          }
        }
        this.popTempScope();
        break;
      }

      case OBJECT_PATTERN: {
        pattern = tree;

        let elementHelper = (lvalue, initializer) => {
          if (initializer)
            initializerFound = true;
          let lookup = this.createConditionalMemberExpression(desugaring.rvalue,
              lvalue, initializer);
          desugaring.assign(lvalue, lookup);
        };

        pattern.fields.forEach((field) => {
          let lookup;
          switch (field.type) {
            case ASSIGNMENT_ELEMENT:
              elementHelper(field.assignment, field.initializer);
              break;

            case BINDING_ELEMENT:
              elementHelper(field.binding, field.initializer);
              break;

            case OBJECT_PATTERN_FIELD: {
              if (field.element.initializer)
                initializerFound = true;
              let name = field.name;
              lookup = this.createConditionalMemberExpression(desugaring.rvalue,
                  name, field.element.initializer);
              desugaring.assign(field.element, lookup);
              break;
            }

            default:
              throw Error('unreachable');
          }
        });
        break;
      }

      case PAREN_EXPRESSION:
        return this.desugarPattern_(desugaring, tree.expression);

      default:
        throw new Error('unreachable');
    }

    // In case we have `var {} = expr` or `var [] = expr` we use a temp
    // variable name so that the expression still gets executed.
    //
    // AssignmentExpressionDesugaring already works.
    if (desugaring instanceof VariableDeclarationDesugaring &&
        desugaring.declarations.length === 0) {
      desugaring.assign(createBindingIdentifier(this.getTempIdentifier()),
                        desugaring.rvalue);
    }

    return initializerFound;
  }

  /**
   * Creates something like:
   *
   *   ($tmp = rvalue.ident) === undefined ? initializer : $tmp
   */
  createConditionalMemberExpression(rvalue, name, initializer) {
    if (name.type === COMPUTED_PROPERTY_NAME) {
      return this.createConditionalMemberLookupExpression(rvalue,
          name.expression, initializer);
    }

    let token;
    switch (name.type) {
      case BINDING_IDENTIFIER:
      case IDENTIFIER_EXPRESSION:
        token = name.identifierToken;
        break;
      default:
        token = name.literalToken;
    }

    if (!initializer)
      return createMemberExpression(rvalue, token);

    let tempIdent = createIdentifierExpression(this.addTempVar());

    return parseExpression `(${tempIdent} = ${rvalue}.${token}) === void 0 ?
        ${initializer} : ${tempIdent}`;
  }

  createConditionalMemberLookupExpression(rvalue, index, initializer) {
    if (!initializer)
      return createMemberLookupExpression(rvalue, index);

    let tempIdent = createIdentifierExpression(this.addTempVar());
    return parseExpression `(${tempIdent} = ${rvalue}[${index}]) === void 0 ?
        ${initializer} : ${tempIdent}`;
  }

  createConditionalIterExpression(iterObjectId, iterId, initializer) {
    let expr = parseExpression `(${iterObjectId} =
        ${iterId}.next()).done ? void 0 : ${iterObjectId}.value`;
    if (!initializer) {
      return expr;
    }
    // TODO(arv): Simplify this expression?
    let tempIdent = createIdentifierExpression(this.addTempVar());
    return parseExpression `(${tempIdent} = ${expr}) === void 0 ?
        ${initializer} : ${tempIdent}`;
  }
}


text:
<f:if condition="{configuration.insertAbove}">
	<f:render section="paginator" arguments="{pagination: pagination,configuration:configuration}" />
</f:if>

<f:renderChildren arguments="{contentArguments}" />

<f:if condition="{configuration.insertBelow}">
	<f:render section="paginator" arguments="{pagination: pagination,configuration:configuration}" />
</f:if>

<f:section name="paginator">
	<f:if condition="{pagination.numberOfPages} > 1">

			<f:if condition="{pagination.previousPage}">

					<f:if condition="{pagination.previousPage} > 1">
						<f:then>
							<f:widget.link arguments="{currentPage: pagination.previousPage}">←</f:widget.link>
						</f:then>
						<f:else>
							<f:widget.link>←</f:widget.link>
						</f:else>
					</f:if>

			</f:if>
			<f:if condition="{pagination.lessPages}">

....

			</f:if>
			<f:for each="{pagination.pages}" as="page">
				<f:if condition="{page.isCurrent}">
					<f:then>

							{page.number}

					</f:then>
					<f:else>

							<f:if condition="{page.number} > 1">
								<f:then>
									<f:widget.link arguments="{currentPage: page.number}">{page.number}</f:widget.link>
								</f:then>
								<f:else>
									<f:widget.link>{page.number}</f:widget.link>
								</f:else>
							</f:if>

					</f:else>
				</f:if>
			</f:for>
			<f:if condition="{pagination.morePages}">

....

			</f:if>
			<f:if condition="{pagination.nextPage}">

					<f:widget.link arguments="{currentPage: pagination.nextPage}">→</f:widget.link>

			</f:if>

	</f:if>
</f:section>


text:
module EWS
  class Attachment < Model
    def id
      attrs[:attachment_id]
    end
  end
end


text:
package org.fuusio.api.flow;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;

import org.fuusio.api.dependency.D;
import org.fuusio.api.mvp.Presenter;
import org.fuusio.api.mvp.ViewActivity;

/**
 * {@link FlowActivity} is an abstract base class for implementing a {@link ViewActivity} that uses
 * a {@link Flow} to implement UI flow logic. A {@link Flow} implementation receives the lifecycle
 * events of an {@link Activity} and can control UI control logic according to the events.
 *
 * @param <T_Flow> A type parameter for {@link Flow}.
 */
public abstract class FlowActivity<T_Flow extends Flow, T_Presenter extends Presenter> extends ViewActivity<T_Presenter> implements FlowFragmentContainer {

    protected T_Flow mFlow;
    protected Class<T_Flow> mFlowClass;

    public final T_Flow getFlow() {
        return mFlow;
    }

    public void setFlow(final T_Flow flow) {
        mFlow = flow;
    }

    @Override
    public Context getContext() {
        return this;
    }

    @Override
    protected void onCreate(final Bundle inState) {
        super.onCreate(inState);

        mFlow = createFlow(inState);
        D.activateScope(mFlow);
    }

    /**
     * Sets the {@link Class} for creating the {@link Flow} in method
     * {@link FlowActivity#setFlowClass(Class)}.
     *
     * @param flowClass A {@link Class}.
     */
    protected void setFlowClass(final Class<T_Flow> flowClass) {
        mFlowClass = flowClass;
    }

    /**
     * Creates the {@link Flow} for this {@link FlowActivity}. This method can be overridden in
     * concrete implementations of {@link FlowActivity} if method {@link FlowActivity} used.
     *
     * @param inState
     * @return
     */
    protected T_Flow createFlow(final Bundle inState) {

        T_Flow flow = null;

        if (mFlowClass != null) {
            flow = FlowManager.createFlow(mFlowClass, this, inState);
        }
        return flow;
    }

    @Override
    protected void onStart() {
        super.onStart();
        mFlow.start(null);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mFlow.restart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mFlow.resume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mFlow.pause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mFlow.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mFlow.destroy();
    }
}