<commit_before>function renderPredicate(pred) {
  switch (pred.type) {
    case 'const':
      return pred.const ? 'T' : 'F'
    case 'not': {
      let inner = renderPredicate(pred.inner)
      if (logicOperationPrecedenceLess(pred, pred.inner)) {
        inner = '(' + inner + ')'
      }
      return '~' + inner
    }
    case 'and':
    case 'implies':
    case 'iff':
    case 'or': {
      let lhs = renderPredicate(pred.left),
          rhs = renderPredicate(pred.right)
      if (logicOperationPrecedenceLess(pred, pred.left)) {
        lhs = '(' + lhs + ')'
      }
      if (logicOperationPrecedenceLess(pred, pred.right)) {
        rhs = '(' + rhs + ')'
      }
      return lhs + ` ${renderLogicOperation(pred.type)} ` + rhs
    }
    case 'comp':
      return renderIntegerExpression(pred.left)
        + ` ${pred.op} ` + renderIntegerExpression(pred.right)
    case 'call':
      return pred.name + '('
        + pred.args.map(renderArgument).join(', ') + ')'
    case 'forall': {
      const name = renderVariable(pred.boundVar)
      const condition = renderPredicate(pred.condition)
      const inner = renderPredicate(pred.inner)
      return `(A ${name} : ${condition} : ${inner})`
    }
    case 'exists': {
      const name = renderVariable(pred.boundVar)
      const condition = renderPredicate(pred.condition)
      const inner = renderPredicate(pred.inner)
      return `(E ${name} : ${condition} : ${inner})`
    }
    default:
      throw new Error(`Unknown type of predicate: ${pred.type}.`)
  }
}

function renderLogicOperation(op) {
  switch (op) {
    case 'and': return '&&'
    case 'implies': return '=>'
    case 'iff': return '<=>'
    case 'or': return '||'
    default:
      throw new Error(`Unknown logic operation: ${op}.`)
  }
}

function renderIntegerExpression(expr) {
  switch (expr.type) {
    case 'const':
      return expr.const.toString()
    case 'negate': {
      let inner = renderIntegerExpression(expr.inner)
      if (integerOperationPrecedenceLess(expr, expr.inner)) {
        inner = '(' + inner + ')'
      }
      return '- ' + inner
    }
    case 'var':
      return renderVariable(expr.var)
    case 'plus':
    case 'minus':
    case 'mult': {
      let lhs = renderIntegerExpression(expr.left),
          rhs = renderIntegerExpression(expr.right)
      if (integerOperationPrecedenceLess(expr, expr.left)) {
        lhs = '(' + lhs + ')'
      }
      if (integerOperationPrecedenceLess(expr, expr.right)) {
        rhs = '(' + rhs + ')'
      }
      return lhs + ` ${renderIntegerOperation(expr.type)} ` + rhs
    }
    case 'call':
      return pred.name + '('
        + pred.args.map(renderArgument).join(', ') + ')'
    case 'sum': {
      const name = renderVariable(expr.boundVar)
      const condition = renderPredicate(expr.condition)
      const inner = renderIntegerExpression(expr.inner)
      return `(SUM ${name} : ${condition} : ${inner})`
    }
    case 'prod': {
      const name = renderVariable(expr.boundVar)
      const condition = renderPredicate(expr.condition)
      const inner = renderIntegerExpression(expr.inner)
      return `(PROD ${name} : ${condition} : ${inner})`
    }
    case 'count': {
      const name = renderVariable(expr.boundVar)
      const condition = renderPredicate(expr.condition)
      const inner = renderPredicate(expr.inner)
      return `(N ${name} : ${condition} : ${inner})`
    }
    default:
      throw new Error(`Unknown type of integer expression: ${expr.type}.`)
  }
}

function renderIntegerOperation(op) {
  switch (op) {
    case 'plus': return '+'
    case 'minus': return '-'
    case 'mult': return '*'
    default:
      throw new Error(`Unknown integer operation: ${op}.`)
  }
}

function renderVariable(variable) {
  switch (variable.type) {
    case 'name':
      return variable.name
    case 'select':
      return renderVariable(variable.base)
        + `[${renderIntegerExpression(variable.selector)}]`
    case 'store': {
      const base = renderVariable(variable.base)
      let selector = renderIntegerExpression(variable.selector)
      if (variable.selector.type !== 'var') {
        selector = '(' + selector + ')'
      }
      let value = null
      if (variable.value.type === 'store') {
        value = renderVariable(variable.value)
      } else if (variable.value.type === 'var') {
        value = renderIntegerExpression(variable.value)
      } else {
        value = '(' + renderIntegerExpression(variable.value) + ')'
      }
      return `(${base}; ${selector}:${value})`
    }
    default:
      throw new Error(`Unknown type of variable: ${variable.type}.`)
  }
}

function renderArgument(arg) {
  return arg.type === 'store'
    ? renderVariable(arg)
    : renderIntegerExpression(arg)
}

function logicOperationPrecedenceLess(op1, op2) {
  return logiOperationPrecedenceNumber(op1)
    < logiOperationPrecedenceNumber(op2)
}

function logiOperationPrecedenceNumber(pred) {
  switch (pred.type) {
    case 'comp':    return 0
    case 'const':   return 0
    case 'call':    return 0
    case 'not':     return 0
    case 'and':     return 1
    case 'or':      return 2
    case 'implies': return 3
    case 'iff':     return 4
    case 'forall':  return 0  // The precedence is "incorrectly" 0, because
    case 'exists':  return 0  // we always render quantifiers in parentheses.
    default:
      throw new Error(`Unknown predicate type: ${pred.type}.`)
  }
}

function integerOperationPrecedenceLess(op1, op2) {
  return integerOperationPrecedenceNumber(op1)
    < integerOperationPrecedenceNumber(op2)
}

function integerOperationPrecedenceNumber(expr) {
  switch (expr.type) {
    case 'var':    return 0
    case 'call':   return 0
    case 'const':  return 0
    case 'negate': return 0
    case 'mult':   return 1
    case 'plus':   return 2
    case 'minus':  return 2
    case 'sum':    return 0  // The precedence is "incorrectly" 0,
    case 'prod':   return 0  // because we always render
    case 'count':  return 0  // quantifiers in parentheses.
    default:
      throw new Error(`Unknown integer expression type: ${expr.type}.`)
  }
}

module.exports.renderPredicate = renderPredicate
module.exports.renderIntegerExpression = renderIntegerExpression
<commit_msg>Fixed store vars rendering.<commit_after>function renderPredicate(pred) {
  switch (pred.type) {
    case 'const':
      return pred.const ? 'T' : 'F'
    case 'not': {
      let inner = renderPredicate(pred.inner)
      if (logicOperationPrecedenceLess(pred, pred.inner)) {
        inner = '(' + inner + ')'
      }
      return '~' + inner
    }
    case 'and':
    case 'implies':
    case 'iff':
    case 'or': {
      let lhs = renderPredicate(pred.left),
          rhs = renderPredicate(pred.right)
      if (logicOperationPrecedenceLess(pred, pred.left)) {
        lhs = '(' + lhs + ')'
      }
      if (logicOperationPrecedenceLess(pred, pred.right)) {
        rhs = '(' + rhs + ')'
      }
      return lhs + ` ${renderLogicOperation(pred.type)} ` + rhs
    }
    case 'comp':
      return renderIntegerExpression(pred.left)
        + ` ${pred.op} ` + renderIntegerExpression(pred.right)
    case 'call':
      return pred.name + '('
        + pred.args.map(renderArgument).join(', ') + ')'
    case 'forall': {
      const name = renderVariable(pred.boundVar)
      const condition = renderPredicate(pred.condition)
      const inner = renderPredicate(pred.inner)
      return `(A ${name} : ${condition} : ${inner})`
    }
    case 'exists': {
      const name = renderVariable(pred.boundVar)
      const condition = renderPredicate(pred.condition)
      const inner = renderPredicate(pred.inner)
      return `(E ${name} : ${condition} : ${inner})`
    }
    default:
      throw new Error(`Unknown type of predicate: ${pred.type}.`)
  }
}

function renderLogicOperation(op) {
  switch (op) {
    case 'and': return '&&'
    case 'implies': return '=>'
    case 'iff': return '<=>'
    case 'or': return '||'
    default:
      throw new Error(`Unknown logic operation: ${op}.`)
  }
}

function renderIntegerExpression(expr) {
  switch (expr.type) {
    case 'const':
      return expr.const.toString()
    case 'negate': {
      let inner = renderIntegerExpression(expr.inner)
      if (integerOperationPrecedenceLess(expr, expr.inner)) {
        inner = '(' + inner + ')'
      }
      return '- ' + inner
    }
    case 'var':
      return renderVariable(expr.var)
    case 'plus':
    case 'minus':
    case 'mult': {
      let lhs = renderIntegerExpression(expr.left),
          rhs = renderIntegerExpression(expr.right)
      if (integerOperationPrecedenceLess(expr, expr.left)) {
        lhs = '(' + lhs + ')'
      }
      if (integerOperationPrecedenceLess(expr, expr.right)) {
        rhs = '(' + rhs + ')'
      }
      return lhs + ` ${renderIntegerOperation(expr.type)} ` + rhs
    }
    case 'call':
      return pred.name + '('
        + pred.args.map(renderArgument).join(', ') + ')'
    case 'sum': {
      const name = renderVariable(expr.boundVar)
      const condition = renderPredicate(expr.condition)
      const inner = renderIntegerExpression(expr.inner)
      return `(SUM ${name} : ${condition} : ${inner})`
    }
    case 'prod': {
      const name = renderVariable(expr.boundVar)
      const condition = renderPredicate(expr.condition)
      const inner = renderIntegerExpression(expr.inner)
      return `(PROD ${name} : ${condition} : ${inner})`
    }
    case 'count': {
      const name = renderVariable(expr.boundVar)
      const condition = renderPredicate(expr.condition)
      const inner = renderPredicate(expr.inner)
      return `(N ${name} : ${condition} : ${inner})`
    }
    default:
      throw new Error(`Unknown type of integer expression: ${expr.type}.`)
  }
}

function renderIntegerOperation(op) {
  switch (op) {
    case 'plus': return '+'
    case 'minus': return '-'
    case 'mult': return '*'
    default:
      throw new Error(`Unknown integer operation: ${op}.`)
  }
}

function renderVariable(variable) {
  switch (variable.type) {
    case 'name':
      return variable.name
    case 'select':
      return renderVariable(variable.base)
        + `[${renderIntegerExpression(variable.selector)}]`
    case 'store': {
      const base = renderVariable(variable.base)
      let selector = renderIntegerExpression(variable.selector)
      if (exprNeedsParentheses(variable.selector)) {
        selector = '(' + selector + ')'
      }
      let value = null
      if (variable.value.type === 'store') {
        value = renderVariable(variable.value)
      } else if (exprNeedsParentheses(variable.value)) {
        value = '(' + renderIntegerExpression(variable.value) + ')'
      } else {
        value = renderIntegerExpression(variable.value)
      }
      return `(${base}; ${selector}:${value})`
    }
    default:
      throw new Error(`Unknown type of variable: ${variable.type}.`)
  }
}

function exprNeedsParentheses(expr) {
  return expr.type === 'negate'
    expr.type === 'plus'
    expr.type === 'minus'
    expr.type === 'mult'
}

function renderArgument(arg) {
  return arg.type === 'store'
    ? renderVariable(arg)
    : renderIntegerExpression(arg)
}

function logicOperationPrecedenceLess(op1, op2) {
  return logiOperationPrecedenceNumber(op1)
    < logiOperationPrecedenceNumber(op2)
}

function logiOperationPrecedenceNumber(pred) {
  switch (pred.type) {
    case 'comp':    return 0
    case 'const':   return 0
    case 'call':    return 0
    case 'not':     return 0
    case 'and':     return 1
    case 'or':      return 2
    case 'implies': return 3
    case 'iff':     return 4
    case 'forall':  return 0  // The precedence is "incorrectly" 0, because
    case 'exists':  return 0  // we always render quantifiers in parentheses.
    default:
      throw new Error(`Unknown predicate type: ${pred.type}.`)
  }
}

function integerOperationPrecedenceLess(op1, op2) {
  return integerOperationPrecedenceNumber(op1)
    < integerOperationPrecedenceNumber(op2)
}

function integerOperationPrecedenceNumber(expr) {
  switch (expr.type) {
    case 'var':    return 0
    case 'call':   return 0
    case 'const':  return 0
    case 'negate': return 0
    case 'mult':   return 1
    case 'plus':   return 2
    case 'minus':  return 2
    case 'sum':    return 0  // The precedence is "incorrectly" 0,
    case 'prod':   return 0  // because we always render
    case 'count':  return 0  // quantifiers in parentheses.
    default:
      throw new Error(`Unknown integer expression type: ${expr.type}.`)
  }
}

module.exports.renderPredicate = renderPredicate
module.exports.renderIntegerExpression = renderIntegerExpression
<|endoftext|>


<commit_before>'use strict';

var glob = require('glob');
var sutil = require('spun-util');
var errors = sutil.errors;
var path = require('path');
var resolve = path.resolve;
var basename = path.basename;
var dirname = path.dirname;

describe('run', function(){
  var run = require('../lib/run');
  var argv = {workerCount: 5};
  var strategyProvider = {};

  describe('during parsing', function(){
    glob
    .sync('./acceptance/parsing/passing/*.spun', {cwd: __dirname})
    .map(toAbsolutePath(__dirname))
    .forEach(function(test){
      it('should allow ' + basename(test.relative, '.spun'), function(done){
        run(argv, [test.absolute], strategyProvider, done);
      });
    });

    glob
    .sync('./acceptance/parsing/failing/*.spun', {cwd: __dirname})
    .map(toAbsolutePath(__dirname))
    .forEach(function(test){
      var absoluePath = test.absolute;
      var errorPath = resolve(dirname(absoluePath), basename(absoluePath, '.spun') + '.js');
      var error = require(errorPath);

      it('should not allow ' + basename(test.relative, '.spun'), function(done){
        run(argv, [absoluePath], strategyProvider, function(err){
          err.should.be.an.instanceOf(error);
          done();
        });
      });
    });
  });
});

function toAbsolutePath(base){
  return function(path){
    return {
      base: base,
      relative: path,
      absolute: resolve(base, path)
    };
  };
}
<commit_msg>Adding better logging for error handling in tests.<commit_after>'use strict';

var glob = require('glob');
var sutil = require('spun-util');
var errors = sutil.errors;
var path = require('path');
var resolve = path.resolve;
var basename = path.basename;
var dirname = path.dirname;

describe('run', function(){
  var run = require('../lib/run');
  var argv = {workerCount: 5};
  var strategyProvider = {};

  describe('during parsing', function(){
    glob
    .sync('./acceptance/parsing/passing/*.spun', {cwd: __dirname})
    .map(toAbsolutePath(__dirname))
    .forEach(function(test){
      it('should allow ' + basename(test.relative, '.spun'), function(done){
        run(argv, [test.absolute], strategyProvider, function(err){
          if(err){
            console.log(err.message);
          }
          done(err);
        });
      });
    });

    glob
    .sync('./acceptance/parsing/failing/*.spun', {cwd: __dirname})
    .map(toAbsolutePath(__dirname))
    .forEach(function(test){
      var absoluePath = test.absolute;
      var errorPath = resolve(dirname(absoluePath), basename(absoluePath, '.spun') + '.js');
      var error = require(errorPath);

      it('should not allow ' + basename(test.relative, '.spun'), function(done){
        run(argv, [absoluePath], strategyProvider, function(err){
          if(!err)return done(new Error('Expected to see an error!'));
          err.should.be.an.instanceOf(error);
          done();
        });
      });
    });
  });
});

function toAbsolutePath(base){
  return function(path){
    return {
      base: base,
      relative: path,
      absolute: resolve(base, path)
    };
  };
}
<|endoftext|>


<commit_before>describes.endtoend(
  'Bento',
  {
    environments: ['single'],
    fixture: 'bento/minimal.html',
  },
  async function (env) {
    it('attaches shadow root', async () => {
      // Set timeout lower than default in order to fail early, since the root
      // is attached as soon as possible.
      // (Feel free to increase if flaky.)
      this.timeout(100);

      const shadowRoot = await env.controller.evaluate(
        () =>
          new Promise((resolve) => {
            function getShadowRoot() {
              const {shadowRoot} = document.body.firstElementChild;
              if (shadowRoot) {
                resolve(shadowRoot);
              } else {
                setTimeout(getShadowRoot, 15);
              }
            }
            getShadowRoot();
          })
      );
      await expect(shadowRoot).ok;
    });
  }
);
<commit_msg>(bento): refactor test to use existing shadow root utilities (#36454)<commit_after>describes.endtoend(
  'Bento',
  {
    environments: ['single'],
    fixture: 'bento/minimal.html',
  },
  async function (env) {
    it('attaches shadow root', async () => {
      // Set timeout lower than default in order to fail early, since the root
      // is attached as soon as possible.
      // (Feel free to increase if flaky.)
      this.timeout(100);
      await env.controller.switchToShadowRoot(
        await env.controller.findElement('bento-timeago')
      );

      await expect(await env.controller.findElement('time')).ok;
    });
  }
);
<|endoftext|>


<commit_before>import { logger } from "./../server/index"

import User from "./models/user"

export default (passport) => {
  passport.serializeUser((user, done) => done(null, user.get("uuid")))

  passport.deserializeUser(async (uuid, done) => {
    logger.debug(`Negotiating session for ${uuid}`)
    done(null, await User.where({ uuid }).fetch())
  })
}
<commit_msg>use id for session serialization<commit_after>import { logger } from "./../server/index"

import User from "./models/user"

export default (passport) => {
  passport.serializeUser((user, done) => { done(null, user.get("id")) })

  passport.deserializeUser(async (id, done) => {
    logger.debug(`Negotiating session for ${id}`)
    done(null, await User.where({ id }).fetch())
  })
}
<|endoftext|>


<commit_before>import Hook from 'util/hook'
import schemaGen from './gensrc/schema'
import resolverGen from './gensrc/resolver'
import schema from './schema'
import resolver from './resolver'
import {deepMergeToFirst} from 'util/deepMerge'
import {ObjectId} from "mongodb";

// Hook to add mongodb resolver
Hook.on('resolver', ({db, resolvers}) => {
    deepMergeToFirst(resolvers, resolver(db), resolverGen(db))
})

// Hook to add mongodb schema
Hook.on('schema', ({schemas}) => {
    schemas.push(schemaGen)
    schemas.push(schema)
})

// Hook to add mongodb schema
Hook.on('NewUserCreated', async ({meta, email, insertResult, db}) => {
    if (insertResult.insertedCount) {
        if (meta && meta.newsletter) {
            const user = (await db.collection('User').findOne({email}))

            // insert or update
            const data = {
                email, list: (meta.newsletterList ? meta.newsletterList.reduce((o, id) => {
                    o.push(ObjectId(id));
                    return o
                }, []) : []), confirmed: false, state: 'optin'
            }

            if (meta.newsletterLocation) {
                data.location = meta.newsletterLocation
            }

            if (user && user._id) {
                data.account = user._id
            }

            const insertResult = await db.collection('NewsletterSubscriber').insertOne(data)
        }
    }
})

Hook.on('UserConfirmed', async ({context, user}) => {
    if (user && user.meta && user.meta.newsletter) {
        // also confirm newsletter
        resolver.Query.confirmNewsletter({email: user.email, location: user.meta.newsletterLocation}, {context})
    }
})

<commit_msg>Small improvements<commit_after>import Hook from 'util/hook'
import schemaGen from './gensrc/schema'
import resolverGen from './gensrc/resolver'
import schema from './schema'
import resolver from './resolver'
import {deepMergeToFirst} from 'util/deepMerge'
import {ObjectId} from "mongodb";

// Hook to add mongodb resolver
Hook.on('resolver', ({db, resolvers}) => {
    deepMergeToFirst(resolvers, resolver(db), resolverGen(db))
})

// Hook to add mongodb schema
Hook.on('schema', ({schemas}) => {
    schemas.push(schemaGen)
    schemas.push(schema)
})

// Hook to add mongodb schema
Hook.on('NewUserCreated', async ({meta, email, insertResult, db}) => {
    if (insertResult.insertedCount) {
        if (meta && meta.newsletter) {
            const user = (await db.collection('User').findOne({email}))

            // insert or update
            const data = {
                email, list: (meta.newsletterList ? meta.newsletterList.reduce((o, id) => {
                    o.push(ObjectId(id));
                    return o
                }, []) : []), confirmed: false, state: 'optin'
            }

            if (meta.newsletterLocation) {
                data.location = meta.newsletterLocation
            }

            if (user && user._id) {
                data.account = user._id
            }

            const insertResult = await db.collection('NewsletterSubscriber').insertOne(data)
        }
    }
})

Hook.on('UserConfirmed', async ({context,db, user}) => {
    if (user && user.meta && user.meta.newsletter) {
        // also confirm newsletter
        resolver(db).Query.confirmNewsletter({email: user.email, location: user.meta.newsletterLocation}, {context})
    }
})

<|endoftext|>


<commit_before>/*
Copyright (c) 2011 Cimaron Shanahan

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

GraphicsContext3D = (function() {

	function Initializer() {
		//private:
		this.webglCtx = null;
		this.canvas = null;

		this.buffer = null;
		this.context = null;

		this._state = {};
		this._dirty = false;

		this._frame = {};
		this._quality = {};
	}

	var GraphicsContext3D = new jClass('GraphicsContext3D', Initializer);

	//public:

	GraphicsContext3D.GraphicsContext3D = function(webglCtx) {
		var threshold, This;
		this.webglCtx = webglCtx;
		this.canvas = webglCtx.canvas;
		this.context = this.canvas.getContext('2d');

		/*
		//The following attempts to adjust the initial quality setting based
		//the number of pixels in the canvas. This threshold is mostly arbitrary
		//and could stand some more intelligent calculation
		this._quality.startThreshold = 250000;
		if (this.canvas.width * this.canvas.height > this._quality.startThreshold) {
			this._quality.factor = (this.canvas.width * this.canvas.height) / this._quality.startThreshold;
		} else {
			this._quality.factor = 1;
		}
		*/
		this._quality.factor = 1;
		this.setTargetFps(0);

		this._createBuffer();

		//initialize state
		glClearColor(0, 0, 0, 255);
		glClearDepth(1.0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glViewport(0, 0, this.canvas.width, this.canvas.height);

		This = this;
		setInterval(function() { This._redraw(); }, 0);
	};

	//public:

	GraphicsContext3D.activeTexture = function(texture) {
		glActiveTexture(texture);
	};

	GraphicsContext3D.attachShader = function(program, shader) {
		glAttachShader(program, shader);
	};

	GraphicsContext3D.bindAttribLocation = function(program, index, name) {
		glBindAttribLocation(program, index, name);
	};

	GraphicsContext3D.bindBuffer = function(target, buffer) {
		glBindBuffer(target, buffer);
	};

	GraphicsContext3D.bindTexture = function(target, texture) {
		glBindTexture(target, texture);
	};

	GraphicsContext3D.blendFunc = function(sfactor, dfactor) {
		glBlendFunc(sfactor, dfactor);
	};

	GraphicsContext3D.bufferData = function(target, size, data, usage) {
		glBufferData(target, size, data, usage);
	};

	GraphicsContext3D.bufferSubData = function(target, offset, size, data) {
		glBufferSubData(target, offset, size, data);
	};

	GraphicsContext3D.clear = function(mask) {
		this._dirty = true;
		glClear(mask);
	};

	GraphicsContext3D.clearColor = function(red, green, blue, alpha) {
		glClearColor(red, green, blue, alpha);
	};

	GraphicsContext3D.clearDepth = function(depth) {
		glClearDepth(depth);
	};

	GraphicsContext3D.compileShader = function(shader) {
		glCompileShader(shader);
	};

	GraphicsContext3D.colorMask = function(red, green, blue, alpha) {
		glColorMask(red, green, blue, alpha);
	};

	GraphicsContext3D.createBuffer = function() {
		var buffers = [];
		glGenBuffers(1, buffers);
		return buffers[0][0];
	};

	GraphicsContext3D.createProgram = function() {
		return glCreateProgram();
	};

	GraphicsContext3D.createShader = function(type) {
		return glCreateShader(type);
	};

	GraphicsContext3D.createTexture = function() {
		var textures = [];
		glGenTextures(1, textures);
		return textures[0][0];
	};

	GraphicsContext3D.cullFace = function(mode) {
		glCullFace(mode);
	};

	GraphicsContext3D.depthMask = function(flag) {
		glDepthMask(flag);
	};

	GraphicsContext3D.drawArrays = function(mode, first, count) {
		this._dirty = true;
		glDrawArrays(mode, first, count);
	};

	GraphicsContext3D.drawElements = function(mode, count, type, offset) {
		this._dirty = true;
		glDrawElements(mode, count, type, offset);
	};

	GraphicsContext3D.disable = function(cap) {
		glDisable(cap);
	};

	GraphicsContext3D.disableVertexAttribArray = function(index) {
		glDisableVertexAttribArray(index);
	};

	GraphicsContext3D.enable = function(cap) {
		glEnable(cap);
	};

	GraphicsContext3D.enableVertexAttribArray = function(index) {
		glEnableVertexAttribArray(index);
	};

	GraphicsContext3D.frontFace = function(mode) {
		glFrontFace(mode);
	};

	GraphicsContext3D.generateMipmap = function(target) {
		//glGenerateMipmap(target);
	};

	GraphicsContext3D.getAttribLocation = function(program, name) {
		return glGetAttribLocation(program, name);
	};

	GraphicsContext3D.getError = function() {
		return glGetError();
	};

	GraphicsContext3D.getProgramParameter = function(program, pname) {
		var params = [];
		glGetProgramiv(program, pname, params);
		return params[0];
	};

	GraphicsContext3D.getShaderInfoLog = function(shader) {
		var length = [], infoLog = [];
		glGetShaderInfoLog(shader, null, length, infoLog);
		return infoLog[0];
	};

	GraphicsContext3D.getShaderParameter = function(shader, pname) {
		var params = [];
		glGetShaderiv(shader, pname, params);
		return params[0];
	};

	GraphicsContext3D.getUniformLocation = function(program, name) {
		return glGetUniformLocation(program, name);
	};

	GraphicsContext3D.linkProgram = function(program) {
		glLinkProgram(program);
	};

	GraphicsContext3D.pixelStorei = function(pname, param) {
		glPixelStorei(pname, param);
	};

	GraphicsContext3D.shaderSource = function(shader, source) {
		glShaderSource(shader, 1, [source], [source.length]);
	};

	GraphicsContext3D.uniform1i = function(location, v0) {
		glUniform1i(location, v0);
	};

	GraphicsContext3D.uniform1f = function(location, v0) {
		glUniform1f(location, v0);
	};

	GraphicsContext3D.uniform3f = function(location, v0, v1, v2) {
		glUniform3f(location, v0, v1, v2);
	};

	GraphicsContext3D.uniform3fv = function(location, value) {
		glUniform3fv(location, 1, value);
	};

	GraphicsContext3D.uniformMatrix3fv = function(location, transpose, value) {
		glUniformMatrix3fv(location, value.length / 9, transpose, value);
	};

	GraphicsContext3D.uniformMatrix4fv = function(location, transpose, value) {
		glUniformMatrix4fv(location, value.length / 16, transpose, value);
	};

	GraphicsContext3D.useProgram = function(program) {
		glUseProgram(program);
	};

	GraphicsContext3D.texImage2D = function(target, level, internalformat, width, height, border, format, type, source) {
		glTexImage2D(target, level, internalformat, width, height, border, format, type, source);
	};

	GraphicsContext3D.texParameteri = function(target, pname, param) {
		glTexParameteri(target, pname, param);
	};

	GraphicsContext3D.vertexAttribPointer = function(idx, size, type, normalized, stride, offset) {
		var pointer = [];
		glVertexAttribPointer(idx, size, type, normalized, stride, offset);
	};

	GraphicsContext3D.viewport = function(x, y, width, height) {
		x = Math.round(x / this._quality.factor);
		y = Math.round(y / this._quality.factor);
		width = Math.round(width / this._quality.factor);
		height = Math.round(height / this._quality.factor);

		glViewport(x, y, width, height);
	};

	GraphicsContext3D.setTargetFps = function(low, high) {
		this._frame.fps = 0;
		this._frame.last = [];
		this._quality.fpsLow = low;
		this._quality.fpsHigh = high ? high : 1.5 * low;
		this._quality.fpsLowThreshold = 0;
		this._quality.fpsHighThreshold = 0;
	};

	GraphicsContext3D.setQuality = function(q) {
		this._quality.factor = 1 / q;
		this._createBuffer();
	};

	//private:

	GraphicsContext3D._createBuffer = function() {
		var ctx, width, height;

		ctx = cnvgl_context.getCurrentContext();

		if (!this.buffer) {
			this.buffer = this.context.createImageData(this.canvas.width, this.canvas.height);
		}
		if (!this._quality.cnv) {
			this._quality.cnv = document.createElement('canvas');
		}

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

		if (this._quality.factor > 1) {

			width = Math.round(width / this._quality.factor);
			height = Math.round(height / this._quality.factor);
			width = Math.max(width, 1);
			height = Math.max(height, 1);

			this.webglCtx.drawingBufferWidth = width;
			this.webglCtx.drawingBufferHeight = height;

			this._quality.cnv.width = width;
			this._quality.cnv.height = height;
			this._quality.ctx = this._quality.cnv.getContext('2d');
			this.context.mozImageSmoothingEnabled = false;

			this._quality.buffer = this.context.createImageData(width, height);
			ctx.color_buffer = this._quality.buffer.data;

		} else {
			ctx.color_buffer = this.buffer.data;
		}

		ctx.depth_buffer = new Float32Array(width * height);
	};

	GraphicsContext3D._updateFrame = function() {
		var time, dur;
		//update frame counts, fps, etc.
		this._frame.count++;
		time = new Date().getTime();
		this._frame.last.push(time);

		//average over one second period
		dur = time - this._frame.last[0];
		this._frame.fps = 1000 * this._frame.last.length / dur;
		if (dur > 1000) {
			this._frame.last.shift();
		}
	};

	GraphicsContext3D._checkFps = function() {
		var change;

		if (this._frame.fps < this._quality.fpsLow) {
			this._quality.fpsLowThreshold++;
		}

		//must maintain low fps over period of one second
		if (this._quality.fpsLowThreshold > this._frame.fps) {
			this._quality.fpsLowThreshold = 0;
			change = 1 + this._quality.fpsLow / Math.max(this._frame.fps, 1) / 4;
			this._quality.factor *= change;
			this._createBuffer();
		}

		if (this._frame.fps > this._quality.fpsHigh) {
			this._quality.fpsHighThreshold++;
		}

		//must maintain high fps over period of one second
		if (this._quality.fpsHighThreshold > this._frame.fps && this._quality.factor > 1) {
			this._quality.fpsHighThreshold = 0;
			//and even then, only slowly increase the resolution
			this._quality.factor = Math.max(1, this._quality.factor / 1.1);
			this._createBuffer();
		}
	};

	GraphicsContext3D._redraw = function() {

		this._updateFrame();
		if (this._dirty) {
			this._dirty = false;

			if (this._quality.factor > 1) {
				this._quality.ctx.putImageData(this._quality.buffer, 0, 0);
				this.context.drawImage(this._quality.cnv, 0, 0, this.canvas.width, this.canvas.height);
			} else {
				this.context.putImageData(this.buffer, 0, 0);
			}
		}

		this._checkFps();
	};

	return GraphicsContext3D.Constructor;

}());

<commit_msg>#10: depthFunc and depth clear value fixes<commit_after>/*
Copyright (c) 2011 Cimaron Shanahan

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

GraphicsContext3D = (function() {

	function Initializer() {
		//private:
		this.webglCtx = null;
		this.canvas = null;

		this.buffer = null;
		this.context = null;

		this._state = {};
		this._dirty = false;

		this._frame = {};
		this._quality = {};
	}

	var GraphicsContext3D = new jClass('GraphicsContext3D', Initializer);

	//public:

	GraphicsContext3D.GraphicsContext3D = function(webglCtx) {
		var threshold, This;
		this.webglCtx = webglCtx;
		this.canvas = webglCtx.canvas;
		this.context = this.canvas.getContext('2d');

		/*
		//The following attempts to adjust the initial quality setting based
		//the number of pixels in the canvas. This threshold is mostly arbitrary
		//and could stand some more intelligent calculation
		this._quality.startThreshold = 250000;
		if (this.canvas.width * this.canvas.height > this._quality.startThreshold) {
			this._quality.factor = (this.canvas.width * this.canvas.height) / this._quality.startThreshold;
		} else {
			this._quality.factor = 1;
		}
		*/
		this._quality.factor = 1;
		this.setTargetFps(0);

		this._createBuffer();

		//initialize state
		glClearColor(0, 0, 0, 255);
		glClearDepth(1.0);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glViewport(0, 0, this.canvas.width, this.canvas.height);

		This = this;
		setInterval(function() { This._redraw(); }, 0);
	};

	//public:

	GraphicsContext3D.activeTexture = function(texture) {
		glActiveTexture(texture);
	};

	GraphicsContext3D.attachShader = function(program, shader) {
		glAttachShader(program, shader);
	};

	GraphicsContext3D.bindAttribLocation = function(program, index, name) {
		glBindAttribLocation(program, index, name);
	};

	GraphicsContext3D.bindBuffer = function(target, buffer) {
		glBindBuffer(target, buffer);
	};

	GraphicsContext3D.bindTexture = function(target, texture) {
		glBindTexture(target, texture);
	};

	GraphicsContext3D.blendFunc = function(sfactor, dfactor) {
		glBlendFunc(sfactor, dfactor);
	};

	GraphicsContext3D.bufferData = function(target, size, data, usage) {
		glBufferData(target, size, data, usage);
	};

	GraphicsContext3D.bufferSubData = function(target, offset, size, data) {
		glBufferSubData(target, offset, size, data);
	};

	GraphicsContext3D.clear = function(mask) {
		this._dirty = true;
		glClear(mask);
	};

	GraphicsContext3D.clearColor = function(red, green, blue, alpha) {
		glClearColor(red, green, blue, alpha);
	};

	GraphicsContext3D.clearDepth = function(depth) {
		glClearDepth(depth);
	};

	GraphicsContext3D.compileShader = function(shader) {
		glCompileShader(shader);
	};

	GraphicsContext3D.colorMask = function(red, green, blue, alpha) {
		glColorMask(red, green, blue, alpha);
	};

	GraphicsContext3D.createBuffer = function() {
		var buffers = [];
		glGenBuffers(1, buffers);
		return buffers[0][0];
	};

	GraphicsContext3D.createProgram = function() {
		return glCreateProgram();
	};

	GraphicsContext3D.createShader = function(type) {
		return glCreateShader(type);
	};

	GraphicsContext3D.createTexture = function() {
		var textures = [];
		glGenTextures(1, textures);
		return textures[0][0];
	};

	GraphicsContext3D.cullFace = function(mode) {
		glCullFace(mode);
	};

	GraphicsContext3D.depthFunc = function(func) {
		glDepthFunc(func);
	};

	GraphicsContext3D.depthMask = function(flag) {
		glDepthMask(flag);
	};

	GraphicsContext3D.drawArrays = function(mode, first, count) {
		this._dirty = true;
		glDrawArrays(mode, first, count);
	};

	GraphicsContext3D.drawElements = function(mode, count, type, offset) {
		this._dirty = true;
		glDrawElements(mode, count, type, offset);
	};

	GraphicsContext3D.disable = function(cap) {
		glDisable(cap);
	};

	GraphicsContext3D.disableVertexAttribArray = function(index) {
		glDisableVertexAttribArray(index);
	};

	GraphicsContext3D.enable = function(cap) {
		glEnable(cap);
	};

	GraphicsContext3D.enableVertexAttribArray = function(index) {
		glEnableVertexAttribArray(index);
	};

	GraphicsContext3D.frontFace = function(mode) {
		glFrontFace(mode);
	};

	GraphicsContext3D.generateMipmap = function(target) {
		//glGenerateMipmap(target);
	};

	GraphicsContext3D.getAttribLocation = function(program, name) {
		return glGetAttribLocation(program, name);
	};

	GraphicsContext3D.getError = function() {
		return glGetError();
	};

	GraphicsContext3D.getProgramParameter = function(program, pname) {
		var params = [];
		glGetProgramiv(program, pname, params);
		return params[0];
	};

	GraphicsContext3D.getShaderInfoLog = function(shader) {
		var length = [], infoLog = [];
		glGetShaderInfoLog(shader, null, length, infoLog);
		return infoLog[0];
	};

	GraphicsContext3D.getShaderParameter = function(shader, pname) {
		var params = [];
		glGetShaderiv(shader, pname, params);
		return params[0];
	};

	GraphicsContext3D.getUniformLocation = function(program, name) {
		return glGetUniformLocation(program, name);
	};

	GraphicsContext3D.linkProgram = function(program) {
		glLinkProgram(program);
	};

	GraphicsContext3D.pixelStorei = function(pname, param) {
		glPixelStorei(pname, param);
	};

	GraphicsContext3D.shaderSource = function(shader, source) {
		glShaderSource(shader, 1, [source], [source.length]);
	};

	GraphicsContext3D.uniform1i = function(location, v0) {
		glUniform1i(location, v0);
	};

	GraphicsContext3D.uniform1f = function(location, v0) {
		glUniform1f(location, v0);
	};

	GraphicsContext3D.uniform3f = function(location, v0, v1, v2) {
		glUniform3f(location, v0, v1, v2);
	};

	GraphicsContext3D.uniform3fv = function(location, value) {
		glUniform3fv(location, 1, value);
	};

	GraphicsContext3D.uniformMatrix3fv = function(location, transpose, value) {
		glUniformMatrix3fv(location, value.length / 9, transpose, value);
	};

	GraphicsContext3D.uniformMatrix4fv = function(location, transpose, value) {
		glUniformMatrix4fv(location, value.length / 16, transpose, value);
	};

	GraphicsContext3D.useProgram = function(program) {
		glUseProgram(program);
	};

	GraphicsContext3D.texImage2D = function(target, level, internalformat, width, height, border, format, type, source) {
		glTexImage2D(target, level, internalformat, width, height, border, format, type, source);
	};

	GraphicsContext3D.texParameteri = function(target, pname, param) {
		glTexParameteri(target, pname, param);
	};

	GraphicsContext3D.vertexAttribPointer = function(idx, size, type, normalized, stride, offset) {
		glVertexAttribPointer(idx, size, type, normalized, stride, offset);
	};

	GraphicsContext3D.viewport = function(x, y, width, height) {
		x = Math.round(x / this._quality.factor);
		y = Math.round(y / this._quality.factor);
		width = Math.round(width / this._quality.factor);
		height = Math.round(height / this._quality.factor);

		glViewport(x, y, width, height);
	};

	GraphicsContext3D.setTargetFps = function(low, high) {
		this._frame.fps = 0;
		this._frame.last = [];
		this._quality.fpsLow = low;
		this._quality.fpsHigh = high ? high : 1.5 * low;
		this._quality.fpsLowThreshold = 0;
		this._quality.fpsHighThreshold = 0;
	};

	GraphicsContext3D.setQuality = function(q) {
		this._quality.factor = 1 / q;
		this._createBuffer();
	};

	//private:

	GraphicsContext3D._createBuffer = function() {
		var ctx, width, height;

		ctx = cnvgl_context.getCurrentContext();

		if (!this.buffer) {
			this.buffer = this.context.createImageData(this.canvas.width, this.canvas.height);
		}
		if (!this._quality.cnv) {
			this._quality.cnv = document.createElement('canvas');
		}

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

		if (this._quality.factor > 1) {

			width = Math.round(width / this._quality.factor);
			height = Math.round(height / this._quality.factor);
			width = Math.max(width, 1);
			height = Math.max(height, 1);

			this.webglCtx.drawingBufferWidth = width;
			this.webglCtx.drawingBufferHeight = height;

			this._quality.cnv.width = width;
			this._quality.cnv.height = height;
			this._quality.ctx = this._quality.cnv.getContext('2d');
			this.context.mozImageSmoothingEnabled = false;

			this._quality.buffer = this.context.createImageData(width, height);
			ctx.color_buffer = this._quality.buffer.data;

		} else {
			ctx.color_buffer = this.buffer.data;
		}

		ctx.depth_buffer = new Float32Array(width * height);
	};

	GraphicsContext3D._updateFrame = function() {
		var time, dur;
		//update frame counts, fps, etc.
		this._frame.count++;
		time = new Date().getTime();
		this._frame.last.push(time);

		//average over one second period
		dur = time - this._frame.last[0];
		this._frame.fps = 1000 * this._frame.last.length / dur;
		if (dur > 1000) {
			this._frame.last.shift();
		}
	};

	GraphicsContext3D._checkFps = function() {
		var change;

		if (this._frame.fps < this._quality.fpsLow) {
			this._quality.fpsLowThreshold++;
		}

		//must maintain low fps over period of one second
		if (this._quality.fpsLowThreshold > this._frame.fps) {
			this._quality.fpsLowThreshold = 0;
			change = 1 + this._quality.fpsLow / Math.max(this._frame.fps, 1) / 4;
			this._quality.factor *= change;
			this._createBuffer();
		}

		if (this._frame.fps > this._quality.fpsHigh) {
			this._quality.fpsHighThreshold++;
		}

		//must maintain high fps over period of one second
		if (this._quality.fpsHighThreshold > this._frame.fps && this._quality.factor > 1) {
			this._quality.fpsHighThreshold = 0;
			//and even then, only slowly increase the resolution
			this._quality.factor = Math.max(1, this._quality.factor / 1.1);
			this._createBuffer();
		}
	};

	GraphicsContext3D._redraw = function() {

		this._updateFrame();
		if (this._dirty) {
			this._dirty = false;

			if (this._quality.factor > 1) {
				this._quality.ctx.putImageData(this._quality.buffer, 0, 0);
				this.context.drawImage(this._quality.cnv, 0, 0, this.canvas.width, this.canvas.height);
			} else {
				this.context.putImageData(this.buffer, 0, 0);
			}
		}

		this._checkFps();
	};

	return GraphicsContext3D.Constructor;

}());

<|endoftext|>


<commit_before>angular.module('sgw.ui.breadcrumb', [])
.factory('breadcrumbService', ['$log', function($log) {
	var service = {};
	var ensureIdIsRegistered = function(id) {
		if (angular.isUndefined(service[id])) {
			service[id] = [];
		}
	};
	return {
		updateCrumb: function(id, index, update) {
			ensureIdIsRegistered(id);
			var crumb = service[id][index];
			for (var property in update) {
				crumb[property] = update[property];
			}
		},
		set: function(id, crumbs) {
			ensureIdIsRegistered(id);
			service[id] = crumbs;
		},
		get: function(id) {
			ensureIdIsRegistered(id);
//			return angular.copy(service[id]);
			return service[id];
		},
		setLastIndex: function(id, index) {
			ensureIdIsRegistered(id);
			if (service[id].length > 1 + index) {
				service[id].splice(1 + index, service[id].length - index);
			}
		}
	};
}])
.directive('breadcrumbs', ['breadcrumbService', '$log', function(breadcrumbService, $log) {
	return {
		restrict : 'A',
		template : '

{{bc.label}}/{{bc.label}}

',
		replace : true,
		compile : function(tElement, tAttrs) {
			return function($scope, $elem, $attr) {
				var breadcrumbId = $attr['id'];
				var resetCrumbs = function(breadcrumbs) {
					$scope.breadcrumbs = [];
					angular.forEach(breadcrumbs, function(v) {
						$scope.breadcrumbs.push(v);
					});
				};
//				resetCrumbs();
				$scope.unregisterBreadCrumb = function(index) {
					breadcrumbService.setLastIndex(breadcrumbId, index);
//					resetCrumbs();
				};
				$scope.$watch(function() { return breadcrumbService.get(breadcrumbId); }, function(breadcrumbs) {
					resetCrumbs(breadcrumbs);
				}, true);
				// $scope.$on( 'breadcrumbsRefresh',
				// function() {
				// $log.log( "$on" );
				// resetCrumbs();
				// } );
			};
		}
	};
}]);<commit_msg>breadcrumb: remove divider from template.  Now in css in BS3.<commit_after>angular.module('sgw.ui.breadcrumb', [])
.factory('breadcrumbService', ['$log', function($log) {
	var service = {};
	var ensureIdIsRegistered = function(id) {
		if (angular.isUndefined(service[id])) {
			service[id] = [];
		}
	};
	return {
		updateCrumb: function(id, index, update) {
			ensureIdIsRegistered(id);
			var crumb = service[id][index];
			for (var property in update) {
				crumb[property] = update[property];
			}
		},
		set: function(id, crumbs) {
			ensureIdIsRegistered(id);
			service[id] = crumbs;
		},
		get: function(id) {
			ensureIdIsRegistered(id);
//			return angular.copy(service[id]);
			return service[id];
		},
		setLastIndex: function(id, index) {
			ensureIdIsRegistered(id);
			if (service[id].length > 1 + index) {
				service[id].splice(1 + index, service[id].length - index);
			}
		}
	};
}])
.directive('breadcrumbs', ['breadcrumbService', '$log', function(breadcrumbService, $log) {
	return {
		restrict : 'A',
		template : '

{{bc.label}}{{bc.label}}

',
		replace : true,
		compile : function(tElement, tAttrs) {
			return function($scope, $elem, $attr) {
				var breadcrumbId = $attr['id'];
				var resetCrumbs = function(breadcrumbs) {
					$scope.breadcrumbs = [];
					angular.forEach(breadcrumbs, function(v) {
						$scope.breadcrumbs.push(v);
					});
				};
//				resetCrumbs();
				$scope.unregisterBreadCrumb = function(index) {
					breadcrumbService.setLastIndex(breadcrumbId, index);
//					resetCrumbs();
				};
				$scope.$watch(function() { return breadcrumbService.get(breadcrumbId); }, function(breadcrumbs) {
					resetCrumbs(breadcrumbs);
				}, true);
				// $scope.$on( 'breadcrumbsRefresh',
				// function() {
				// $log.log( "$on" );
				// resetCrumbs();
				// } );
			};
		}
	};
}]);<|endoftext|>


<commit_before>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014-2020 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.
 */

(function () {
    'use strict';

    angular.module('pnc.builds').component('pncBuildDetailBrewPushPage', {
      bindings: {
        build: '<',
        brewPushResult: '<'
      },
      templateUrl: 'builds/detail/brew-push/pnc-build-detail-brew-push-page.html',
      controller: ['$scope', Controller]
    });

    function Controller($scope) {
      const $ctrl = this;

      // -- Controller API --

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

      $ctrl.$onInit = () => {
        load($ctrl.brewPushResult);

        $scope.$on('BUILD_PUSH_STATUS_CHANGE', (event, brewPushResult) => {
          if (brewPushResult.buildId === $ctrl.build.id) {
            $scope.$applyAsync(() => load(brewPushResult));
          }
        });
      };

      function load(brewPushResult) {
        if (brewPushResult) {
          $ctrl.data = brewPushResult;
          $ctrl.prefixFilters = 'loggerName.keyword:org.jboss.pnc.causeway|org.jboss.pnc._userlog_.brewpush,level.keyword:INFO|ERROR|WARN';
          $ctrl.matchFilters = `mdc.buildRecord.keyword:${brewPushResult.buildId},mdc.processContext.keyword:${brewPushResult.logContext}`; //`mdc.buildId.keyword:${$ctrl.brewPushResult.buildId}`;
        }
      }
    }

  })();
<commit_msg>NCL-5011 Update bifrost params for single push log<commit_after>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014-2020 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.
 */

(function () {
    'use strict';

    angular.module('pnc.builds').component('pncBuildDetailBrewPushPage', {
      bindings: {
        build: '<',
        brewPushResult: '<'
      },
      templateUrl: 'builds/detail/brew-push/pnc-build-detail-brew-push-page.html',
      controller: ['$scope', Controller]
    });

    function Controller($scope) {
      const $ctrl = this;

      // -- Controller API --

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

      $ctrl.$onInit = () => {
        load($ctrl.brewPushResult);

        $scope.$on('BUILD_PUSH_STATUS_CHANGE', (event, brewPushResult) => {
          if (brewPushResult.buildId === $ctrl.build.id) {
            $scope.$applyAsync(() => load(brewPushResult));
          }
        });
      };

      function load(brewPushResult) {
        if (brewPushResult) {
          $ctrl.data = brewPushResult;
          $ctrl.prefixFilters = 'loggerName.keyword:org.jboss.pnc.causeway|org.jboss.pnc._userlog_.brewpush,level.keyword:INFO|ERROR|WARN';
          $ctrl.matchFilters = `mdc.buildId.keyword:${brewPushResult.buildId},mdc.processContext.keyword:${brewPushResult.logContext}`;
        }
      }
    }

  })();
<|endoftext|>


<commit_before>const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'development';
const browsers = process.env.BROWSERSLIST;

const targets = {};
if (browsers) {
  targets.browsers = browsers;
}
if (env === 'production') {
  targets.uglify = true;
}

const preset = {
  presets: [
    ['env', {
      modules: false,
      targets
    }],
    'stage-2',
    'react'
  ],
  plugins: [
    'transform-decorators-legacy',
    'transform-export-extensions',
    ['transform-runtime', { polyfill: false }]
  ]
};

if (env === 'development') {
  preset.plugins.push('react-hot-loader/babel');
}

if (env === 'production') {
  preset.plugins.push(
    'transform-react-constant-elements',
    'transform-react-inline-elements',
    ['transform-react-remove-prop-types', { mode: 'wrap' }]
  );
}

module.exports = preset;
<commit_msg>build: Enable classes transform for react-hot-loader interop.<commit_after>const env = process.env.BABEL_ENV || process.env.NODE_ENV || 'development';
const browsers = process.env.BROWSERSLIST;

const targets = {};
if (browsers) {
  targets.browsers = browsers;
}
if (env === 'production') {
  targets.uglify = true;
}

const preset = {
  presets: [
    ['env', {
      modules: false,
      loose: env === 'production',
      targets,
      // Force enable the classes transform, react-hot-loader doesn't
      // appear to work well with native classes + arrow functions in
      // transpiled class properties.
      include: ['transform-es2015-classes']
    }],
    'stage-2',
    'react'
  ],
  plugins: [
    'transform-decorators-legacy',
    'transform-export-extensions',
    ['transform-runtime', { polyfill: false }]
  ]
};

if (env === 'development') {
  preset.plugins.push('react-hot-loader/babel');
}

if (env === 'production') {
  preset.plugins.push(
    'transform-react-constant-elements',
    'transform-react-inline-elements',
    ['transform-react-remove-prop-types', { mode: 'wrap' }]
  );
}

module.exports = preset;
<|endoftext|>


<commit_before>allure.api.addTab('xUnit', {
    title: 'xUnit',
    icon: 'fa fa-briefcase',
    route: 'xUnit(/:testcaseId)(/:attachmentId)',
    onEnter: (...routeParams) => new allure.components.TreeLayout({
        routeParams: routeParams,
        tabName: 'xUnit',
        baseUrl: 'xUnit',
        url: 'data/xunit.json'
    })
});
allure.api.addWidget('xunit', allure.components.WidgetStatusView.extend({
    title: 'xunit widget',
    baseUrl: 'xUnit',
    showAllText: 'Show all test suites'
}));<commit_msg>change xunit widget name<commit_after>allure.api.addTab('xUnit', {
    title: 'xUnit',
    icon: 'fa fa-briefcase',
    route: 'xUnit(/:testcaseId)(/:attachmentId)',
    onEnter: (...routeParams) => new allure.components.TreeLayout({
        routeParams: routeParams,
        tabName: 'xUnit',
        baseUrl: 'xUnit',
        url: 'data/xunit.json'
    })
});
allure.api.addWidget('xunit', allure.components.WidgetStatusView.extend({
    title: 'xunit',
    baseUrl: 'xUnit',
    showAllText: 'Show all test suites'
}));<|endoftext|>


<commit_before>import chai from 'chai';
import sinon from 'sinon';
import models from '../../models';
import AdhocModelService from '../../services/AdhocModelService';
import dummyData from '../dummy.json';

const { Group, Message, User } = models;
const { Groups, Messages, Users } = dummyData;
const expect = chai.expect;

describe('AdhocModelService.addUserToGroup', () => {
  const groupId = Groups.validGroup.id;
  before(() => {
    return models.sequelize.truncate({ cascade: true })
    .then(() => {
      return Group.create(Groups.validGroup);
    })
    .then(() => {
      return User.bulkCreate([
        Users.validUser,
        Users.anotherValidUser,
        Users.thirdValidUser
      ], {
        individualHooks: true,
        validate: true
      });
    });
  });
  it('should add a user to a group', () => {
    const username = Users.validUser.username;
    return AdhocModelService.addUserToGroup(username, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasUser(username);
    })
    .then((hasUser) => {
      expect(hasUser).to.be.equal(true);
    });
  });
  it('should add multiple users to a group', () => {
    const usernames = [
      Users.anotherValidUser.username,
      Users.thirdValidUser.username
    ];
    return AdhocModelService.addUserToGroup(usernames, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasUsers(usernames);
    })
    .then((hasUsers) => {
      expect(hasUsers).to.be.equal(true);
    });
  });
  it('should throw error if group does not exist',
  () => {
    const username = Users.validUser.username;
    return AdhocModelService
    .addUserToGroup(username, Groups.anotherValidGroup.id)
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! Group does not exist');
    });
  });
  it('should throw error if username is undefined',
  () => {
    return AdhocModelService
    .addUserToGroup(undefined, groupId)
    .catch((err) => {
      expect(err.code).to.equal(400);
      expect(err.message).to
      .equal('Username is invalid or not defined');
    });
  });

  it('should throw error for failure', () => {
    const stub = sinon.stub(models.Group.prototype, 'addUser');
    stub.rejects();
    return AdhocModelService
    .addUserToGroup('fronesy01', groupId)
    .catch((err) => {
      // eslint-disable-next-line
      expect(err).to.exist;
      stub.restore();
    });
  });
});

describe('AdhocModelService.getAllGroupUsers', () => {
  it('should get all users in a group', () => {
    const groupId = Groups.validGroup.id;
    return AdhocModelService.getAllGroupUsers(groupId)
    .then((usersArray) => {
      expect(usersArray).to.have.lengthOf(3);
      usersArray.forEach((user) => {
        expect(user).to.be.an.instanceof(User);
      });
    });
  });
  it('should throw error if group does not exist',
  () => {
    return AdhocModelService
    .getAllGroupUsers(Groups.anotherValidGroup.id)
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! Group does not exist');
    });
  });
});

describe('AdhocModelService.getUsergroups', () => {
  before(() => {
    return Group.create(Groups.anotherValidGroup)
    .then((group) => {
      return User.findById(Users.validUser.username)
      .then((user) => {
        return user.addGroup(group);
      });
    });
  });
  it('should get all groups of a user', () => {
    const username = Users.validUser.username;
    return AdhocModelService.getUserGroups(username)
    .then((groups) => {
      expect(groups).to.have.lengthOf(2);
      groups.forEach((group) => {
        expect(group).to.be.an.instanceof(Group);
      });
    });
  });
  it('should throw error if user does not exist',
  () => {
    return AdhocModelService
    .getUserGroups('fronesy01')
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! User does not exist');
    });
  });
});

describe('AdhocModelService.removeUserFromGroup', () => {
  const groupId = Groups.validGroup.id;
  it('should remove a user from a group', () => {
    const username = Users.validUser.username;
    return AdhocModelService
    .removeUserFromGroup(username, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasUser(username);
    })
    .then((hasUser) => {
      expect(hasUser).to.equal(false);
    });
  });
  it('should remove multiple users from a group', () => {
    const usernames = [
      Users.anotherValidUser.username,
      Users.thirdValidUser.username
    ];
    return AdhocModelService
    .removeUserFromGroup(usernames, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasUsers(usernames);
    })
    .then((hasUsers) => {
      expect(hasUsers).to.be.equal(false);
    });
  });

  it('should throw error if group does not exist',
  () => {
    const username = Users.validUser.username;
    return AdhocModelService
    .removeUserFromGroup(username, Groups.emptyName.id)
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! Group does not exist');
    });
  });

  it('should throw error for failure',
  () => {
    const stub = sinon.stub(models.Group.prototype, 'removeUser');
    stub.rejects();
    return AdhocModelService
    .removeUserFromGroup('fronesy01', groupId)
    .catch((err) => {
      // eslint-disable-next-line
      expect(err).to.exist;
      stub.restore();
    });
  });
});

describe('AdhocModelService.addMessageToGroup', () => {
  const groupId = Groups.validGroup.id;
  it('should create a message and add to group', () => {
    const message = Messages.validMessage;
    return AdhocModelService
    .addMessageToGroup(message, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasMessage(message.id);
    })
    .then((hasMessage) => {
      expect(hasMessage).to.equal(true);
    });
  });
  it('should create a message and add to group', () => {
    const message = Messages.anotherValidMessage;
    return AdhocModelService
    .addMessageToGroup(message, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasMessage(message.id);
    })
    .then((hasMessages) => {
      expect(hasMessages).to.equal(true);
    });
  });
  it('should create a message and add to group', () => {
    const message = Messages.thirdValidMessage;
    return AdhocModelService
    .addMessageToGroup(message, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasMessage(message.id);
    })
    .then((hasMessages) => {
      expect(hasMessages).to.equal(true);
    });
  });
  it('should throw error if group does not exist',
  () => {
    const message = Messages.thirdValidMessage;
    return AdhocModelService
    .addMessageToGroup(message, Groups.emptyName.id)
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! Group does not exist');
    });
  });
});

describe('AdhocModelService.getGroupMessages', () => {
  it('should get all messages in a group', () => {
    return AdhocModelService.getGroupMessages(Groups.validGroup.id)
    .then((messageArray) => {
      expect(messageArray).to.have.lengthOf(3);
      messageArray.forEach((message) => {
        expect(message).to.be.an.instanceof(Message);
      });
    });
  });
  it('should throw error if group does not exist',
  () => {
    return AdhocModelService
    .getGroupMessages(Groups.emptyName.id)
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! Group does not exist');
    });
  });
});

describe('AdhocModelService.removeMessageFromGroup', () => {
  const groupId = Groups.validGroup.id;
  it('should remove a message from a group', () => {
    const messageId = Messages.validMessage.id;
    return AdhocModelService
    .removeMessageFromGroup(messageId, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasMessage(messageId);
    })
    .then((hasMessage) => {
      expect(hasMessage).to.equal(false);
    });
  });
  it('should remove multiple messages from a group', () => {
    const messageIds = [
      Messages.anotherValidMessage.id,
      Messages.thirdValidMessage.id
    ];
    return AdhocModelService
    .removeMessageFromGroup(messageIds, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasMessages(messageIds);
    })
    .then((hasMessages) => {
      expect(hasMessages).to.be.equal(false);
    });
  });
  it('should throw error if group does not exist',
  () => {
    const messageId = Messages.validMessage.id;
    return AdhocModelService
    .removeMessageFromGroup(messageId, Groups.emptyName.id)
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! Group does not exist');
    });
  });
  it('should throw error for failure',
  () => {
    const stub = sinon.stub(models.Group.prototype, 'removeMessage');
    stub.rejects();
    const messageId = Messages.fourthValidMessage.id;
    return AdhocModelService
    .removeMessageFromGroup(messageId, groupId)
    .catch((err) => {
      // eslint-disable-next-line
      expect(err).to.exist;
      stub.restore();
    });
  });
});
<commit_msg>[test] ensure validation checks are done<commit_after>import chai from 'chai';
import sinon from 'sinon';
import models from '../../models';
import AdhocModelService from '../../services/AdhocModelService';
import dummyData from '../dummy.json';

const { Group, Message, User } = models;
const { Groups, Messages, Users } = dummyData;
const expect = chai.expect;

describe('AdhocModelService.validateInputs', () => {
  it('validates inputs when creating group', () => {
    return AdhocModelService.validateInputs(Group, {
      name: undefined
    })
    .catch((err) => {
      expect(err.message).to
      .equal('Incomplete field; name is required');
    });
  });
  it('validates inputs when creating group', () => {
    return AdhocModelService.validateInputs(Group, {
      name: Groups.twitter.name
    })
    .then((isValid) => {
      expect(isValid).to.equal(true);
    });
  });
  it('validates inputs when creating user', () => {
    return AdhocModelService.validateInputs(User, {
      username: Users.validUser.username,
      phoneNo: Users.validUser.phoneNo
    })
    .catch((err) => {
      expect(err.message).to
      .equal('Username, password, email and phoneNo required');
    });
  });
  it('validates inputs when creating user', () => {
    return AdhocModelService.validateInputs(User, Users.validUser)
    .then((isValid) => {
      expect(isValid).to.equal(true);
    });
  });
});

describe('AdhocModelService.addUserToGroup', () => {
  const groupId = Groups.validGroup.id;
  before(() => {
    return models.sequelize.truncate({ cascade: true })
    .then(() => {
      return Group.create(Groups.validGroup);
    })
    .then(() => {
      return User.bulkCreate([
        Users.validUser,
        Users.anotherValidUser,
        Users.thirdValidUser
      ], {
        individualHooks: true,
        validate: true
      });
    });
  });
  it('should add a user to a group', () => {
    const username = Users.validUser.username;
    return AdhocModelService.addUserToGroup(username, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasUser(username);
    })
    .then((hasUser) => {
      expect(hasUser).to.be.equal(true);
    });
  });
  it('should add multiple users to a group', () => {
    const usernames = [
      Users.anotherValidUser.username,
      Users.thirdValidUser.username
    ];
    return Promise.all([
      AdhocModelService.addUserToGroup(usernames[0], groupId),
      AdhocModelService.addUserToGroup(usernames[1], groupId)
    ])
    .then(() => {
      return Group.findById(groupId)
      .then((group) => {
        return group.hasUsers(usernames);
      });
    })
    .then((hasUsers) => {
      expect(hasUsers).to.be.equal(true);
    });
  });
  it('should throw error if group does not exist',
  () => {
    const username = Users.validUser.username;
    return AdhocModelService
    .addUserToGroup(username, Groups.anotherValidGroup.id)
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! Group does not exist');
    });
  });
  it('should throw error if username is undefined',
  () => {
    return AdhocModelService
    .addUserToGroup(undefined, groupId)
    .catch((err) => {
      expect(err.code).to.equal(400);
      expect(err.message).to
      .equal('Username is invalid or not defined');
    });
  });
  it('should throw error if username is already in group',
  () => {
    const username = Users.validUser.username;
    return AdhocModelService
    .addUserToGroup(username, groupId)
    .catch((err) => {
      expect(err.code).to.equal(400);
      expect(err.message).to
      .equal('User already belong to group');
    });
  });
  it('should throw error for failure', () => {
    const stub = sinon.stub(models.Group.prototype, 'addUser');
    stub.rejects();
    return AdhocModelService
    .addUserToGroup('fronesy01', groupId)
    .catch((err) => {
      // eslint-disable-next-line
      expect(err).to.exist;
      stub.restore();
    });
  });
});

describe('AdhocModelService.getAllGroupUsers', () => {
  it('should get all users in a group', () => {
    const groupId = Groups.validGroup.id;
    return AdhocModelService.getAllGroupUsers(groupId)
    .then((usersArray) => {
      expect(usersArray).to.have.lengthOf(3);
      usersArray.forEach((user) => {
        expect(user).to.be.an.instanceof(User);
      });
    });
  });
  it('should throw error if group does not exist',
  () => {
    return AdhocModelService
    .getAllGroupUsers(Groups.anotherValidGroup.id)
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! Group does not exist');
    });
  });
});

describe('AdhocModelService.getUsergroups', () => {
  before(() => {
    return Group.create(Groups.anotherValidGroup)
    .then((group) => {
      return User.findById(Users.validUser.username)
      .then((user) => {
        return user.addGroup(group);
      });
    });
  });
  it('should get all groups of a user', () => {
    const username = Users.validUser.username;
    return AdhocModelService.getUserGroups(username)
    .then((groups) => {
      expect(groups).to.have.lengthOf(2);
      groups.forEach((group) => {
        expect(group).to.be.an.instanceof(Group);
      });
    });
  });
  it('should throw error if user does not exist',
  () => {
    return AdhocModelService
    .getUserGroups('fronesy01')
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! User does not exist');
    });
  });
});

describe('AdhocModelService.removeUserFromGroup', () => {
  const groupId = Groups.validGroup.id;
  it('should remove a user from a group', () => {
    const username = Users.validUser.username;
    return AdhocModelService
    .removeUserFromGroup(username, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasUser(username);
    })
    .then((hasUser) => {
      expect(hasUser).to.equal(false);
    });
  });
  it('should remove multiple users from a group', () => {
    const usernames = [
      Users.anotherValidUser.username,
      Users.thirdValidUser.username
    ];
    return AdhocModelService
    .removeUserFromGroup(usernames, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasUsers(usernames);
    })
    .then((hasUsers) => {
      expect(hasUsers).to.be.equal(false);
    });
  });

  it('should throw error if group does not exist',
  () => {
    const username = Users.validUser.username;
    return AdhocModelService
    .removeUserFromGroup(username, Groups.emptyName.id)
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! Group does not exist');
    });
  });

  it('should throw error if user does not exist in group',
  () => {
    const username = Users.validUser.username;
    return AdhocModelService
    .removeUserFromGroup(username, groupId)
    .catch((err) => {
      expect(err.code).to.equal(400);
      expect(err.message).to
      .equal('User does not exist in group');
    });
  });

  it('should throw error for failure',
  () => {
    const stub = sinon.stub(models.Group.prototype, 'removeUser');
    stub.rejects();
    return AdhocModelService
    .removeUserFromGroup('fronesy01', groupId)
    .catch((err) => {
      // eslint-disable-next-line
      expect(err).to.exist;
      stub.restore();
    });
  });
});

describe('AdhocModelService.addMessageToGroup', () => {
  const groupId = Groups.validGroup.id;
  it('should create a message and add to group', () => {
    const message = Messages.validMessage;
    return AdhocModelService
    .addMessageToGroup(message, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasMessage(message.id);
    })
    .then((hasMessage) => {
      expect(hasMessage).to.equal(true);
    });
  });
  it('should create a message and add to group', () => {
    const message = Messages.anotherValidMessage;
    return AdhocModelService
    .addMessageToGroup(message, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasMessage(message.id);
    })
    .then((hasMessages) => {
      expect(hasMessages).to.equal(true);
    });
  });
  it('should create a message and add to group', () => {
    const message = Messages.thirdValidMessage;
    return AdhocModelService
    .addMessageToGroup(message, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasMessage(message.id);
    })
    .then((hasMessages) => {
      expect(hasMessages).to.equal(true);
    });
  });
  it('should throw error if group does not exist',
  () => {
    const message = Messages.thirdValidMessage;
    return AdhocModelService
    .addMessageToGroup(message, Groups.emptyName.id)
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! Group does not exist');
    });
  });
  it('should throw error if message does not have text',
  () => {
    const message = { text: undefined };
    return AdhocModelService
    .addMessageToGroup(message, groupId)
    .catch((err) => {
      expect(err.code).to.equal(400);
      expect(err.message).to
      .equal('Incomplete field; text is required');
    });
  });
});

describe('AdhocModelService.getGroupMessages', () => {
  it('should get all messages in a group', () => {
    return AdhocModelService.getGroupMessages(Groups.validGroup.id)
    .then((messageArray) => {
      expect(messageArray).to.have.lengthOf(3);
      messageArray.forEach((message) => {
        expect(message).to.be.an.instanceof(Message);
      });
    });
  });
  it('should throw error if group does not exist',
  () => {
    return AdhocModelService
    .getGroupMessages(Groups.emptyName.id)
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! Group does not exist');
    });
  });
});

describe('AdhocModelService.removeMessageFromGroup', () => {
  const groupId = Groups.validGroup.id;
  it('should remove a message from a group', () => {
    const messageId = Messages.validMessage.id;
    return AdhocModelService
    .removeMessageFromGroup(messageId, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasMessage(messageId);
    })
    .then((hasMessage) => {
      expect(hasMessage).to.equal(false);
    });
  });
  it('should remove multiple messages from a group', () => {
    const messageIds = [
      Messages.anotherValidMessage.id,
      Messages.thirdValidMessage.id
    ];
    return AdhocModelService
    .removeMessageFromGroup(messageIds, groupId)
    .then(() => {
      return Group.findById(groupId);
    })
    .then((group) => {
      return group.hasMessages(messageIds);
    })
    .then((hasMessages) => {
      expect(hasMessages).to.be.equal(false);
    });
  });
  it('should throw error if group does not exist',
  () => {
    const messageId = Messages.validMessage.id;
    return AdhocModelService
    .removeMessageFromGroup(messageId, Groups.emptyName.id)
    .catch((err) => {
      expect(err.code).to.equal(404);
      expect(err.message).to
      .equal('Error! Group does not exist');
    });
  });
  it('should throw error for failure',
  () => {
    const stub = sinon.stub(models.Group.prototype, 'removeMessage');
    stub.rejects();
    const messageId = Messages.fourthValidMessage.id;
    return AdhocModelService
    .removeMessageFromGroup(messageId, groupId)
    .catch((err) => {
      // eslint-disable-next-line
      expect(err).to.exist;
      stub.restore();
    });
  });
});
<|endoftext|>


<commit_before>/**
 * @file voyager.js Exported methods for voyager in a node environment.
 * @module {Object} voyager
 */

/**
 * Module dependencies
 */
var colors = require('colors')
  , del = require('del')
  , fs = require('graceful-fs')
  , path = require('path')
  , Pinwheel = require('pinwheel')({ mark: '⚡' })
  , Promise = require('es6-promise').Promise
  , requireDir = require('require-dir')
  , vfs = require('vinyl-fs')

  , defaults = {
      spin: true
    , namespaces: []
    };

function addNS(ns, args) {
  var tasks = []
    , i = 0
    , l = voyager.namespaces_[ns].length;
  for (i; i < l; i++) {
    var t = voyager.namespaces_[ns][i];
    if (typeof voyager.tasks_[t] === 'function') {
      tasks.push(addTask(t, args));
    }
  }
  return Promise.resolve(tasks);
}

function addTask(id, args) {
  new Promise(function (done, fail) {
    voyager.tasks_[id].call(voyager, args).then(done);
  });
}

/**
 * Exported voyager namespace
 * @namespace
 */
var voyager = Object.defineProperties({}, {

  /**
   * Immutable string representing the build path
   * @member {string}
   * @public
   */
  BLD: {
    value: process.cwd() + '/build'
  }

  /**
   * Immutable string representing the current working directory
   * @member {string}
   * @public
   */
, CWD: {
    value: process.cwd()
  }

  /**
   * Immutable string represeting the tempory build path
   * @member {string}
   * @public
   */
, TMP: {
    value: process.cwd() + '/.dev'
  }

  /**
   * Immutable string representing the source directory path
   * @member {string}
   * @public
   */
, SRC: {
    value: process.cwd() + '/src'
  }

});

/**
 * Namespace for task namespaces
 * @member {Object}
 * @private
 */
voyager.namespaces_ = {};

/**
 * Namespace for registered tasks
 * @member {Object}
 * @private
 */
voyager.tasks_ = {};

/**
 * Attempts to load all known voyager tasks. Order is as follows:
 * 1) Default internal voyager tasks
 * 2) voyager-* tasks installed via npm
 * 3) User defined tasks within voyager application
 * @method
 * @private
 */
voyager.loadTasks_ = function () {
  // load default tasks
  requireDir('./tasks');

  // load installed voyager tasks
  var pkg = JSON.parse(fs.readFileSync(this.CWD + '/package.json', { encoding: 'utf8' }))
    , scopes = ['dependencies', 'devDependencies'];
  for (var i = 0, l = scopes.length; i < l; i++) {
    if (pkg[scopes[i]]) {
      for (var key in pkg[scopes[i]]) {
        if (/^voyager\-/.test(key)) {
          require(this.CWD + '/node_modules/' + key)(this);
        }
      }
    }
  }

  // try loading any user defined tasks
  try {
    requireDir(this.CWD + '/tasks');
  } catch (e) {
    if (e.errno !== 34) {
      console.log(e);
    }
  }
};

/**
 * Creates a production ready build
 * Runs prebuild, build
 * @method
 * @public
 * @param {Function} [done=function(){}] - Optional callback
 */
voyager.build = function (done) {
  done = done || function () {};
  this.loadTasks_();
  this.clean()
    .then(this.run.bind(this, ['read', 'transform', 'write', 'build']))
    .then(done);
};

/**
 * Cleans both the build and prebuild directories
 * @method
 * @public
 * @returns {Promise}
 */
voyager.clean = function () {
  return new Promise(function (done, fail) {
    del([voyager.TMP, voyager.BLD], done);
  });
};

voyager.dest = function (out, options) {
  return vfs.dest(out, options);
};

voyager.in = function (paths) {
  if (!Array.isArray(paths)) paths = [paths];
  paths = paths.map(function (p) {
    return path.relative(voyager.CWD, path.join(voyager.SRC, p));
  });
  return vfs.src(paths);
};

voyager.in.src = function (paths) {
  return voyager.in.call(this, paths);
};

voyager.in.dev = function (paths) {
  if (!Array.isArray(paths)) paths = [paths];
  paths = paths.map(function (p) {
    return path.relative(voyager.CWD, path.join(voyager.TMP, p));
  });
  return vfs.src(paths);
};

voyager.out = function (p) {
  p = p || '';
  return vfs.dest(path.relative(voyager.CWD, path.join(voyager.BLD, p)));
};

voyager.out.bld = function (p) {
  return voyager.out.call(this, p);
};

voyager.out.dev = function (p) {
  p = p || '';
  return vfs.dest(path.relative(voyager.CWD, path.join(voyager.TMP, p)));
};

/**
 * Run a registered task
 * @method
 * @public
 * @param {string|Array} id - The task(s)/namespace(s) to run
 */
voyager.run = function (id) {
  var ids = Array.isArray(id) ? id : [id]
    , tasks = []
    , watches = [];
  ids.forEach(function (name) {
    if (name in voyager.namespaces_) {
      voyager.namespaces_[name].forEach(function (t) {
        if (name === 'watch') {
          watches.push(t);
        } else {
          tasks.push(t);
        }
      });
    } else if (name in voyager.tasks_) {
      tasks.push(name);
    } else {
      console.log('No registered tasks under name ' + name + ', skipping.');
    }
  });
  return tasks.reduce(function (sequence, task) {
    return sequence.then(voyager.tasks_[task].bind(voyager));
  }, Promise.resolve()).then(function () {
    watches.forEach(function (t) {
      voyager.tasks_[t].call(voyager);
    });
  });
};

voyager.src = function (glob, options) {
  return vfs.src(glob, options);
};

/**
 * Builds project into temporary directory and starts a static server
 * Runs prebuild, serve, watch
 * @method
 * @public
 */
voyager.start = function (done) {
  done = done || function () {};
  this.loadTasks_();
  this.clean()
    .then(this.run.bind(this, ['read', 'transform', 'write', 'serve', 'watch']))
    .then(done);
};

/**
 * Registers a task in the _tasks namespace. Tasks are automatically wrapped
 * in a Promise for chained execution.
 * @method
 * @public
 * @param {string} id - The name under which this task will be registered
 * @param {string|Array} ns - Namespace(s) this task belongs to
 * @param {Function} func - The task definition
 * @param {Object} [opts={}] - Options for this task
 * @returns {Promise}
 */
voyager.task = function (id, ns, func, opts) {
  if (typeof ns === 'function') {
    opts = func || {};
    func = ns;
    ns = 'ns';
  } else {
    opts = opts || {};
  }
  var options = {}
    , key
    , wheel = new Pinwheel('TASK: ' + id);
  // extend default options
  if (ns.indexOf('watch') > 0 || ns === 'watch') options.spin = false;
  for (key in defaults) {
    var v = defaults[key];
    if (opts.hasOwnProperty(key)) {
      v = opts[key];
    }
    options[key] = v;
  }
  // store task id in given namespace
  if (Array.isArray(ns)) {
    for (var i = 0, l = ns.length; i < l; i++) {
      if (!this.namespaces_[ns[i]]) this.namespaces_[ns[i]] = [];
      if (this.namespaces_[ns[i]].indexOf(id) === -1) {
        this.namespaces_[ns[i]].push(id);
      }
    }
  } else {
    if (!this.namespaces_[ns]) this.namespaces_[ns] = [];
    this.namespaces_[ns].push(id);
  }
  // register the task
  this.tasks_[id] = function () {
    var start = Date.now();
    if (options.spin) {
      wheel.start();
    } else {
      console.log('starting ' + id.grey + '...');
    }
    var args = Array.prototype.slice.call(arguments);
    return new Promise(function (resolve, reject) {
      func.call(voyager, function (err) {
        if (err) return reject(err);
        return resolve();
      }, args);
    }).then(function () {
      if (options.spin) return wheel.stop();
      return console.log(
        'finished ' + id.green + ' ' + ((Date.now() - start) + 'ms').grey
      );
    })['catch'](function (err) {
      if (options.spin) {
        wheel.stop(err);
      } else {
        console.log(
          'ERROR'.inverse.red + ' ' + id.red + ' '
        + ((Date.now() - start) + 'ms').grey
        );
      }
      return console.error(err);
    });
  };
};

voyager.watch = function (paths, tasks) {
  if (!Array.isArray(paths)) paths = [paths];
  paths = paths.map(function (p) {
    return path.relative(voyager.CWD, path.join(voyager.SRC, p));
  });
  if (typeof tasks === 'undefined') return false;
  if (typeof tasks === 'function') {
    return vfs.watch(paths, tasks);
  }
  return vfs.watch(paths, this.run.bind(this, tasks));
};

module.exports = voyager;
<commit_msg>add override flag to watch<commit_after>/**
 * @file voyager.js Exported methods for voyager in a node environment.
 * @module {Object} voyager
 */

/**
 * Module dependencies
 */
var colors = require('colors')
  , del = require('del')
  , fs = require('graceful-fs')
  , path = require('path')
  , Pinwheel = require('pinwheel')({ mark: '⚡' })
  , Promise = require('es6-promise').Promise
  , requireDir = require('require-dir')
  , vfs = require('vinyl-fs')

  , defaults = {
      spin: true
    , namespaces: []
    };

function addNS(ns, args) {
  var tasks = []
    , i = 0
    , l = voyager.namespaces_[ns].length;
  for (i; i < l; i++) {
    var t = voyager.namespaces_[ns][i];
    if (typeof voyager.tasks_[t] === 'function') {
      tasks.push(addTask(t, args));
    }
  }
  return Promise.resolve(tasks);
}

function addTask(id, args) {
  new Promise(function (done, fail) {
    voyager.tasks_[id].call(voyager, args).then(done);
  });
}

/**
 * Exported voyager namespace
 * @namespace
 */
var voyager = Object.defineProperties({}, {

  /**
   * Immutable string representing the build path
   * @member {string}
   * @public
   */
  BLD: {
    value: process.cwd() + '/build'
  }

  /**
   * Immutable string representing the current working directory
   * @member {string}
   * @public
   */
, CWD: {
    value: process.cwd()
  }

  /**
   * Immutable string represeting the tempory build path
   * @member {string}
   * @public
   */
, TMP: {
    value: process.cwd() + '/.dev'
  }

  /**
   * Immutable string representing the source directory path
   * @member {string}
   * @public
   */
, SRC: {
    value: process.cwd() + '/src'
  }

});

/**
 * Namespace for task namespaces
 * @member {Object}
 * @private
 */
voyager.namespaces_ = {};

/**
 * Namespace for registered tasks
 * @member {Object}
 * @private
 */
voyager.tasks_ = {};

/**
 * Attempts to load all known voyager tasks. Order is as follows:
 * 1) Default internal voyager tasks
 * 2) voyager-* tasks installed via npm
 * 3) User defined tasks within voyager application
 * @method
 * @private
 */
voyager.loadTasks_ = function () {
  // load default tasks
  requireDir('./tasks');

  // load installed voyager tasks
  var pkg = JSON.parse(fs.readFileSync(this.CWD + '/package.json', { encoding: 'utf8' }))
    , scopes = ['dependencies', 'devDependencies'];
  for (var i = 0, l = scopes.length; i < l; i++) {
    if (pkg[scopes[i]]) {
      for (var key in pkg[scopes[i]]) {
        if (/^voyager\-/.test(key)) {
          require(this.CWD + '/node_modules/' + key)(this);
        }
      }
    }
  }

  // try loading any user defined tasks
  try {
    requireDir(this.CWD + '/tasks');
  } catch (e) {
    if (e.errno !== 34) {
      console.log(e);
    }
  }
};

/**
 * Creates a production ready build
 * Runs prebuild, build
 * @method
 * @public
 * @param {Function} [done=function(){}] - Optional callback
 */
voyager.build = function (done) {
  done = done || function () {};
  this.loadTasks_();
  this.clean()
    .then(this.run.bind(this, ['read', 'transform', 'write', 'build']))
    .then(done);
};

/**
 * Cleans both the build and prebuild directories
 * @method
 * @public
 * @returns {Promise}
 */
voyager.clean = function () {
  return new Promise(function (done, fail) {
    del([voyager.TMP, voyager.BLD], done);
  });
};

voyager.dest = function (out, options) {
  return vfs.dest(out, options);
};

voyager.in = function (paths) {
  if (!Array.isArray(paths)) paths = [paths];
  paths = paths.map(function (p) {
    return path.relative(voyager.CWD, path.join(voyager.SRC, p));
  });
  return vfs.src(paths);
};

voyager.in.src = function (paths) {
  return voyager.in.call(this, paths);
};

voyager.in.dev = function (paths) {
  if (!Array.isArray(paths)) paths = [paths];
  paths = paths.map(function (p) {
    return path.relative(voyager.CWD, path.join(voyager.TMP, p));
  });
  return vfs.src(paths);
};

voyager.out = function (p) {
  p = p || '';
  return vfs.dest(path.relative(voyager.CWD, path.join(voyager.BLD, p)));
};

voyager.out.bld = function (p) {
  return voyager.out.call(this, p);
};

voyager.out.dev = function (p) {
  p = p || '';
  return vfs.dest(path.relative(voyager.CWD, path.join(voyager.TMP, p)));
};

/**
 * Run a registered task
 * @method
 * @public
 * @param {string|Array} id - The task(s)/namespace(s) to run
 */
voyager.run = function (id) {
  var ids = Array.isArray(id) ? id : [id]
    , tasks = []
    , watches = [];
  ids.forEach(function (name) {
    if (name in voyager.namespaces_) {
      voyager.namespaces_[name].forEach(function (t) {
        if (name === 'watch') {
          watches.push(t);
        } else {
          tasks.push(t);
        }
      });
    } else if (name in voyager.tasks_) {
      tasks.push(name);
    } else {
      console.log('No registered tasks under name ' + name + ', skipping.');
    }
  });
  return tasks.reduce(function (sequence, task) {
    return sequence.then(voyager.tasks_[task].bind(voyager));
  }, Promise.resolve()).then(function () {
    watches.forEach(function (t) {
      voyager.tasks_[t].call(voyager);
    });
  });
};

voyager.src = function (glob, options) {
  return vfs.src(glob, options);
};

/**
 * Builds project into temporary directory and starts a static server
 * Runs prebuild, serve, watch
 * @method
 * @public
 */
voyager.start = function (done) {
  done = done || function () {};
  this.loadTasks_();
  this.clean()
    .then(this.run.bind(this, ['read', 'transform', 'write', 'serve', 'watch']))
    .then(done);
};

/**
 * Registers a task in the _tasks namespace. Tasks are automatically wrapped
 * in a Promise for chained execution.
 * @method
 * @public
 * @param {string} id - The name under which this task will be registered
 * @param {string|Array} ns - Namespace(s) this task belongs to
 * @param {Function} func - The task definition
 * @param {Object} [opts={}] - Options for this task
 * @returns {Promise}
 */
voyager.task = function (id, ns, func, opts) {
  if (typeof ns === 'function') {
    opts = func || {};
    func = ns;
    ns = 'ns';
  } else {
    opts = opts || {};
  }
  var options = {}
    , key
    , wheel = new Pinwheel('TASK: ' + id);
  // extend default options
  if (ns.indexOf('watch') > 0 || ns === 'watch') options.spin = false;
  for (key in defaults) {
    var v = defaults[key];
    if (opts.hasOwnProperty(key)) {
      v = opts[key];
    }
    options[key] = v;
  }
  // store task id in given namespace
  if (Array.isArray(ns)) {
    for (var i = 0, l = ns.length; i < l; i++) {
      if (!this.namespaces_[ns[i]]) this.namespaces_[ns[i]] = [];
      if (this.namespaces_[ns[i]].indexOf(id) === -1) {
        this.namespaces_[ns[i]].push(id);
      }
    }
  } else {
    if (!this.namespaces_[ns]) this.namespaces_[ns] = [];
    this.namespaces_[ns].push(id);
  }
  // register the task
  this.tasks_[id] = function () {
    var start = Date.now();
    if (options.spin) {
      wheel.start();
    } else {
      console.log('starting ' + id.grey + '...');
    }
    var args = Array.prototype.slice.call(arguments);
    return new Promise(function (resolve, reject) {
      func.call(voyager, function (err) {
        if (err) return reject(err);
        return resolve();
      }, args);
    }).then(function () {
      if (options.spin) return wheel.stop();
      return console.log(
        'finished ' + id.green + ' ' + ((Date.now() - start) + 'ms').grey
      );
    })['catch'](function (err) {
      if (options.spin) {
        wheel.stop(err);
      } else {
        console.log(
          'ERROR'.inverse.red + ' ' + id.red + ' '
        + ((Date.now() - start) + 'ms').grey
        );
      }
      return console.error(err);
    });
  };
};

voyager.watch = function (paths, tasks, override) {
  override = override || false;
  if (!Array.isArray(paths)) paths = [paths];
  paths = paths.map(function (p) {
    var b = override ? '' : voyager.SRC;
    return path.relative(voyager.CWD, path.join(b, p));
  });
  if (typeof tasks === 'undefined') return false;
  if (typeof tasks === 'function') {
    return vfs.watch(paths, tasks);
  }
  return vfs.watch(paths, this.run.bind(this, tasks));
};

module.exports = voyager;
<|endoftext|>