<commit_before>'use strict';

angular.module('MyApp.controllers')
.value('BASE_URL', 'https://noticeapp.firebaseio.com/')
.controller('DashboardCtrl', function($firebase, $scope, Auth, md5, $ionicModal, User, $http) {
    var noticeRef = new Firebase('https://trynotice.firebaseio.com/notifications');
    $scope.notifications = $firebase(noticeRef);

    $scope.email = Auth.currentUser.email;
    $scope.message = '';
    $scope.activityName = '';
    $scope.isStudent = /([\._a-zA-Z0-9-]+@students.d211.org)/.test($scope.email);

    $http.get(User.getSubscriptions())
    .success(function(data) {
        if(data == null) {
            $scope.subscriptions = [{ id: 1, name: 'Math Team', color: '#43cee6', isChecked: false },
            { id: 2, name: 'Basketball', color: '#4a87ee', isChecked: false },
            { id: 3, name: 'Horticulture Club', color: '#ef4e3a', isChecked: false },
            { id: 4, name: 'Science Olympiad', color: '#8a6de9', isChecked: false }];
        }

        else {
            $scope.subscriptions = data;
        }
    });

    $scope.gravatarURL = 'http://www.gravatar.com/avatar/' + md5.createHash($scope.email);

    $scope.manage = function() {
        User.manageSubscriptions($scope.subscriptions);
    };

    $scope.postNotification = function(message, tag, color) {
        $scope.notifications.$add({message: message, createdBy: $scope.email, gravatarURL: $scope.gravatarURL, dateCreated: Date.now(), tag: tag, color: color});
  	    $scope.message = null;
    };

    $scope.getGravatar = function(md5) {
        return 'http://www.gravatar.com/avatar/' + notifications.md5;
    };

    $ionicModal.fromTemplateUrl('templates/modal.html', {
        scope: $scope
    }).then(function(modal) {
        $scope.modal = modal;
    });

    $scope.filterSubscriptions = function(index) {
        console.log(User.getSubscriptions())
        console.log(index)
        if(User.getSubscriptions()[0].name == $scope.notifications[index].tag) {
            return true;
        }
        else {
            return false;
        }
    };
})
.filter('reverse', function() {
      function toArray(list) {
         var k, out = [];
         if( list ) {
            if( angular.isArray(list) ) {
               out = list;
            }
            else if( typeof(list) === 'object' ) {
               for (k in list) {
                  if (list.hasOwnProperty(k)) { out.push(list[k]); }
               }
            }
         }
         return out;
      }
      return function(items) {
         return toArray(items).slice().reverse();
      };
});
<commit_msg>Update dashboard-controller.js<commit_after>'use strict';

angular.module('MyApp.controllers')
.value('BASE_URL', 'https://noticeapp.firebaseio.com/')
.controller('DashboardCtrl', function($firebase, $scope, Auth, md5, $ionicModal, User, $http) {
    var noticeRef = new Firebase('https://trynotice.firebaseio.com/notifications');
    $scope.notifications = $firebase(noticeRef);

    $scope.email = Auth.currentUser.email;
    $scope.message = '';
    $scope.activityName = '';
    $scope.isStudent = /([\._a-zA-Z0-9-]+@students.d211.org)/.test($scope.email);

    $http.get(User.getSubscriptions())
    .success(function(data) {
        if(data == null) {
            $scope.subscriptions = [{ id: 1, name: 'Math Team', color: '#43cee6', isChecked: false },
            { id: 2, name: 'Basketball', color: '#4a87ee', isChecked: false },
            { id: 3, name: 'Horticulture Club', color: '#ef4e3a', isChecked: false },
            { id: 4, name: 'Science Olympiad', color: '#8a6de9', isChecked: false }];
        }

        else {
            $scope.subscriptions = data;
        }
    });

    $scope.gravatarURL = 'http://www.gravatar.com/avatar/' + md5.createHash($scope.email);

    $scope.manage = function() {
        User.manageSubscriptions($scope.subscriptions);
    };

    $scope.postNotification = function(message, tag, color) {
        if (tag != null)
        {
             $scope.notifications.$add({message: message, createdBy: $scope.email, gravatarURL: $scope.gravatarURL, dateCreated: Date.now(), tag: tag, color: color});
  	    $scope.message = null;
        }
    };

    $scope.getGravatar = function(md5) {
        return 'http://www.gravatar.com/avatar/' + notifications.md5;
    };

    $ionicModal.fromTemplateUrl('templates/modal.html', {
        scope: $scope
    }).then(function(modal) {
        $scope.modal = modal;
    });

    $scope.filterSubscriptions = function(index) {
        console.log(User.getSubscriptions())
        console.log(index)
        if(User.getSubscriptions()[0].name == $scope.notifications[index].tag) {
            return true;
        }
        else {
            return false;
        }
    };
})
.filter('reverse', function() {
      function toArray(list) {
         var k, out = [];
         if( list ) {
            if( angular.isArray(list) ) {
               out = list;
            }
            else if( typeof(list) === 'object' ) {
               for (k in list) {
                  if (list.hasOwnProperty(k)) { out.push(list[k]); }
               }
            }
         }
         return out;
      }
      return function(items) {
         return toArray(items).slice().reverse();
      };
});
<|endoftext|>


<commit_before>/* @flow */

import deepClone from "lodash/lang/cloneDeep";
import sourceMapSupport from "source-map-support";
import * as registerCache from "./cache";
import extend from "lodash/object/extend";
import * as babel from "babel-core";
import each from "lodash/collection/each";
import { util, OptionManager } from "babel-core";
import fs from "fs";
import path from "path";

sourceMapSupport.install({
  handleUncaughtExceptions: false,
  retrieveSourceMap(source) {
    let map = maps && maps[source];
    if (map) {
      return {
        url: null,
        map: map
      };
    } else {
      return null;
    }
  }
});

registerCache.load();
let cache = registerCache.get();

let transformOpts = {};

let ignore;
let only;

let oldHandlers   = {};
let maps          = {};

let cwd = process.cwd();

function getRelativePath(filename){
  return path.relative(cwd, filename);
}

function mtime(filename) {
  return +fs.statSync(filename).mtime;
}

function compile(filename) {
  let result;

  let optsManager = new OptionManager;

  // merge in base options and resolve all the plugins and presets relative to this file
  optsManager.mergeOptions(deepClone(transformOpts), "base", null, path.dirname(filename));

  let opts = optsManager.init({ filename });

  let cacheKey = `${JSON.stringify(opts)}:${babel.version}`;

  let env = process.env.BABEL_ENV || process.env.NODE_ENV;
  if (env) cacheKey += `:${env}`;

  if (cache) {
    let cached = cache[cacheKey];
    if (cached && cached.mtime === mtime(filename)) {
      result = cached;
    }
  }

  if (!result) {
    result = babel.transformFileSync(filename, extend(opts, {
      sourceMap: "both",
      ast:       false
    }));
  }

  if (cache) {
    cache[cacheKey] = result;
    result.mtime = mtime(filename);
  }

  maps[filename] = result.map;

  return result.code;
}

function shouldIgnore(filename) {
  if (!ignore && !only) {
    return getRelativePath(filename).split(path.sep).indexOf("node_modules") >= 0;
  } else {
    return util.shouldIgnore(filename, ignore || [], only);
  }
}

function loader(m, filename) {
  m._compile(compile(filename), filename);
}

function registerExtension(ext) {
  let old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"];

  require.extensions[ext] = function (m, filename) {
    if (shouldIgnore(filename)) {
      old(m, filename);
    } else {
      loader(m, filename, old);
    }
  };
}

function hookExtensions(_exts) {
  each(oldHandlers, function (old, ext) {
    if (old === undefined) {
      delete require.extensions[ext];
    } else {
      require.extensions[ext] = old;
    }
  });

  oldHandlers = {};

  each(_exts, function (ext) {
    oldHandlers[ext] = require.extensions[ext];
    registerExtension(ext);
  });
}

hookExtensions(util.canCompile.EXTENSIONS);

export default function (opts?: Object = {}) {
  if (opts.only != null) only = util.arrayify(opts.only, util.regexify);
  if (opts.ignore != null) ignore = util.arrayify(opts.ignore, util.regexify);

  if (opts.extensions) hookExtensions(util.arrayify(opts.extensions));

  if (opts.cache === false) cache = null;

  delete opts.extensions;
  delete opts.ignore;
  delete opts.cache;
  delete opts.only;

  extend(transformOpts, opts);
}
<commit_msg>Disable babelrc processing on the already-processed configuration - fixes T6690<commit_after>/* @flow */

import deepClone from "lodash/lang/cloneDeep";
import sourceMapSupport from "source-map-support";
import * as registerCache from "./cache";
import extend from "lodash/object/extend";
import * as babel from "babel-core";
import each from "lodash/collection/each";
import { util, OptionManager } from "babel-core";
import fs from "fs";
import path from "path";

sourceMapSupport.install({
  handleUncaughtExceptions: false,
  retrieveSourceMap(source) {
    let map = maps && maps[source];
    if (map) {
      return {
        url: null,
        map: map
      };
    } else {
      return null;
    }
  }
});

registerCache.load();
let cache = registerCache.get();

let transformOpts = {};

let ignore;
let only;

let oldHandlers   = {};
let maps          = {};

let cwd = process.cwd();

function getRelativePath(filename){
  return path.relative(cwd, filename);
}

function mtime(filename) {
  return +fs.statSync(filename).mtime;
}

function compile(filename) {
  let result;

  let optsManager = new OptionManager;

  // merge in base options and resolve all the plugins and presets relative to this file
  optsManager.mergeOptions(deepClone(transformOpts), "base", null, path.dirname(filename));

  let opts = optsManager.init({ filename });

  let cacheKey = `${JSON.stringify(opts)}:${babel.version}`;

  let env = process.env.BABEL_ENV || process.env.NODE_ENV;
  if (env) cacheKey += `:${env}`;

  if (cache) {
    let cached = cache[cacheKey];
    if (cached && cached.mtime === mtime(filename)) {
      result = cached;
    }
  }

  if (!result) {
    result = babel.transformFileSync(filename, extend(opts, {
      // Do not process config files since has already been done with the OptionManager
      // calls above and would introduce duplicates.
      babelrc: false,
      sourceMap: "both",
      ast:       false
    }));
  }

  if (cache) {
    cache[cacheKey] = result;
    result.mtime = mtime(filename);
  }

  maps[filename] = result.map;

  return result.code;
}

function shouldIgnore(filename) {
  if (!ignore && !only) {
    return getRelativePath(filename).split(path.sep).indexOf("node_modules") >= 0;
  } else {
    return util.shouldIgnore(filename, ignore || [], only);
  }
}

function loader(m, filename) {
  m._compile(compile(filename), filename);
}

function registerExtension(ext) {
  let old = oldHandlers[ext] || oldHandlers[".js"] || require.extensions[".js"];

  require.extensions[ext] = function (m, filename) {
    if (shouldIgnore(filename)) {
      old(m, filename);
    } else {
      loader(m, filename, old);
    }
  };
}

function hookExtensions(_exts) {
  each(oldHandlers, function (old, ext) {
    if (old === undefined) {
      delete require.extensions[ext];
    } else {
      require.extensions[ext] = old;
    }
  });

  oldHandlers = {};

  each(_exts, function (ext) {
    oldHandlers[ext] = require.extensions[ext];
    registerExtension(ext);
  });
}

hookExtensions(util.canCompile.EXTENSIONS);

export default function (opts?: Object = {}) {
  if (opts.only != null) only = util.arrayify(opts.only, util.regexify);
  if (opts.ignore != null) ignore = util.arrayify(opts.ignore, util.regexify);

  if (opts.extensions) hookExtensions(util.arrayify(opts.extensions));

  if (opts.cache === false) cache = null;

  delete opts.extensions;
  delete opts.ignore;
  delete opts.cache;
  delete opts.only;

  extend(transformOpts, opts);
}
<|endoftext|>


<commit_before>BinaryHeap = function (comparator, initData) {
  if (! _.isFunction(comparator))
    throw new Error('Passed comparator is invalid, should be a comparison function');
  var self = this;
  self._comparator = comparator;
  self._map = {};
  self._heap = [];

  if (_.isArray(initData))
    self._initFromData(initData);
};

var idStringify, idParse;
if (Package.minimongo) {
  idStringify = Package.minimongo.LocalCollection._idStringify;
  idParse = Package.minimongo.LocalCollection._idParse;
} else {
  // XXX: These can't deal with special strings like '__proto__'
  // XXX: or '{ looksLike: "object" }' or numbers.
  idStringify = function (id) { return JSON.stringify(id); };
  idParse = function (id) { return JSON.parse(id); }
}

_.extend(BinaryHeap.prototype, {
  _initFromData: function (data) {},

  get: function (id) {},
  set: function (id, value) {},
  remove: function (id) {},
  has: function (id) {},
  empty: function (id) {},
  clear: function () {},
  forEach: function (iterator) {},
  size: function () {},
  setDefault: function () {},
  clone: function () {},

  maxElementId: function () {}
});

<commit_msg>The implementation of Heap<commit_after>// Constructor of Heap
// - comparator - Function - given two items returns a number
// - initData - Array - the initial data in a format:
//      Object:
//        - id - String - unique id of the item
//        - value - Any - the data value
//    the contents of initData is retained
BinaryHeap = function (comparator, initData) {
  if (! _.isFunction(comparator))
    throw new Error('Passed comparator is invalid, should be a comparison function');
  var self = this;
  self._comparator = comparator;
  self._heapIdx = {};
  self._heap = [];

  if (_.isArray(initData))
    self._initFromData(initData);
};

var idStringify;
if (Package.minimongo) {
  idStringify = Package.minimongo.LocalCollection._idStringify;
} else {
  // XXX: These can't deal with special strings like '__proto__'
  // XXX: or '{ looksLike: "object" }' or numbers.
  idStringify = function (id) { return JSON.stringify(id); };
}

_.extend(BinaryHeap.prototype, {
  _initFromData: function (data) {
    var self = this;

    self._heap = _.clone(data);

    _.each(data, function (o, i) {
      self._heapIdx[idStringify(o.id)] = i;
    });

    for (var i = parentIdx(data.length); i >= 0; i--)
      self._heapify(i);
  },

  _heapify: function (idx) {
    var self = this;

    while (leftChildIdx(idx) < self.size()) {
      var left = leftChildIdx(idx);
      var right = rightChildIdx(idx);
      var largest = idx;

      if (left < self.size() &&
          self._comparator(self._get(left), self._get(largest)) > 0) {
        largest = left;
      }
      if (right < self.size() &&
          self._comparator(self._get(right), self._get(largest)) > 0) {
        largest = right;
      }

      if (largest === idx)
        break;

      self._swap(largest, idx);
      idx = largest;
    }
  },

  _upHeap: function (idx) {
    var self = this;
    var value = self._get(idx);
    var ancestor = idx;

    while (ancestor > 0) {
      var parent = parentIdx(ancestor);
      if (self._comparator(self._get(parent), value) < 0)
        ancestor = parent;
      else
        break;
    }

    if (ancestor !== idx)
      self._swap(ancestor, idx);
  },

  // Internal: gets raw data object placed on idxth place in heap
  _get: function (idx) {
    var self = this;
    return self._heap[idx].value;
  },

  _swap: function (idxA, idxB) {
    var self = this;
    var A = self._heap[idxA];
    var B = self._heap[idxB];

    self._heapIdx[idStringify(A.id)] = idxB;
    self._heapIdx[idStringify(B.id)] = idxA;

    self._heap[idxA] = B;
    self._heap[idxB] = A;
  },

  get: function (id) {
    var self = this;
    return self._get(self._heapIdx[idStringify(id)]);
  },
  set: function (id, value) {
    var self = this;

    if (self.has(id)) {
      if (self.get(id) === value)
        return;
      else
        self.remove(id);
    }

    self._heapIdx[idStringify(id)] = self._heap.length;
    self._heap.push({ id: id, value: value });
    self._upHeap(self._heap.length - 1);
  },
  remove: function (id) {
    var self = this;
    var strId = idStringify(id);

    if (! self.has(id)) {
      var last = self._heap.length - 1;
      var idx = self._heapIdx[strId];
      self._swap(idx, last);
      self._heap.pop();
      self._heapify(idx);
      delete self._heapIdx[strId];
    }
  },
  has: function (id) {
    var self = this;
    return self._heapIdx[idStringify(id)] !== undefined;
  },
  empty: function (id) {
    var self = this;
    return !self.size();
  },
  clear: function () {
    var self = this;
    self._heap = [];
    self._heapIdx = {};
  },
  forEach: function (iterator) {
    var self = this;
    _.each(self._heap, function (obj) {
      return iterator(obj.value, obj.id);
    });
  },
  size: function () {
    var self = this;
    return self._heap.length;
  },
  setDefault: function (id, def) {
    var self = this;
    if (self.has(id))
      return self.get(id);
    self.set(id, def);
    return def;
  },
  clone: function () {
    var self = this;
    var clone = new BinaryHeap(self._comparator);
    clone._heap = EJSON.clone(self._heap);
    clone._heapIdx = EJSON.clone(self._heapIdx);
  },

  maxElementId: function () {
    var self = this;
    return self.size() ? self._heap[0].id : null;
  }
});

function leftChildIdx (i) { return i * 2 + 1; }
function rightChildIdx (i) { return i * i + 2; }
function parentIdx (i) { return (i - 1) >> 1; }

<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import pure from 'recompose/pure';
import { withStyles } from 'material-ui/styles';
import Typography from 'material-ui/Typography';
import Tooltip from 'material-ui/Tooltip';

const styles = theme => ({
  '@global': {
    '#carbonads': {
      padding: theme.spacing.unit,
      backgroundColor: theme.palette.background.paper,
      '& img': {
        verticalAlign: 'middle',
      },
      '& a': {
        textDecoration: 'none',
      },
      '& .carbon-wrap': {
        display: 'flex',
        [theme.breakpoints.up('sm')]: {
          display: 'block',
        },
      },
      '& .carbon-text': {
        ...theme.typography.body1,
        display: 'block',
        margin: `0 0 0 ${theme.spacing.unit}px`,
        [theme.breakpoints.up('sm')]: {
          margin: `${theme.spacing.unit}px 0`,
        },
      },
      '& .carbon-poweredby': {
        ...theme.typography.caption,
        display: 'block',
        marginTop: theme.spacing.unit / 2,
        position: 'absolute',
        right: 0,
        bottom: 0,
        padding: theme.spacing.unit,
        [theme.breakpoints.up('sm')]: {
          marginTop: 0,
          position: 'static',
          padding: 0,
        },
      },
    },
  },
  root: {
    minHeight: 116,
    margin: `${theme.spacing.unit}px 0 0`,
    [theme.breakpoints.up('sm')]: {
      margin: 0,
      minHeight: 0,
    },
  },
  ad: {
    zIndex: 1,
    borderRadius: 4,
    position: 'relative',
    [theme.breakpoints.up('sm')]: {
      margin: `${theme.spacing.unit * 2}px ${theme.spacing.unit}px ${theme.spacing.unit}px`,
      maxWidth: 130 + theme.spacing.unit * 2,
      float: 'right',
    },
    [theme.breakpoints.up('xl')]: {
      position: 'fixed',
      margin: 0,
      right: theme.spacing.unit * 2,
      bottom: theme.spacing.unit * 2,
    },
  },
  info: {
    ...theme.typography.caption,
    position: 'absolute',
    padding: theme.spacing.unit,
    cursor: 'default',
    display: 'none',
    [theme.breakpoints.up('sm')]: {
      display: 'block',
      bottom: 0,
      right: 0,
    },
  },
});

class Carbon extends React.Component {
  state = {
    adblock: null,
  };

  componentDidMount() {
    if (process.env.NODE_ENV !== 'production') {
      return;
    }

    const script = document.createElement('script');
    script.setAttribute('async', '');
    script.src = '//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=materialuicom';
    script.id = '_carbonads_js';
    const ad = document.querySelector('#ad');
    if (ad) {
      ad.appendChild(script);
    }

    this.checkAdblock();
  }

  componentWillUnmount() {
    clearTimeout(this.timerAdblock);
  }

  timerAdblock = null;

  checkAdblock = (attempt = 1) => {
    if (document.querySelector('#carbonads')) {
      this.setState({
        adblock: false,
      });
      return;
    }

    if (attempt < 4) {
      this.timerAdblock = setTimeout(() => {
        this.checkAdblock(attempt + 1);
      }, 500);
    } else {
      this.setState({
        adblock: true,
      });
    }
  };

  render() {
    const { classes } = this.props;
    const { adblock } = this.state;

    if (adblock) {
      return (

              <Typography gutterBottom>Like Material-UI?</Typography>
              <Typography gutterBottom>
                {`If you don't mind tech-related ads, and want to support Open Source,
                please whitelist Material-UI in your ad blocker.`}
              </Typography>
              <Typography>
                Thank you!{' '}

                  ❤

              </Typography>

      );
    }

    return (

          {adblock === false && (
            <Tooltip
              id="ad-info"
              title="This ad is designed to support Open Source."
              placement="left"
            >
              i
            </Tooltip>
          )}

    );
  }
}

Carbon.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default pure(withStyles(styles)(Carbon));
<commit_msg>[docs] Better ad blocker logic<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import pure from 'recompose/pure';
import { withStyles } from 'material-ui/styles';
import Typography from 'material-ui/Typography';
import Tooltip from 'material-ui/Tooltip';

const styles = theme => ({
  '@global': {
    '#carbonads': {
      padding: theme.spacing.unit,
      backgroundColor: theme.palette.background.paper,
      '& img': {
        verticalAlign: 'middle',
      },
      '& a': {
        textDecoration: 'none',
      },
      '& .carbon-wrap': {
        display: 'flex',
        [theme.breakpoints.up('sm')]: {
          display: 'block',
        },
      },
      '& .carbon-text': {
        ...theme.typography.body1,
        display: 'block',
        margin: `0 0 0 ${theme.spacing.unit}px`,
        [theme.breakpoints.up('sm')]: {
          margin: `${theme.spacing.unit}px 0`,
        },
      },
      '& .carbon-poweredby': {
        ...theme.typography.caption,
        display: 'block',
        marginTop: theme.spacing.unit / 2,
        position: 'absolute',
        right: 0,
        bottom: 0,
        padding: theme.spacing.unit,
        [theme.breakpoints.up('sm')]: {
          marginTop: 0,
          position: 'static',
          padding: 0,
        },
      },
    },
  },
  root: {
    minHeight: 116,
    margin: `${theme.spacing.unit}px 0 0`,
    [theme.breakpoints.up('sm')]: {
      margin: 0,
      minHeight: 0,
    },
  },
  ad: {
    zIndex: 1,
    borderRadius: 4,
    position: 'relative',
    [theme.breakpoints.up('sm')]: {
      margin: `${theme.spacing.unit * 2}px ${theme.spacing.unit}px ${theme.spacing.unit}px`,
      maxWidth: 130 + theme.spacing.unit * 2,
      float: 'right',
    },
    [theme.breakpoints.up('xl')]: {
      position: 'fixed',
      margin: 0,
      right: theme.spacing.unit * 2,
      bottom: theme.spacing.unit * 2,
    },
  },
  info: {
    ...theme.typography.caption,
    position: 'absolute',
    padding: theme.spacing.unit,
    cursor: 'default',
    display: 'none',
    [theme.breakpoints.up('sm')]: {
      display: 'block',
      bottom: 0,
      right: 0,
    },
  },
});

class Carbon extends React.Component {
  state = {
    adblock: null,
  };

  componentDidMount() {
    if (process.env.NODE_ENV !== 'production') {
      return;
    }

    const script = document.createElement('script');
    script.setAttribute('async', '');
    script.src = '//cdn.carbonads.com/carbon.js?zoneid=1673&serve=C6AILKT&placement=materialuicom';
    script.id = '_carbonads_js';
    const ad = document.querySelector('#ad');
    if (ad) {
      ad.appendChild(script);
    }

    this.checkAdblock();
  }

  componentWillUnmount() {
    clearTimeout(this.timerAdblock);
  }

  timerAdblock = null;

  checkAdblock = (attempt = 1) => {
    if (document.querySelector('#carbonads')) {
      this.setState({
        adblock: false,
      });
      return;
    }

    if (attempt < 6) {
      this.timerAdblock = setTimeout(() => {
        this.checkAdblock(attempt + 1);
      }, 500);
    } else {
      this.setState({
        adblock: true,
      });
    }
  };

  render() {
    const { classes } = this.props;
    const { adblock } = this.state;

    if (adblock) {
      return (

              <Typography gutterBottom>Like Material-UI?</Typography>
              <Typography gutterBottom>
                {`If you don't mind tech-related ads, and want to support Open Source,
                please whitelist Material-UI in your ad blocker.`}
              </Typography>
              <Typography>
                Thank you!{' '}

                  ❤

              </Typography>

      );
    }

    return (

          {adblock === false && (
            <Tooltip
              id="ad-info"
              title="This ad is designed to support Open Source."
              placement="left"
            >
              i
            </Tooltip>
          )}

    );
  }
}

Carbon.propTypes = {
  classes: PropTypes.object.isRequired,
};

export default pure(withStyles(styles)(Carbon));
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */
var util = require('util')
  , OAuth2Strategy = require('passport-oauth').OAuth2Strategy
  , InternalOAuthError = require('passport-oauth').InternalOAuthError;

/**
 * `Strategy` constructor.
 *
 * The HumanAPI authentication strategy authenticates requests by delegating to
 * HumanAPI using the OAuth 2.0 protocol.
 *
 * Applications must supply a `verify` callback which accepts an `accessToken`,
 * `refreshToken` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occurred, `err` should be set.
 *
 * Options:
 *   - `clientID`      your HumanAPI application's App ID
 *   - `clientSecret`  your HumanAPI application's App Secret
 *   - `callbackURL`   URL to which HumanAPI will redirect the user after granting authorization
 *
 * Examples:
 *
 *     passport.use(new HumanApiStrategy({
 *         clientID: '-unique-identifier-',
 *         clientSecret: '-hash-of-something-'
 *         callbackURL: 'https://www.example.com/auth/humanapi/callback',
 *       },
 *       function(accessToken, refreshToken, profile, done) {
 *         User.findOrCreate(..., function (err, user) {
 *           done(err, user);
 *         });
 *       }
 *     ));
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {
  options = options || {};
  options.authorizationURL = options.authorizationURL || 'https://user.humanapi.co/oauth/authorize';
  options.tokenURL = options.tokenURL || 'https://user.humanapi.co/oauth/token';
  options.scopeSeparator = options.scopeSeparator || '%20';

  OAuth2Strategy.call(this, options, verify);
  this.name = 'humanapi';
}

/**
 * Inherit from `OAuth2Strategy`.
 */
util.inherits(Strategy, OAuth2Strategy);

/**
 * Retrieve user profile from HumanAPI. __REQUIRES__ the `names` scope or it will fail.
 *
 * This function constructs a normalized profile, with the following properties:
 *
 *   - `provider`         always set to `humanapi`
 *   - `id`               the user's HumanAPI ID
 *   - `displayName`      the user's full name
 *   - `firstName`        the user's first name
 *   - `lastName`         the user's last name
 *
 * @param {String} accessToken
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(accessToken, done) {

  this._oauth2.getProtectedResource('https://api.humanapi.co/v1/human/profile', accessToken, function (err, body, res) {
    if (err) { return done(new InternalOAuthError('failed to fetch user profiles', err)); }

    try {
      var json = JSON.parse(body);

      var profile = { provider: 'humanapi' };
      profile.id = json.userId;
      profile.email = json.email;
      profile.defaultTimeZone = json.defaultTimeZone;
      profile._raw = body;
      profile._json = json;

      done(null, profile);
    } catch(e) {
      done(e);
    }
  });
}

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;<commit_msg>Update strategy.js<commit_after>/**
 * Module dependencies.
 */
var util = require('util')
  , OAuth2Strategy = require('passport-oauth').OAuth2Strategy
  , InternalOAuthError = require('passport-oauth').InternalOAuthError;

/**
 * `Strategy` constructor.
 *
 * The HumanAPI authentication strategy authenticates requests by delegating to
 * HumanAPI using the OAuth 2.0 protocol.
 *
 * Applications must supply a `verify` callback which accepts an `accessToken`,
 * `refreshToken` and service-specific `profile`, and then calls the `done`
 * callback supplying a `user`, which should be set to `false` if the
 * credentials are not valid.  If an exception occurred, `err` should be set.
 *
 * Options:
 *   - `clientID`      your HumanAPI application's App ID
 *   - `clientSecret`  your HumanAPI application's App Secret
 *   - `callbackURL`   URL to which HumanAPI will redirect the user after granting authorization
 *
 * Examples:
 *
 *     passport.use(new HumanApiStrategy({
 *         clientID:      '-the-app-id-',
 *         clientSecret:  '-the-app-secret-'
 *         callbackURL:   'https://www.example.com/auth/humanapi/callback',
 *       },
 *       function(accessToken, refreshToken, profile, done) {
 *         User.findOrCreate(..., function (err, user) {
 *           done(err, user);
 *         });
 *       }
 *     ));
 *
 * @param {Object} options
 * @param {Function} verify
 * @api public
 */
function Strategy(options, verify) {
  options = options || {};
  options.authorizationURL = options.authorizationURL || 'https://user.humanapi.co/oauth/authorize';
  options.tokenURL = options.tokenURL || 'https://user.humanapi.co/oauth/token';
  options.scopeSeparator = options.scopeSeparator || '%20';

  OAuth2Strategy.call(this, options, verify);
  this.name = 'humanapi';
}

/**
 * Inherit from `OAuth2Strategy`.
 */
util.inherits(Strategy, OAuth2Strategy);

/**
 * Retrieve user profile from HumanAPI.
 *
 * This function constructs a normalized profile, with the following properties:
 *
 *   - `provider`         always set to `humanapi`
 *   - `id`               the user's HumanAPI ID
 *   - `email`            the user's email address
 *   - `defaultTimeZone`  the user's default time zone
 *
 * @param {String} accessToken
 * @param {Function} done
 * @api protected
 */
Strategy.prototype.userProfile = function(accessToken, done) {

  this._oauth2.getProtectedResource('https://api.humanapi.co/v1/human/profile', accessToken, function (err, body, res) {
    if (err) { return done(new InternalOAuthError('failed to fetch user profiles', err)); }

    try {
      var json = JSON.parse(body);

      var profile = { provider: 'humanapi' };
      profile.id = json.userId;
      profile.email = json.email;
      profile.defaultTimeZone = json.defaultTimeZone;
      profile._raw = body;
      profile._json = json;

      done(null, profile);
    } catch(e) {
      done(e);
    }
  });
}

/**
 * Expose `Strategy`.
 */
module.exports = Strategy;
<|endoftext|>


<commit_before>define(["dojo/_base/declare", "dojox/gfx", "./ScaleIndicatorBase", "./_circularGaugeUtil", "dojo/_base/event"], function(declare, gfx, ScaleIndicatorBase, _circularGaugeUtil, eventUtil){

    /*=====
     var ScaleIndicatorBase = dojox.gauge.ScaleIndicatorBase;
     =====*/

	return declare("dojox.gauge.CircularValueIndicator", ScaleIndicatorBase, {
		//	summary:
		//		The circular value indicator, typically used for creating needles.

		indicatorShapeFunc: function(group){
			return group.createLine({
				x1: 0,
				y1: 0,
				x2: 40,
				y2: 0
			}).setStroke({
				color: 'black',
				width: 1
			});
		},

		refreshRendering: function(){
			this.inherited(arguments);

			var angle = this.scale.positionForValue(this.value);

			this._gfxGroup.setTransform([{
				dx: this.scale.originX,
				dy: this.scale.originY
			}, gfx.matrix.rotateg(angle)]);
		},

		_mouseDownHandler: function(event){
			this.inherited(arguments);
			var origin = this.scale._gauge._gaugeToPage(this.scale.originX, this.scale.originY);
			var angle = ((Math.atan2(event.pageY - origin.y, event.pageX - origin.x)) * 180) / (Math.PI);
			this.set("value", this.scale.valueForPosition(angle));

			// prevent the browser from selecting text
			eventUtil.stop(event);
		},

		_mouseMoveHandler: function(event){
			this.inherited(arguments);

			var origin = this.scale._gauge._gaugeToPage(this.scale.originX, this.scale.originY);
			var angle = ((Math.atan2(event.pageY - origin.y, event.pageX - origin.x)) * 180) / (Math.PI);
			this.set("value", this.scale.valueForPosition(angle));
		}
	});
});
<commit_msg>API doc<commit_after>define(["dojo/_base/declare", "dojox/gfx", "./ScaleIndicatorBase", "./_circularGaugeUtil", "dojo/_base/event"], function(declare, gfx, ScaleIndicatorBase, _circularGaugeUtil, eventUtil){

    /*=====
     var ScaleIndicatorBase = dojox.gauge.ScaleIndicatorBase;
     =====*/

	return declare("dojox.gauge.CircularValueIndicator", ScaleIndicatorBase, {
		//	summary:
		//		The circular value indicator, typically used for creating needles.

		indicatorShapeFunc: function(group, indicator){
			//	summary:
			//		Draws the indicator. The rotation center is at (0, 0).
			//	group: dojox.gfx.canvas.Group
			//		A GFX group for drawing.
			//	returns: dojox.gfx.canvas.Shape
			//		A GFX shape retrievable using the getIndicatorRenderer method of the associated scale.
			return group.createLine({
				x1: 0,
				y1: 0,
				x2: 40,
				y2: 0
			}).setStroke({
				color: 'black',
				width: 1
			});
		},

		refreshRendering: function(){
			this.inherited(arguments);

			var angle = this.scale.positionForValue(this.value);

			this._gfxGroup.setTransform([{
				dx: this.scale.originX,
				dy: this.scale.originY
			}, gfx.matrix.rotateg(angle)]);
		},

		_mouseDownHandler: function(event){
			this.inherited(arguments);
			var origin = this.scale._gauge._gaugeToPage(this.scale.originX, this.scale.originY);
			var angle = ((Math.atan2(event.pageY - origin.y, event.pageX - origin.x)) * 180) / (Math.PI);
			this.set("value", this.scale.valueForPosition(angle));

			// prevent the browser from selecting text
			eventUtil.stop(event);
		},

		_mouseMoveHandler: function(event){
			this.inherited(arguments);

			var origin = this.scale._gauge._gaugeToPage(this.scale.originX, this.scale.originY);
			var angle = ((Math.atan2(event.pageY - origin.y, event.pageX - origin.x)) * 180) / (Math.PI);
			this.set("value", this.scale.valueForPosition(angle));
		}
	});
});
<|endoftext|>


<commit_before>'use strict';

var Collection = require('ampersand-collection');
var SubCollection = require('ampersand-subcollection');
var React = require('react');
var merge = require('lodash.merge');
var view = require('./view');
var constructCollection = require('../util/ensureInstance').collection;

function bindIfExists(fn, ctx) {
  if (typeof fn === 'function') {
    return fn.bind(ctx);
  }
  return fn;
}

module.exports = function(config) {
  if (config == null) {
    throw new Error('config parameter is required');
  }
  if (config.itemView == null) {
    throw new Error('itemView attribute is required');
  }
  var configCollection = config.collection;
  delete config.collection;

  // items = array of item views
  // collection = ampersand collection
  var CollectionViewMixin = {
    collectionName: 'modelView',
    propTypes: {
      collection: React.PropTypes.oneOfType([
        React.PropTypes.func,
        React.PropTypes.object,
        React.PropTypes.instanceOf(Collection)
      ]),
      data: React.PropTypes.arrayOf(React.PropTypes.object),
      query: React.PropTypes.object,
      offset: React.PropTypes.number,
      limit: React.PropTypes.number,
      where: React.PropTypes.object,
      filter: React.PropTypes.func,
      filters: React.PropTypes.arrayOf(React.PropTypes.func),
      watch: React.PropTypes.arrayOf(React.PropTypes.string),
      sort: React.PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.func
      ])
    },

    // most options can be passed via config or props
    // props takes precedence
    getDefaultProps: function(){
      return {
        collection: configCollection,
        data: config.data,
        query: config.query,
        offset: config.offset,
        limit: config.limit,
        where: config.where,
        filter: config.filter,
        filters: config.filters,
        watch: config.watch,
        sort: config.sort
      };
    },

    // on component mount we initialize everything
    componentWillMount: function() {
      this._initialize(this.props);
      this._computeItemsWithContext();
    },

    componentWillReceiveProps: function(nextProps) {
      this._configureItems(nextProps);
    },

    componentWillUpdate: function(){
      this._computeItemsWithContext();
    },

    _collectionFetchFailed: function(m, res) {
      var notFound = res.status === 404 || res.status === 204;
      var handled404 = notFound && this.collectionNotFound;
      if (this.collectionFetchFailed) {
        this.collectionFetchFailed.apply(this, arguments);
      }
      if (handled404) {
        this.collectionNotFound.apply(this, arguments);
      }

      this.collection = null;
      if (!this.collectionFetchFailed && !handled404) {
        throw new Error('Collection fetch failed with a ' + res.status);
      }
    },

    _initialize: function(props) {
      // get sync and create collection based on model
      // model passed in via props or config
      var collection = constructCollection(props.collection, props);

      var setCollection = (function() {
        this.collection = collection;
        // create items sub-collection
        this._items = new SubCollection(this.collection);
        this._configureItems(props);
        // TODO: remove events on prop change switch up or destroy
        this._items.on('add change remove sort', this.tryUpdate);
        if (this.collectionDidFetch) {
          this.collectionDidFetch();
        }
        this.tryUpdate();
      }).bind(this);

      // TODO: override all sync behavior to run errors and success
      // through our hooks
      if (collection._needsInitialFetch) {
        collection.fetch({
          success: setCollection,
          error: this._collectionFetchFailed
        });
      } else {
        setCollection();
      }
    },

    // internal fn to sync props to shadow collection
    _configureItems: function(props) {
      if (typeof props !== 'object') {
        throw new Error('_configureItems called with invalid props');
      }
      // not intialized yet
      if (!this._items) {
        return;
      }
      this._items.configure({
        where: props.where,
        filter: props.filter,
        limit: props.limit,
        offset: props.offset,
        comparator: bindIfExists(props.sort, this)
      }, true);
    },

    // internal fn to sync this.items with collection
    _computeItemsWithContext: function() {
      React.withContext(this.context, this._computeItems);
    },
    _computeItems: function() {
      // nothing to compute, data hasnt been constructed yet
      if (!this._items) {
        return;
      }

      // TODO: switch to transform when available
      // https://github.com/AmpersandJS/ampersand-subcollection/issues/31
      this.items = this._items.map(function(m, idx) {
        var fissionProps = {
          model: m,
          index: idx,
          key: m.id
        };

        // if itemview props transform, use that merged w/ defaults
        // otherwise just defaults
        var itemProps = this.getItemViewProps ?
          merge(this.getItemViewProps(m, idx), fissionProps) :
          fissionProps;

        return this.itemView(itemProps);
      }, this);
    }
  };

  return view(config, [CollectionViewMixin]);
};<commit_msg>initialized<commit_after>'use strict';

var Collection = require('ampersand-collection');
var SubCollection = require('ampersand-subcollection');
var React = require('react');
var merge = require('lodash.merge');
var view = require('./view');
var constructCollection = require('../util/ensureInstance').collection;

function bindIfExists(fn, ctx) {
  if (typeof fn === 'function') {
    return fn.bind(ctx);
  }
  return fn;
}

module.exports = function(config) {
  if (config == null) {
    throw new Error('config parameter is required');
  }
  if (config.itemView == null) {
    throw new Error('itemView attribute is required');
  }
  var configCollection = config.collection;
  delete config.collection;

  // items = array of item views
  // collection = ampersand collection
  var CollectionViewMixin = {
    collectionName: 'modelView',
    propTypes: {
      collection: React.PropTypes.oneOfType([
        React.PropTypes.func,
        React.PropTypes.object,
        React.PropTypes.instanceOf(Collection)
      ]),
      data: React.PropTypes.arrayOf(React.PropTypes.object),
      query: React.PropTypes.object,
      offset: React.PropTypes.number,
      limit: React.PropTypes.number,
      where: React.PropTypes.object,
      filter: React.PropTypes.func,
      filters: React.PropTypes.arrayOf(React.PropTypes.func),
      watch: React.PropTypes.arrayOf(React.PropTypes.string),
      sort: React.PropTypes.oneOfType([
        React.PropTypes.string,
        React.PropTypes.func
      ])
    },

    // most options can be passed via config or props
    // props takes precedence
    getDefaultProps: function(){
      return {
        collection: configCollection,
        data: config.data,
        query: config.query,
        offset: config.offset,
        limit: config.limit,
        where: config.where,
        filter: config.filter,
        filters: config.filters,
        watch: config.watch,
        sort: config.sort
      };
    },

    // on component mount we initialize everything
    componentWillMount: function() {
      this._initialize(this.props);
      this._computeItemsWithContext();
    },

    componentWillReceiveProps: function(nextProps) {
      this._configureItems(nextProps);
    },

    componentWillUpdate: function(){
      this._computeItemsWithContext();
    },

    _collectionFetchFailed: function(m, res) {
      var notFound = res.status === 404 || res.status === 204;
      var handled404 = notFound && this.collectionNotFound;
      if (this.collectionFetchFailed) {
        this.collectionFetchFailed.apply(this, arguments);
      }
      if (handled404) {
        this.collectionNotFound.apply(this, arguments);
      }

      this.collection = null;
      if (!this.collectionFetchFailed && !handled404) {
        throw new Error('Collection fetch failed with a ' + res.status);
      }
    },

    _initialize: function(props) {
      // get sync and create collection based on model
      // model passed in via props or config
      var collection = constructCollection(props.collection, props);

      var setCollection = (function() {
        this.collection = collection;
        // create items sub-collection
        this._items = new SubCollection(this.collection);
        this._configureItems(props);
        // TODO: remove events on prop change switch up or destroy
        this._items.on('add change remove sort', this.tryUpdate);
        if (this.collectionDidFetch) {
          this.collectionDidFetch();
        }
        this.tryUpdate();
      }).bind(this);

      // TODO: override all sync behavior to run errors and success
      // through our hooks
      if (collection._needsInitialFetch) {
        collection.fetch({
          success: setCollection,
          error: this._collectionFetchFailed
        });
      } else {
        setCollection();
      }
    },

    // internal fn to sync props to shadow collection
    _configureItems: function(props) {
      if (typeof props !== 'object') {
        throw new Error('_configureItems called with invalid props');
      }
      // not initialized yet
      if (!this._items) {
        return;
      }
      this._items.configure({
        where: props.where,
        filter: props.filter,
        limit: props.limit,
        offset: props.offset,
        comparator: bindIfExists(props.sort, this)
      }, true);
    },

    // internal fn to sync this.items with collection
    _computeItemsWithContext: function() {
      React.withContext(this.context, this._computeItems);
    },
    _computeItems: function() {
      // nothing to compute, data hasnt been constructed yet
      if (!this._items) {
        return;
      }

      // TODO: switch to transform when available
      // https://github.com/AmpersandJS/ampersand-subcollection/issues/31
      this.items = this._items.map(function(m, idx) {
        var fissionProps = {
          model: m,
          index: idx,
          key: m.id
        };

        // if itemview props transform, use that merged w/ defaults
        // otherwise just defaults
        var itemProps = this.getItemViewProps ?
          merge(this.getItemViewProps(m, idx), fissionProps) :
          fissionProps;

        return this.itemView(itemProps);
      }, this);
    }
  };

  return view(config, [CollectionViewMixin]);
};<|endoftext|>


<commit_before>var sys = require('sys')
var path = require('path');

var resourcer = require('resourcer'),
    cradle = require('cradle');

resourcer.Cache = require('resourcer/cache').Cache;

this.Connection = function (config) {
    this.connection = new(cradle.Connection)({
        host:  config.host || '127.0.0.1',
        port:  config.port || 5984,
        raw:   true,
        cache: false
    }).database(config.uri || resourcer.env);
    this.cache = new(resourcer.Cache);
};

this.Connection.prototype = {
    protocol: 'database',
    load: function(data) {
				throw new(Error)("Load not valid for database engine.");
    },
    request: function (method) {
        var args = Array.prototype.slice.call(arguments, 1);
        return this.connection[method].apply(this.connection, args);
    },
    head: function (id, callback) {
        return this.request('head', id, callback);
    },
    get: function (id, callback) {
        this.request.call(this, 'get', id, function (e, res) {
            if (e) { callback(e) }
            else {
                if (Array.isArray(id)) {
                    callback(null, res.rows.map(function (r) { return r.doc }));
                } else {
                    callback(null, res);
                }
            }
        });
    },
    put: function (id, doc, callback) {
        var args = Array.prototype.slice.call(arguments);
        return this.request('put', id, doc, function (e, res) {
            if (e) {
                callback(e);
            } else {
                res.status = 201;
                callback(null, res);
            }
        });
    },
    save: function () {
        return this.put.apply(this, arguments);
    },
    update: function (id, doc, callback) {
        var that = this;
        if (this.cache.has(id)) {
            that.put(id, resourcer.mixin({}, this.cache.get(id), doc), callback);
        } else {
            this.get(id, function (e, res) {
                var obj = resourcer.mixin({}, res, doc);
                that.cache.put(id, res);
                that.put(id, obj, callback);
            });
        }
    },
    destroy: function () {
        var args = Array.prototype.slice.call(arguments);
        return this.request.apply(this, ['remove'].concat(args));
    },
    view: function (path, opts, callback) {
        return this.request.call(this, 'view', path, opts, function (e, res) {
            if (e) { callback(e) }
            else {
                callback(null, res.rows.map(function (r) {
                    // With `include_docs=true`, the 'doc' attribute is set instead of 'value'.
                    return r.doc || r.value;
                }));
            }
        });
    },
    all: function (callback) {
        return this.request.call(this, 'all', { include_docs: 'true' }, function (e, res) {
            if (e) { callback(e) }
            else {
                callback(null, res.rows.map(function (r) { return r.doc }));
            }
        });
    }
};
<commit_msg>set _id in view query, if not in doc<commit_after>var sys = require('sys')
var path = require('path');

var resourcer = require('resourcer'),
    cradle = require('cradle');

resourcer.Cache = require('resourcer/cache').Cache;

this.Connection = function (config) {
    this.connection = new(cradle.Connection)({
        host:  config.host || '127.0.0.1',
        port:  config.port || 5984,
        raw:   true,
        cache: false
    }).database(config.uri || resourcer.env);
    this.cache = new(resourcer.Cache);
};

this.Connection.prototype = {
    protocol: 'database',
    load: function(data) {
				throw new(Error)("Load not valid for database engine.");
    },
    request: function (method) {
        var args = Array.prototype.slice.call(arguments, 1);
        return this.connection[method].apply(this.connection, args);
    },
    head: function (id, callback) {
        return this.request('head', id, callback);
    },
    get: function (id, callback) {
        this.request.call(this, 'get', id, function (e, res) {
            if (e) { callback(e) }
            else {
                if (Array.isArray(id)) {
                    callback(null, res.rows.map(function (r) { return r.doc }));
                } else {
                    callback(null, res);
                }
            }
        });
    },
    put: function (id, doc, callback) {
        var args = Array.prototype.slice.call(arguments);
        return this.request('put', id, doc, function (e, res) {
            if (e) {
                callback(e);
            } else {
                res.status = 201;
                callback(null, res);
            }
        });
    },
    save: function () {
        return this.put.apply(this, arguments);
    },
    update: function (id, doc, callback) {
        var that = this;
        if (this.cache.has(id)) {
            that.put(id, resourcer.mixin({}, this.cache.get(id), doc), callback);
        } else {
            this.get(id, function (e, res) {
                var obj = resourcer.mixin({}, res, doc);
                that.cache.put(id, res);
                that.put(id, obj, callback);
            });
        }
    },
    destroy: function () {
        var args = Array.prototype.slice.call(arguments);
        return this.request.apply(this, ['remove'].concat(args));
    },
    view: function (path, opts, callback) {
        return this.request.call(this, 'view', path, opts, function (e, res) {
            if (e) { callback(e) }
            else {
                callback(null, res.rows.map(function (r) {
                    // With `include_docs=true`, the 'doc' attribute is set instead of 'value'.
                    var doc = r.doc || r.value;

                    if (r.id) { doc._id = r.id }
                    return doc;
                }));
            }
        });
    },
    all: function (callback) {
        return this.request.call(this, 'all', { include_docs: 'true' }, function (e, res) {
            if (e) { callback(e) }
            else {
                callback(null, res.rows.map(function (r) { return r.doc }));
            }
        });
    }
};
<|endoftext|>


<commit_before>module['exports'] = function formatError (type, err) {
  if (typeof err === "undefined") {
    err = type;
  }
  var message = 'An error occurred with user-submitted code \n';
  var stack = err.stack.split('\n');
  message += '    ' + stack[1] + '\n\n';
  message += 'Error: ' + err.message;
  console.log(stack)
  err.message = message;
  return err;
};<commit_msg>[api] [errors] Show more of error stack<commit_after>module['exports'] = function formatError (type, err) {
  if (typeof err === "undefined") {
    err = type;
  }
  var message = 'An error occurred with user-submitted code \n';
  var stack = err.stack.split('\n');
  message += '    ' + stack[1] + '\n';
  message += '    ' + stack[2] + '\n\n';
  message += 'Error: ' + err.message;
  console.log(stack)
  err.message = message;
  return err;
};<|endoftext|>


<commit_before>const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');

const TeamEventSchema = new mongoose.Schema({
    eventId: { type: String, required: true },
    teamId: { type: String, required: true },
    programId: { type: String, required: true },
    registeredOn: {type: Date, required: true },
    teamNumber: {type:String}
});

// create TTL index
TeamEventSchema.index({ eventId:1, teamId: 1 }, { unique:true });

if (!mongoose.models.TeamEvent) {
    mongoose.model('TeamEvent', TeamEventSchema);
}

module.exports = TeamEventSchema;<commit_msg>added comment<commit_after>const mongoose = require('mongoose');
mongoose.Promise = require('bluebird');

const TeamEventSchema = new mongoose.Schema({
    eventId: { type: String, required: true },
    teamId: { type: String, required: true },
    programId: { type: String, required: true },
    registeredOn: {type: Date, required: true },
    teamNumber: {type:String}
});

// unique index to ensure team can register for specific event only once
TeamEventSchema.index({ eventId:1, teamId: 1 }, { unique:true });

if (!mongoose.models.TeamEvent) {
    mongoose.model('TeamEvent', TeamEventSchema);
}

module.exports = TeamEventSchema;<|endoftext|>


<commit_before>(function ngCatwalk($angular, $object) {

    "use strict";

    // Bootstrap ngCatwalk!
    var app = $angular.module('ngCatwalk', ['ngCrossfilter']);

    /**
     * @method throwException
     * @param message {String}
     * @return {void}
     */
    var throwException = function throwException(message) {
        throw "ngCatwalk: " + message + ".";
    };

    /**
     * @property ngCatwalkAttribute
     * @type {Object}
     */
    var ngCatwalkAttribute = {

        /**
         * @method any
         * @property defaultValue {Object|Array|Number|Boolean|Date|String|RegExp}
         * @return {Function}
         */
        any: function any(defaultValue) {

            return function(value) {

                if (value === null) {
                    return null;
                }

                return typeof value !== 'undefined' ? value : defaultValue;

            };

        },

        /**
         * @method autoIncrement
         * @return {Function}
         */
        autoIncrement: function autoIncrement() {

            var index = 0;

            return function() {
                return ++index;
            }

        },

        /**
         * @method number
         * @param defaultValue {Number}
         * @returns {Function}
         */
        number: function number(defaultValue) {

            return function(value) {

                if (value === null) {
                    return null;
                }

                return typeof value !== 'undefined' ? +value : defaultValue;

            };

        },

        /**
         * @method string
         * @property defaultValue {String}
         * @returns {Function}
         */
        string: function string(defaultValue) {

            return function(value) {

                if (value === null) {
                    return defaultValue || null;
                }

                return typeof value !== 'undefined' ? String(value) : defaultValue;

            };

        }

    };

    /**
     * @property ngCatwalkRelationship
     * @type {Object}
     */
    var ngCatwalkRelationship = {

        /**
         * @method One
         * @param options {Object}
         * @constructor
         */
        One: function One(options) {

            /**
             * @method getOptions
             * @return {Object}
             */
            this.getOptions = function getOptions() {
                return options;
            }

        }

    };

    /**
     * @module ngCatwalk
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngCatwalk
     */
    app.service('catwalk', ['$rootScope', '$q', '$interpolate', 'Crossfilter',

        /**
         * @method CatwalkService
         * @param $rootScope {Object}
         * @param $interpolate {Function}
         * @param $q {Object}
         * @param Crossfilter {Function}
         * @return {Object}
         */
        function CatwalkService($rootScope, $q, $interpolate, Crossfilter) {

            /**
             * @module ngCatwalk
             * @submodule Catwalk
             * @constructor
             */
            function Catwalk() {}

            /**
             * @property prototype
             * @type {Object}
             */
            Catwalk.prototype = {

                /**
                 * @property attribute
                 * @type ngCatwalkAttribute
                 */
                attribute: ngCatwalkAttribute,

                /**
                 * @property relationship
                 * @type {Object}
                 */
                relationship: {

                    /**
                     * @property hasOne
                     * @param options {Object}
                     * @return {ngCatwalkRelationship.One}
                     */
                    hasOne: function hasOne(options) {
                        return new ngCatwalkRelationship.One(options);
                    }

                },

                /**
                 * @property _primaryName
                 * @type {String}
                 */
                _primaryName: '_catwalkId',

                /**
                 * @property _relationshipStores
                 * @type {Object}
                 */
                _relationshipStores: {},

                /**
                 * @property _silent
                 * @type {Boolean}
                 */
                _silent: false,

                /**
                 * @property _eventName
                 * @type {String}
                 */
                _eventName: 'catwalk/{{type}}/{{collection}}',

                /**
                 * @property _collections
                 * @type {Object}
                 * @private
                 */
                _collections: {},

                /**
                 * @method collection
                 * @param name {String}
                 * @param properties {Object}
                 * @return {Array}
                 */
                collection: function collection(name, properties) {

                    if (!this._collections[name]) {

                        // Create the empty collection.
                        this._collections[name] = new Crossfilter([]);

                    }

                    if (properties) {

                        // Define the primary key as a number.
                        properties[this._primaryName] = this.attribute.number();

                        // Create the collection if we've defined the properties;
                        this._collections[name].primaryKey(this._primaryName);
                        this._collections[name].blueprint = properties;
                        this._collections[name].index     = 0;

                        for (var property in properties) {

                            if (properties.hasOwnProperty(property)) {

                                // Define the dimension.
                                this._collections[name].addDimension(property);

                            }

                        }

                    }

                    // Otherwise we'll retrieve the collection.
                    return this._collections[name];

                },

                /**
                 * Invokes a CRUD method which normally emits an event. However, when wrapped in the
                 * silently method, the CRUD method behaves as normal, minus the emitting of the event.
                 *
                 * @method silently
                 * @param processFunction {Function}
                 * @return {void}
                 */
                silently: function silently(processFunction) {
                    this._silent = true;
                    processFunction.apply(this);
                    this._silent = false;
                },

                /**
                 * @method createModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Object}
                 */
                createModel: function createModel(collectionName, model) {

                    // Ensure the model conforms with the collection blueprint.
                    model = this.cleanModel(collectionName, model);

                    // Add the model to the collection and generate the promise.
                    this.collection(collectionName).addModel(model);
                    var promise = this.createPromise(collectionName, 'create', [model]);

                    // Promise resolution.
                    promise.then(this.resolveCreateModel(collectionName, model).bind(this));
                    promise.catch(this.rejectCreateModel(collectionName, model).bind(this));

                    return model;

                },

                /**
                 * @method rejectCreateModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Function}
                 */
                rejectCreateModel: function rejectCreateModel(collectionName, model) {

                    return function rejectPromise() {

                        this.silently(function silentlyDelete() {
                            this.collection(collectionName).deleteModel(model);
                        });

                    };

                },

                /**
                 * @method resolveCreateModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Function}
                 */
                resolveCreateModel: function resolveCreateModel(collectionName, model) {

                    return function resolvePromise(properties) {

                        var blueprint = this.collection(collectionName).blueprint;

                        this._propertyIterator(properties, function iterator(property) {

                            var typecast = blueprint[property];

                            // Don't add properties to the model if it hasn't been defined in
                            // the blueprint.
                            if (typeof typecast === 'undefined') {
                                return;
                            }

                            // Overwrite the value with the one specified in the resolution of
                            // the related promise.
                            model[property] = typecast(properties[property]);

                        });

                    };

                },

                /**
                 * @method updateModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @param properties {Object}
                 * @return {Object}
                 */
                updateModel: function updateModel(collectionName, model, properties) {

                },

                /**
                 * @method resolveUpdateModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Object}
                 */
                resolveUpdateModel: function resolveUpdateModel(collectionName, model) {

                },

                /**
                 * @method rejectUpdateModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @param oldProperties {Object}
                 * @return {Object}
                 */
                rejectUpdateModel: function rejectUpdateModel(collectionName, model, oldProperties) {

                },

                /**
                 * @method deleteModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Object}
                 */
                deleteModel: function deleteModel(collectionName, model) {

                    // Add the model to the collection and generate the promise.
                    this.collection(collectionName).deleteModel(model);
                    var promise = this.createPromise(collectionName, 'delete', [model]);

                    // Promise resolution.
                    promise.then(this.resolveDeleteModel(collectionName, model).bind(this));
                    promise.catch(this.rejectDeleteModel(collectionName, model).bind(this));

                    return model;

                },

                /**
                 * @method resolveDeleteModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Object}
                 */
                resolveDeleteModel: function resolveDeleteModel(collectionName, model) {

                    return function resolvePromise() {};

                },

                /**
                 * @method rejectDeleteModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Object}
                 */
                rejectDeleteModel: function rejectDeleteModel(collectionName, model) {

                    return function rejectPromise() {

                        this.silently(function silentlyRestore() {
                            this.collection(collectionName).restoreModel(model);
                        });

                    };

                },

                /**
                 * @method createPromise
                 * @param collectionName {String}
                 * @param type {String}
                 * @param args {Array}
                 * @return {$q.promise}
                 */
                createPromise: function createPromise(collectionName, type, args) {

                    var deferred = $q.defer();

                    if (!Array.isArray(args)) {

                        // Ensure the `args` variable is an array.
                        args = args ? [args] : [];

                    }

                    // Attach the promise for the developer to resolve or reject.
                    args.unshift(deferred);

                    // Create and broadcast the event.
                    var eventName = $interpolate(this._eventName)({ type: type, collection: collectionName });
                    $rootScope.$broadcast(eventName, args[0], args[1], args[2]);
                    return deferred.promise;

                },

                /**
                 * @method createHasManyRelationship
                 * @param model {Object}
                 * @param fromCollectionName {String}
                 * @param fromProperty {String}
                 * @param toCollectionName {String}
                 * @param toProperty {String}
                 * @param value {Array}
                 * @return {Boolean}
                 */
                createHasManyRelationship: function createHasManyRelationship(model, fromCollectionName, fromProperty, toCollectionName, toProperty, value) {

                },

                /**
                 * @method createHasOneRelationship
                 * @param model {Object}
                 * @param fromCollectionName {String}
                 * @param fromProperty {String}
                 * @param toCollectionName {String}
                 * @param toProperty {String}
                 * @param value {String|Number|Boolean}
                 * @return {Boolean}
                 */
                createHasOneRelationship: function createHasOneRelationship(model, fromCollectionName, fromProperty, toCollectionName, toProperty, value) {

                },

                /**
                 * Responsible for cleaning a model based on the collection's blueprint.
                 *
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Object}
                 */
                cleanModel: function cleanModel(collectionName, model) {

                    var primaryKey         = this._primaryName,
                        blueprint          = this.collection(collectionName).blueprint,
                        iterator           = this._propertyIterator,
                        isRelationship     = this.isRelationship.bind(this),
                        createRelationship = this.createRelationship.bind(this);

                    // Add the primary key to the model.
                    model[primaryKey] = ++this.collection(collectionName).index;

                    /**
                     * @method removeProperties
                     * @return {void}
                     */
                    (function removeProperties() {

                        iterator(model, function iterator(property) {

                            if (!blueprint.hasOwnProperty(property)) {

                                // Remove the property if it's not in the blueprint.
                                delete model[property];

                            }

                        });

                    })();

                    /**
                     * @method addAndTypecastProperties
                     * @return {void}
                     */
                    (function addAndTypecastProperties() {

                        iterator(blueprint, function iterator(property) {

                            // Ignore if it's already been defined, or it's the primary key.
                            if (typeof model[property] === 'undefined' && property !== primaryKey) {

                                // Create the property on the model, and typecast it.
                                model[property] = null;

                            }

                            if (!isRelationship(collectionName, property)) {

                                var typecast = blueprint[property];

                                // Typecast each property accordingly.
                                model[property] = typecast(model[property]);
                                return;

                            }

                            // Now we know we're dealing with a relationship.
                            createRelationship(collectionName, model, property);

                        });

                    })();

                    return model;

                },

                /**
                 * @method createRelationship
                 * @param collectionName {String}
                 * @param model {Object}
                 * @param property {String}
                 * @return {void}
                 */
                createRelationship: function createRelationship(collectionName, model, property) {

                    var localCollection   = this.collection(collectionName),
                        options           = localCollection.blueprint[property].getOptions(),
                        foreignCollection = this.collection(options.collection),
                        store             = this._relationshipStores,
                        internalId        = model[this._primaryName];

                    if (typeof store[internalId] === 'undefined') {

                        // Create the relationship store for the model if it doesn't exist already.
                        store[internalId] = {};

                    }

                    // Attach the property to the model relationship store.
                    store[internalId][property] = model[property] || '';

                    $object.defineProperty(model, property, {

                        /**
                         * @method get
                         * @return {Object}
                         */
                        get: function get() {

                            // Filter the foreign collection by the value we've defined on the local model.
                            foreignCollection.filterBy(options.foreignKey, store[internalId][property]);
                            var foreignModel = foreignCollection[0];
                            foreignCollection.unfilterAll();
                            return foreignModel;

                        },

                        /**
                         * @method set
                         * @param value {Object|Array|Number|Boolean|Date|String|RegExp}
                         * @return {void}
                         */
                        set: function set(value) {
                            store[internalId][property] = value;
                        }

                    });

                },

                /**
                 * @method isRelationship
                 * @param collectionName {String}
                 * @param property {String}
                 * @return {Boolean}
                 */
                isRelationship: function isRelationship(collectionName, property) {

                    var propertyBlueprint = this.collection(collectionName).blueprint[property],
                        relationships     = [ngCatwalkRelationship.One];

                    for (var index in relationships) {

                        if (relationships.hasOwnProperty(index)) {

                            if (propertyBlueprint instanceof relationships[index]) {
                                return true;
                            }

                        }

                    }

                    return false;

                },

                /**
                 * @method _propertyIterator
                 *
                 * @private
                 */
                _propertyIterator: function _propertyIterator(model, iteratorFunction) {

                    for (var property in model) {

                        if (model.hasOwnProperty(property)) {
                            iteratorFunction.call(this, property);
                        }

                    }

                }

            };

            return new Catwalk();

        }]);

})(window.angular, window.Object);<commit_msg>Added initial support for hasMany<commit_after>(function ngCatwalk($angular, $object) {

    "use strict";

    // Bootstrap ngCatwalk!
    var app = $angular.module('ngCatwalk', ['ngCrossfilter']);

    /**
     * @method throwException
     * @param message {String}
     * @return {void}
     */
    var throwException = function throwException(message) {
        throw "ngCatwalk: " + message + ".";
    };

    /**
     * @property ngCatwalkAttribute
     * @type {Object}
     */
    var ngCatwalkAttribute = {

        /**
         * @method any
         * @property defaultValue {Object|Array|Number|Boolean|Date|String|RegExp}
         * @return {Function}
         */
        any: function any(defaultValue) {

            return function(value) {

                if (value === null) {
                    return null;
                }

                return typeof value !== 'undefined' ? value : defaultValue;

            };

        },

        /**
         * @method autoIncrement
         * @return {Function}
         */
        autoIncrement: function autoIncrement() {

            var index = 0;

            return function() {
                return ++index;
            }

        },

        /**
         * @method number
         * @param defaultValue {Number}
         * @returns {Function}
         */
        number: function number(defaultValue) {

            return function(value) {

                if (value === null) {
                    return null;
                }

                return typeof value !== 'undefined' ? +value : defaultValue;

            };

        },

        /**
         * @method string
         * @property defaultValue {String}
         * @returns {Function}
         */
        string: function string(defaultValue) {

            return function(value) {

                if (value === null) {
                    return defaultValue || null;
                }

                return typeof value !== 'undefined' ? String(value) : defaultValue;

            };

        }

    };

    /**
     * @property ngCatwalkRelationship
     * @type {Object}
     */
    var ngCatwalkRelationship = {

        /**
         * @method One
         * @param options {Object}
         * @constructor
         */
        One: function One(options) {

            /**
             * @method getOptions
             * @return {Object}
             */
            this.getOptions = function getOptions() {
                return options;
            }

        },

        /**
         * @method Many
         * @param options {Object}
         * @constructor
         */
        Many: function Many(options) {

            /**
             * @method getOptions
             * @return {Object}
             */
            this.getOptions = function getOptions() {
                return options;
            }

        }

    };

    /**
     * @module ngCatwalk
     * @author Adam Timberlake
     * @link https://github.com/Wildhoney/ngCatwalk
     */
    app.service('catwalk', ['$rootScope', '$q', '$interpolate', 'Crossfilter',

        /**
         * @method CatwalkService
         * @param $rootScope {Object}
         * @param $interpolate {Function}
         * @param $q {Object}
         * @param Crossfilter {Function}
         * @return {Object}
         */
        function CatwalkService($rootScope, $q, $interpolate, Crossfilter) {

            /**
             * @module ngCatwalk
             * @submodule Catwalk
             * @constructor
             */
            function Catwalk() {}

            /**
             * @property prototype
             * @type {Object}
             */
            Catwalk.prototype = {

                /**
                 * @property attribute
                 * @type ngCatwalkAttribute
                 */
                attribute: ngCatwalkAttribute,

                /**
                 * @property relationship
                 * @type {Object}
                 */
                relationship: {

                    /**
                     * @property hasOne
                     * @param options {Object}
                     * @return {ngCatwalkRelationship.One}
                     */
                    hasOne: function hasOne(options) {
                        return new ngCatwalkRelationship.One(options);
                    },

                    /**
                     * @property hasMany
                     * @param options {Object}
                     * @return {ngCatwalkRelationship.Many}
                     */
                    hasMany: function hasMany(options) {
                        return new ngCatwalkRelationship.Many(options);
                    }

                },

                /**
                 * @property _primaryName
                 * @type {String}
                 */
                _primaryName: '_catwalkId',

                /**
                 * @property _relationshipStores
                 * @type {Object}
                 */
                _relationshipStores: {},

                /**
                 * @property _silent
                 * @type {Boolean}
                 */
                _silent: false,

                /**
                 * @property _eventName
                 * @type {String}
                 */
                _eventName: 'catwalk/{{type}}/{{collection}}',

                /**
                 * @property _collections
                 * @type {Object}
                 * @private
                 */
                _collections: {},

                /**
                 * @method collection
                 * @param name {String}
                 * @param properties {Object}
                 * @return {Array}
                 */
                collection: function collection(name, properties) {

                    if (!this._collections[name]) {

                        // Create the empty collection.
                        this._collections[name] = new Crossfilter([]);

                    }

                    if (properties) {

                        // Define the primary key as a number.
                        properties[this._primaryName] = this.attribute.number();

                        // Create the collection if we've defined the properties;
                        this._collections[name].primaryKey(this._primaryName);
                        this._collections[name].blueprint = properties;
                        this._collections[name].index     = 0;

                        for (var property in properties) {

                            if (properties.hasOwnProperty(property)) {

                                // Define the dimension.
                                this._collections[name].addDimension(property);

                            }

                        }

                    }

                    // Otherwise we'll retrieve the collection.
                    return this._collections[name];

                },

                /**
                 * Invokes a CRUD method which normally emits an event. However, when wrapped in the
                 * silently method, the CRUD method behaves as normal, minus the emitting of the event.
                 *
                 * @method silently
                 * @param processFunction {Function}
                 * @return {void}
                 */
                silently: function silently(processFunction) {
                    this._silent = true;
                    processFunction.apply(this);
                    this._silent = false;
                },

                /**
                 * @method createModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Object}
                 */
                createModel: function createModel(collectionName, model) {

                    // Ensure the model conforms with the collection blueprint.
                    model = this.cleanModel(collectionName, model);

                    // Add the model to the collection and generate the promise.
                    this.collection(collectionName).addModel(model);
                    var promise = this.createPromise(collectionName, 'create', [model]);

                    // Promise resolution.
                    promise.then(this.resolveCreateModel(collectionName, model).bind(this));
                    promise.catch(this.rejectCreateModel(collectionName, model).bind(this));

                    return model;

                },

                /**
                 * @method rejectCreateModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Function}
                 */
                rejectCreateModel: function rejectCreateModel(collectionName, model) {

                    return function rejectPromise() {

                        this.silently(function silentlyDelete() {
                            this.collection(collectionName).deleteModel(model);
                        });

                    };

                },

                /**
                 * @method resolveCreateModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Function}
                 */
                resolveCreateModel: function resolveCreateModel(collectionName, model) {

                    return function resolvePromise(properties) {

                        var blueprint = this.collection(collectionName).blueprint;

                        this._propertyIterator(properties, function iterator(property) {

                            var typecast = blueprint[property];

                            // Don't add properties to the model if it hasn't been defined in
                            // the blueprint.
                            if (typeof typecast === 'undefined') {
                                return;
                            }

                            // Overwrite the value with the one specified in the resolution of
                            // the related promise.
                            model[property] = typecast(properties[property]);

                        });

                    };

                },

                /**
                 * @method updateModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @param properties {Object}
                 * @return {Object}
                 */
                updateModel: function updateModel(collectionName, model, properties) {

                },

                /**
                 * @method resolveUpdateModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Object}
                 */
                resolveUpdateModel: function resolveUpdateModel(collectionName, model) {

                },

                /**
                 * @method rejectUpdateModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @param oldProperties {Object}
                 * @return {Object}
                 */
                rejectUpdateModel: function rejectUpdateModel(collectionName, model, oldProperties) {

                },

                /**
                 * @method deleteModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Object}
                 */
                deleteModel: function deleteModel(collectionName, model) {

                    // Add the model to the collection and generate the promise.
                    this.collection(collectionName).deleteModel(model);
                    var promise = this.createPromise(collectionName, 'delete', [model]);

                    // Promise resolution.
                    promise.then(this.resolveDeleteModel(collectionName, model).bind(this));
                    promise.catch(this.rejectDeleteModel(collectionName, model).bind(this));

                    return model;

                },

                /**
                 * @method resolveDeleteModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Object}
                 */
                resolveDeleteModel: function resolveDeleteModel(collectionName, model) {

                    return function resolvePromise() {};

                },

                /**
                 * @method rejectDeleteModel
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Object}
                 */
                rejectDeleteModel: function rejectDeleteModel(collectionName, model) {

                    return function rejectPromise() {

                        this.silently(function silentlyRestore() {
                            this.collection(collectionName).restoreModel(model);
                        });

                    };

                },

                /**
                 * @method createPromise
                 * @param collectionName {String}
                 * @param type {String}
                 * @param args {Array}
                 * @return {$q.promise}
                 */
                createPromise: function createPromise(collectionName, type, args) {

                    var deferred = $q.defer();

                    if (!Array.isArray(args)) {

                        // Ensure the `args` variable is an array.
                        args = args ? [args] : [];

                    }

                    // Attach the promise for the developer to resolve or reject.
                    args.unshift(deferred);

                    // Create and broadcast the event.
                    var eventName = $interpolate(this._eventName)({ type: type, collection: collectionName });
                    $rootScope.$broadcast(eventName, args[0], args[1], args[2]);
                    return deferred.promise;

                },

                /**
                 * @method createHasManyRelationship
                 * @param model {Object}
                 * @param fromCollectionName {String}
                 * @param fromProperty {String}
                 * @param toCollectionName {String}
                 * @param toProperty {String}
                 * @param value {Array}
                 * @return {Boolean}
                 */
                createHasManyRelationship: function createHasManyRelationship(model, fromCollectionName, fromProperty, toCollectionName, toProperty, value) {

                },

                /**
                 * @method createHasOneRelationship
                 * @param model {Object}
                 * @param fromCollectionName {String}
                 * @param fromProperty {String}
                 * @param toCollectionName {String}
                 * @param toProperty {String}
                 * @param value {String|Number|Boolean}
                 * @return {Boolean}
                 */
                createHasOneRelationship: function createHasOneRelationship(model, fromCollectionName, fromProperty, toCollectionName, toProperty, value) {

                },

                /**
                 * Responsible for cleaning a model based on the collection's blueprint.
                 *
                 * @param collectionName {String}
                 * @param model {Object}
                 * @return {Object}
                 */
                cleanModel: function cleanModel(collectionName, model) {

                    var primaryKey         = this._primaryName,
                        blueprint          = this.collection(collectionName).blueprint,
                        iterator           = this._propertyIterator,
                        isRelationship     = this.isRelationship.bind(this),
                        createRelationship = this.createRelationship.bind(this);

                    // Add the primary key to the model.
                    model[primaryKey] = ++this.collection(collectionName).index;

                    /**
                     * @method removeProperties
                     * @return {void}
                     */
                    (function removeProperties() {

                        iterator(model, function iterator(property) {

                            if (!blueprint.hasOwnProperty(property)) {

                                // Remove the property if it's not in the blueprint.
                                delete model[property];

                            }

                        });

                    })();

                    /**
                     * @method addAndTypecastProperties
                     * @return {void}
                     */
                    (function addAndTypecastProperties() {

                        iterator(blueprint, function iterator(property) {

                            // Ignore if it's already been defined, or it's the primary key.
                            if (typeof model[property] === 'undefined' && property !== primaryKey) {

                                // Create the property on the model, and typecast it.
                                model[property] = null;

                            }

                            if (!isRelationship(collectionName, property)) {

                                var typecast = blueprint[property];

                                // Typecast each property accordingly.
                                model[property] = typecast(model[property]);
                                return;

                            }

                            // Now we know we're dealing with a relationship.
                            createRelationship(collectionName, model, property);

                        });

                    })();

                    return model;

                },

                /**
                 * @method createRelationship
                 * @param collectionName {String}
                 * @param model {Object}
                 * @param property {String}
                 * @return {void}
                 */
                createRelationship: function createRelationship(collectionName, model, property) {

                    var localCollection   = this.collection(collectionName),
                        options           = localCollection.blueprint[property].getOptions(),
                        foreignCollection = this.collection(options.collection),
                        store             = this._relationshipStores,
                        internalId        = model[this._primaryName];

                    if (typeof store[internalId] === 'undefined') {

                        // Create the relationship store for the model if it doesn't exist already.
                        store[internalId] = {};

                    }

                    // Attach the property to the model relationship store.
                    store[internalId][property] = model[property] || '';

                    $object.defineProperty(model, property, {

                        /**
                         * @method get
                         * @return {Object}
                         */
                        get: function get() {

                            // Filter the foreign collection by the value we've defined on the local model.
                            foreignCollection.filterBy(options.foreignKey, store[internalId][property]);
                            var foreignModel = foreignCollection[0];
                            foreignCollection.unfilterAll();
                            return foreignModel;

                        },

                        /**
                         * @method set
                         * @param value {Object|Array|Number|Boolean|Date|String|RegExp}
                         * @return {void}
                         */
                        set: function set(value) {
                            store[internalId][property] = value;
                        }

                    });

                },

                /**
                 * @method isRelationship
                 * @param collectionName {String}
                 * @param property {String}
                 * @return {Boolean}
                 */
                isRelationship: function isRelationship(collectionName, property) {

                    var propertyBlueprint = this.collection(collectionName).blueprint[property],
                        relationships     = [ngCatwalkRelationship.One, ngCatwalkRelationship.Many];

                    for (var index in relationships) {

                        if (relationships.hasOwnProperty(index)) {

                            if (propertyBlueprint instanceof relationships[index]) {
                                return true;
                            }

                        }

                    }

                    return false;

                },

                /**
                 * @method _propertyIterator
                 *
                 * @private
                 */
                _propertyIterator: function _propertyIterator(model, iteratorFunction) {

                    for (var property in model) {

                        if (model.hasOwnProperty(property)) {
                            iteratorFunction.call(this, property);
                        }

                    }

                }

            };

            return new Catwalk();

        }]);

})(window.angular, window.Object);<|endoftext|>