<commit_before>'use strict';

const async = require('async');
const path = require('path');
const targz = require('tar.gz');
const logger = require('../../logging').getLogger();
const storage = require('../../storage');
const storeEnvelope = require('./store').storeEnvelope;
const removeEnvelopes = require('./remove').removeEnvelopes;

/**
 * @description Store new content into the content store from an uploaded tarball.
 */
exports.handler = function (req, res, next) {
  const reqStart = Date.now();

  let contentIDBase = null;
  let envelopeCount = 0;
  let deletionCount = 0;
  let toKeep = {};

  const envelopeWorker = (task, cb) => {
    logger.debug('Beginning envelope storage', {
      contentID: task.contentID
    });

    storeEnvelope(task.contentID, task.envelope, cb);
  };

  const uploadQueue = async.queue(envelopeWorker, 4);

  // Log an error and optionally report it to the user.
  const reportError = (err, entryPath, description, fatal) => {
    const logPayload = {
      action: 'bulkcontentstore',
      apikeyName: req.apikeyName,
      entryPath,
      err: err.message,
      stack: err.stack,
      statusCode: 400,
      totalReqDuration: Date.now() - reqStart
    };

    if (fatal) {
      logger.error(`Fatal bulk upload problem: ${description}`, logPayload);

      err.statusCode = 400;

      next(err);
    } else {
      logger.warn(`Bulk upload problem: ${description}`, logPayload);
    }
  };

  // Handle a metadata/config.json entry.
  const handleConfigEntry = (entry) => {
    jsonFromStream(entry, (err, config) => {
      if (err) return reportError(err, entry.path, 'parsing config.json');

      if (!config.contentIDBase) {
        let e = new Error('Missing required key: contentIDBase');
        return reportError(e, entry.path, 'parsing config.json');
      }

      contentIDBase = config.contentIDBase;
    });
  };

  // Handle a metadata/keep.json entry.
  const handleKeepEntry = (entry) => {
    jsonFromStream(entry, (err, keep) => {
      if (err) return reportError(err, entry.path, 'parsing keep.json');

      if (!keep.keep) {
        let e = new Error('Missing required key: keep');
        return reportError(e, entry.path, 'parsing keep.json');
      }

      keep.keep.forEach((contentID) => {
        toKeep[contentID] = true;
      });
    });
  };

  const handleEnvelopeEntry = (entry) => {
    let encodedContentID = path.basename(entry.path, '.json');
    let contentID = decodeURIComponent(encodedContentID);
    toKeep[contentID] = true;

    jsonFromStream(entry, (err, envelope) => {
      if (err) return reportError(err, entry.path, 'parsing metadata envelope');

      // TODO validate envelope contents against a schema

      uploadQueue.push({ contentID, envelope }, (err) => {
        if (err) return reportError(err, entry.path, 'storing metadata envelope');

        envelopeCount++;

        logger.debug('Envelope stored successfully', {
          entryPath: entry.path,
          contentID,
          envelopeCount
        });
      });
    });
  };

  const removeDeletedContent = (cb) => {
    if (!contentIDBase) {
      logger.debug('Skipping content deletion.');
      return cb(null);
    }

    let existingContentIDs = [];

    storage.listContent(contentIDBase, (err, ids, next) => {
      if (err) return cb(err);

      if (ids.length > 0) {
        // Page of content.
        existingContentIDs = existingContentIDs.concat(ids);
        next();
      } else {
        // All content consumed.
        let toDelete = existingContentIDs.filter((id) => !toKeep[id]);
        deletionCount = toDelete.length;

        logger.debug('Deleting removed envelopes.', {
          deletionCount
        });

        removeEnvelopes(toDelete, (err, results) => {
          if (err) return cb(err);

          logger.debug('Envelopes deleted.', results);

          cb();
        });
      }
    });
  };

  const reportCompletion = () => {
    logger.info('Bulk content upload completed successfully.', {
      action: 'bulkcontentstore',
      apikeyName: req.apikeyName,
      acceptedCount: envelopeCount,
      deletedCount: deletionCount,
      totalReqDuration: Date.now() - reqStart
    });

    res.send(204);
    next();
  };

  const parse = targz().createParseStream();

  parse.on('entry', (entry) => {
    if (entry.type !== 'File') return;

    let dirs = path.dirname(entry.path).split(path.sep);
    let dname = dirs[dirs.length - 1];
    let bname = path.basename(entry.path);

    logger.debug('Received entry for path', { path: entry.path });

    if (dname === 'metadata') {
      // metadata/ entries
      switch (bname) {
        case 'config.json':
          handleConfigEntry(entry);
          break;
        case 'keep.json':
          handleKeepEntry(entry);
          break;
        default:
          logger.warn('Unrecognized metadata entry', {
            entryPath: entry.path
          });
          break;
      }
    } else if (bname.endsWith('.json')) {
      handleEnvelopeEntry(entry);
    } else {
      logger.warn('Unrecognized entry', {
        entryPath: entry.path
      });
    }
  });

  parse.on('error', (err) => {
    logger.info('Corrupted tarball uploaded', {
      err: err.message,
      stack: err.stack
    });

    res.send(400, err);

    next();
  });

  parse.on('end', () => {
    removeDeletedContent((err) => {
      if (err) return reportError(err, null, 'deleted content removal', true);

      reportCompletion();
    });
  });

  req.pipe(parse);
};

const jsonFromStream = function (stream, callback) {
  let chunks = [];

  stream.on('data', (chunk) => chunks.push(chunk));
  stream.on('error', callback);
  stream.on('end', () => {
    try {
      let b = Buffer.concat(chunks, stream.size);
      let s = b.toString('utf-8');
      let payload = JSON.parse(s);
      return callback(null, payload);
    } catch (err) {
      return callback(err);
    }
  });
};
<commit_msg>Report completion after the queue drains.<commit_after>'use strict';

const async = require('async');
const path = require('path');
const targz = require('tar.gz');
const logger = require('../../logging').getLogger();
const storage = require('../../storage');
const storeEnvelope = require('./store').storeEnvelope;
const removeEnvelopes = require('./remove').removeEnvelopes;

/**
 * @description Store new content into the content store from an uploaded tarball.
 */
exports.handler = function (req, res, next) {
  const reqStart = Date.now();

  let contentIDBase = null;
  let envelopeCount = 0;
  let deletionCount = 0;
  let toKeep = {};

  const envelopeWorker = (task, cb) => {
    logger.debug('Beginning envelope storage', {
      contentID: task.contentID
    });

    storeEnvelope(task.contentID, task.envelope, cb);
  };

  const uploadQueue = async.queue(envelopeWorker, 4);

  // Log an error and optionally report it to the user.
  const reportError = (err, entryPath, description, fatal) => {
    const logPayload = {
      action: 'bulkcontentstore',
      apikeyName: req.apikeyName,
      entryPath,
      err: err.message,
      stack: err.stack,
      statusCode: 400,
      totalReqDuration: Date.now() - reqStart
    };

    if (fatal) {
      logger.error(`Fatal bulk upload problem: ${description}`, logPayload);

      err.statusCode = 400;

      next(err);
    } else {
      logger.warn(`Bulk upload problem: ${description}`, logPayload);
    }
  };

  // Handle a metadata/config.json entry.
  const handleConfigEntry = (entry) => {
    jsonFromStream(entry, (err, config) => {
      if (err) return reportError(err, entry.path, 'parsing config.json');

      if (!config.contentIDBase) {
        let e = new Error('Missing required key: contentIDBase');
        return reportError(e, entry.path, 'parsing config.json');
      }

      contentIDBase = config.contentIDBase;
    });
  };

  // Handle a metadata/keep.json entry.
  const handleKeepEntry = (entry) => {
    jsonFromStream(entry, (err, keep) => {
      if (err) return reportError(err, entry.path, 'parsing keep.json');

      if (!keep.keep) {
        let e = new Error('Missing required key: keep');
        return reportError(e, entry.path, 'parsing keep.json');
      }

      keep.keep.forEach((contentID) => {
        toKeep[contentID] = true;
      });
    });
  };

  const handleEnvelopeEntry = (entry) => {
    let encodedContentID = path.basename(entry.path, '.json');
    let contentID = decodeURIComponent(encodedContentID);
    toKeep[contentID] = true;

    jsonFromStream(entry, (err, envelope) => {
      if (err) return reportError(err, entry.path, 'parsing metadata envelope');

      // TODO validate envelope contents against a schema

      uploadQueue.push({ contentID, envelope }, (err) => {
        if (err) return reportError(err, entry.path, 'storing metadata envelope');

        envelopeCount++;

        logger.debug('Envelope stored successfully', {
          entryPath: entry.path,
          contentID,
          envelopeCount
        });
      });
    });
  };

  const removeDeletedContent = (cb) => {
    if (!contentIDBase) {
      logger.debug('Skipping content deletion.');
      return cb(null);
    }

    let existingContentIDs = [];

    storage.listContent(contentIDBase, (err, ids, next) => {
      if (err) return cb(err);

      if (ids.length > 0) {
        // Page of content.
        existingContentIDs = existingContentIDs.concat(ids);
        next();
      } else {
        // All content consumed.
        let toDelete = existingContentIDs.filter((id) => !toKeep[id]);
        deletionCount = toDelete.length;

        logger.debug('Deleting removed envelopes.', {
          deletionCount
        });

        removeEnvelopes(toDelete, (err, results) => {
          if (err) return cb(err);

          logger.debug('Envelopes deleted.', results);

          cb();
        });
      }
    });
  };

  const reportCompletion = () => {
    logger.info('Bulk content upload completed successfully.', {
      action: 'bulkcontentstore',
      apikeyName: req.apikeyName,
      acceptedCount: envelopeCount,
      deletedCount: deletionCount,
      totalReqDuration: Date.now() - reqStart
    });

    res.send(204);
    next();
  };

  const parse = targz().createParseStream();

  parse.on('entry', (entry) => {
    if (entry.type !== 'File') return;

    let dirs = path.dirname(entry.path).split(path.sep);
    let dname = dirs[dirs.length - 1];
    let bname = path.basename(entry.path);

    logger.debug('Received entry for path', { path: entry.path });

    if (dname === 'metadata') {
      // metadata/ entries
      switch (bname) {
        case 'config.json':
          handleConfigEntry(entry);
          break;
        case 'keep.json':
          handleKeepEntry(entry);
          break;
        default:
          logger.warn('Unrecognized metadata entry', {
            entryPath: entry.path
          });
          break;
      }
    } else if (bname.endsWith('.json')) {
      handleEnvelopeEntry(entry);
    } else {
      logger.warn('Unrecognized entry', {
        entryPath: entry.path
      });
    }
  });

  parse.on('error', (err) => {
    logger.info('Corrupted tarball uploaded', {
      err: err.message,
      stack: err.stack
    });

    res.send(400, err);

    next();
  });

  parse.on('end', () => {
    const finishRequest = () => {
      removeDeletedContent((err) => {
        if (err) return reportError(err, null, 'deleted content removal', true);

        reportCompletion();
      });
    };

    if (uploadQueue.running()) {
      uploadQueue.drain = finishRequest;
    } else {
      finishRequest();
    }
  });

  req.pipe(parse);
};

const jsonFromStream = function (stream, callback) {
  let chunks = [];

  stream.on('data', (chunk) => chunks.push(chunk));
  stream.on('error', callback);
  stream.on('end', () => {
    try {
      let b = Buffer.concat(chunks, stream.size);
      let s = b.toString('utf-8');
      let payload = JSON.parse(s);
      return callback(null, payload);
    } catch (err) {
      return callback(err);
    }
  });
};
<|endoftext|>


<commit_before>/*
Copyright 2014 Google Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var base = "http://localhost:8001/api/v1beta1/";

var updateImage = function($http, server) {
  $http.get("http://" + server.ip + ":8080/data.json")
    .success(function(data) {
      server.image = data.image;
      console.log(data);
    })
    .error(function(data) {
      server.image = "";
      console.log(data);
    });
};

var updateServer = function($http, server) {
  $http.get(base + "pods/" + server.id)
    .success(function(data) {
      console.log(data);
      server.ip = data.currentState.hostIP;
      server.labels = data.labels;
      server.host = data.currentState.host.split('.')[0];
      server.status = data.currentState.status;
      server.dockerImage = data.currentState.info["update-demo"].Config.Image;
      updateImage($http, server);
    })
    .error(function(data) {
      console.log(data);
    });
};

var updateData = function($scope, $http) {
  var servers = $scope.servers
  for (var i = 0; i < servers.length; ++i) {
    var server = servers[i];
    updateServer($http, server);
  }
};

var ButtonsCtrl = function ($scope, $http, $interval) {
  $scope.servers = [];
  update($scope, $http);
  $interval(angular.bind({}, update, $scope, $http), 2000);
};

var getServer = function($scope, id) {
  var servers = $scope.servers;
  for (var i = 0; i < servers.length; ++i) {
    if (servers[i].id == id) {
      return servers[i];
    }
  }
  return null;
};

var update = function($scope, $http) {
  if (!$http) {
    console.log("No HTTP!");
    return;
  }
  $http.get(base + "pods")
    .success(function(data) {
      console.log(data);
      var newServers = [];
      for (var i = 0; i < data.items.length; ++i) {
        var server = getServer($scope, data.items[i].id);
        if (server == null) {
          server = { "id": data.items[i].id };
        }
        newServers.push(server);
      }
      $scope.servers = newServers;
      updateData($scope, $http);
    })
    .error(function(data) {
      console.log("ERROR: " + data);
    })
};
<commit_msg>Fix update demo.<commit_after>/*
Copyright 2014 Google Inc. All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

var base = "http://localhost:8001/api/v1beta1/";

var updateImage = function($http, server) {
  $http.get("http://" + server.ip + ":8080/data.json")
    .success(function(data) {
      server.image = data.image;
      console.log(data);
    })
    .error(function(data) {
      server.image = "";
      console.log(data);
    });
};

var updateServer = function($http, server) {
  $http.get(base + "pods/" + server.id)
    .success(function(data) {
      console.log(data);
      server.ip = data.currentState.hostIP;
      server.labels = data.labels;
      server.host = data.currentState.host.split('.')[0];
      server.status = data.currentState.status;
      server.dockerImage = data.currentState.info["update-demo"].detailInfo.Config.Image;
      updateImage($http, server);
    })
    .error(function(data) {
      console.log(data);
    });
};

var updateData = function($scope, $http) {
  var servers = $scope.servers
  for (var i = 0; i < servers.length; ++i) {
    var server = servers[i];
    updateServer($http, server);
  }
};

var ButtonsCtrl = function ($scope, $http, $interval) {
  $scope.servers = [];
  update($scope, $http);
  $interval(angular.bind({}, update, $scope, $http), 2000);
};

var getServer = function($scope, id) {
  var servers = $scope.servers;
  for (var i = 0; i < servers.length; ++i) {
    if (servers[i].id == id) {
      return servers[i];
    }
  }
  return null;
};

var update = function($scope, $http) {
  if (!$http) {
    console.log("No HTTP!");
    return;
  }
  $http.get(base + "pods")
    .success(function(data) {
      console.log(data);
      var newServers = [];
      for (var i = 0; i < data.items.length; ++i) {
        var server = getServer($scope, data.items[i].id);
        if (server == null) {
          server = { "id": data.items[i].id };
        }
        newServers.push(server);
      }
      $scope.servers = newServers;
      updateData($scope, $http);
    })
    .error(function(data) {
      console.log("ERROR: " + data);
    })
};
<|endoftext|>


<commit_before>/**
 * Created by xubt on 4/20/16.
 */

kanbanApp.controller('userController', ['$scope', '$location', '$q', 'publicKeyServices', 'loginService', 'localStorageService', '$uibModal', 'notificationsService', 'usersService', '$interval',
    function ($scope, $location, $q, publicKeyServices, loginService, localStorageService, $uibModal, notificationsService, usersService, $interval) {
        $scope.userName = localStorageService.get("identity.userName");

        var unreadNotificationsTotalLink = usersService.getCurrentUser()._links.unreadNotificationsTotal.href;
        $interval(function () {
            var notificationPromise = notificationsService.loadUnreadNotificationsTotal(unreadNotificationsTotalLink);
            notificationPromise.then(function (_data) {
                $scope.unreadNotificationsTotal = _data.unreadNotificationsTotal;
                $scope.isShowNotification = $scope.unreadNotificationsTotal === 0 ? false : true;
            });
        }, 5000);

        $scope.gotoTeams = function () {
            $location.path(localStorageService.get('identity.userName') + "/teams");
        };
        $scope.loginOut = function () {
            $uibModal.open({
                animation: false,
                templateUrl: 'foundation/modal/partials/confirm-dialog.html',
                controller: function ($scope, $uibModalInstance) {
                    $scope.title = '确认';
                    $scope.message = "确定要退出登录吗?";
                    $scope.ok = function () {
                        localStorageService.clearAll();
                        $uibModalInstance.close();
                        $location.path("/welcome");
                    };
                    $scope.cancel = function () {
                        $uibModalInstance.dismiss('cancel');
                    };
                },
                size: 'sm'
            });
        };
    }]);
<commit_msg>Adding notifications entrance.<commit_after>/**
 * Created by xubt on 4/20/16.
 */

kanbanApp.controller('userController', ['$scope', '$location', '$q', 'publicKeyServices', 'loginService', 'localStorageService', '$uibModal', 'notificationsService', 'usersService', '$interval',
    function ($scope, $location, $q, publicKeyServices, loginService, localStorageService, $uibModal, notificationsService, usersService, $interval) {
        $scope.userName = localStorageService.get("identity.userName");

        var unreadNotificationsTotalLink = usersService.getCurrentUser()._links.unreadNotificationsTotal.href;
        var pollNotifications = $interval(function () {
            var notificationPromise = notificationsService.loadUnreadNotificationsTotal(unreadNotificationsTotalLink);
            notificationPromise.then(function (_data) {
                $scope.unreadNotificationsTotal = _data.unreadNotificationsTotal;
                $scope.isShowNotification = $scope.unreadNotificationsTotal === 0 ? false : true;
                localStorageService.set("notificationsUrl", _data._links.notifications.href);
            }, function () {
                $interval.cancel(pollNotifications);
            });
        }, 5000);

        $scope.gotoTeams = function () {
            $location.path(localStorageService.get('identity.userName') + "/teams");
        };
        $scope.openNotifications = function () {
            $location.path(usersService.getCurrentUser().name + "/notifications");
        };

        $scope.loginOut = function () {
            $uibModal.open({
                animation: false,
                templateUrl: 'foundation/modal/partials/confirm-dialog.html',
                controller: function ($scope, $uibModalInstance) {
                    $scope.title = '确认';
                    $scope.message = "确定要退出登录吗?";
                    $scope.ok = function () {
                        localStorageService.clearAll();
                        $uibModalInstance.close();
                        $location.path("/welcome");
                    };
                    $scope.cancel = function () {
                        $uibModalInstance.dismiss('cancel');
                    };
                },
                size: 'sm'
            });
        };
    }]);
<|endoftext|>


<commit_before>import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import createLogger from 'redux-logger';
import { hashHistory } from 'react-router';
import { routerMiddleware, push } from 'react-router-redux';
import rootReducer from '../reducers';

import * as counterActions from '../actions/counter';

const actionCreators = {
  ...counterActions,
  push,
};

const logger = createLogger({
  level: 'info',
  collapsed: true,
});

const router = routerMiddleware(hashHistory);

const enhancer = compose(
  applyMiddleware(thunk, router, logger),
  window.devToolsExtension ?
    window.devToolsExtension({ actionCreators }) :
    noop => noop
);

export default function configureStore(initialState) {
  const store = createStore(rootReducer, initialState, enhancer);

  if (window.devToolsExtension) {
    window.devToolsExtension.updateStore(store);
  }

  if (module.hot) {
    module.hot.accept('../reducers', () =>
      store.replaceReducer(require('../reducers')) // eslint-disable-line global-require
    );
  }

  return store;
}
<commit_msg>configureStore.development.js - split development modules imports, remove trailing comma<commit_after>import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import { hashHistory } from 'react-router';
import { routerMiddleware, push } from 'react-router-redux';
import rootReducer from '../reducers';

import * as counterActions from '../actions/counter';

const actionCreators = {
  ...counterActions,
  push,
};

// Dev modules
import createLogger from 'redux-logger';

const logger = createLogger({
  level: 'info',
  collapsed: true
});

const router = routerMiddleware(hashHistory);

const enhancer = compose(
  applyMiddleware(thunk, router, logger),
  window.devToolsExtension ?
    window.devToolsExtension({ actionCreators }) :
    noop => noop
);

export default function configureStore(initialState) {
  const store = createStore(rootReducer, initialState, enhancer);

  if (window.devToolsExtension) {
    window.devToolsExtension.updateStore(store);
  }

  if (module.hot) {
    module.hot.accept('../reducers', () =>
      store.replaceReducer(require('../reducers')) // eslint-disable-line global-require
    );
  }

  return store;
}
<|endoftext|>


<commit_before>import options from './options';

/**
 * Create an virtual node (used for JSX)
 * @param {import('./internal').VNode["type"]} type The node name or Component
 * constructor for this virtual node
 * @param {object | null | undefined} [props] The properties of the virtual node
 * @param {Array<import('.').ComponentChildren>} [children] The children of the virtual node
 * @returns {import('./internal').VNode}
 */
export function createElement(type, props, children) {
	let normalizedProps = {},
		i;
	for (i in props) {
		if (i !== 'key' && i !== 'ref') normalizedProps[i] = props[i];
	}

	if (arguments.length > 3) {
		children = [children];
		// https://github.com/preactjs/preact/issues/1916
		for (i = 3; i < arguments.length; i++) {
			children.push(arguments[i]);
		}
	}
	if (children != null) {
		normalizedProps.children = children;
	}

	// If a Component VNode, check for and apply defaultProps
	// Note: type may be undefined in development, must never error here.
	if (typeof type === 'function' && type.defaultProps != null) {
		for (i in type.defaultProps) {
			if (typeof normalizedProps[i] === 'undefined')
				normalizedProps[i] = type.defaultProps[i];
		}
	}

	return createVNode(
		type,
		normalizedProps,
		props && props.key,
		props && props.ref
	);
}

/**
 * Create a VNode (used internally by Preact)
 * @param {import('./internal').VNode["type"]} type The node name or Component
 * Constructor for this virtual node
 * @param {object | string | number | null} props The properties of this virtual node.
 * If this virtual node represents a text node, this is the text of the node (string or number).
 * @param {string | number | null} key The key for this virtual node, used when
 * diffing it against its children
 * @param {import('./internal').VNode["ref"]} ref The ref property that will
 * receive a reference to its created child
 * @returns {import('./internal').VNode}
 */
export function createVNode(type, props, key, ref) {
	// V8 seems to be better at detecting type shapes if the object is allocated from the same call site
	// Do not inline into createElement and coerceToVNode!
	const vnode = {
		type,
		props,
		key,
		ref,
		_children: null,
		_parent: null,
		_depth: 0,
		_dom: null,
		_lastDomChild: null,
		_component: null,
		constructor: undefined
	};

	if (options.vnode) options.vnode(vnode);

	return vnode;
}

export function createRef() {
	return {};
}

export function Fragment(props) {
	return props.children;
}

/**
 * Check if a the argument is a valid Preact VNode.
 * @param {*} vnode
 * @returns {vnode is import('./internal').VNode}
 */
export const isValidElement = vnode =>
	vnode != null && vnode.constructor === undefined;
<commit_msg>remove superfluous typeof<commit_after>import options from './options';

/**
 * Create an virtual node (used for JSX)
 * @param {import('./internal').VNode["type"]} type The node name or Component
 * constructor for this virtual node
 * @param {object | null | undefined} [props] The properties of the virtual node
 * @param {Array<import('.').ComponentChildren>} [children] The children of the virtual node
 * @returns {import('./internal').VNode}
 */
export function createElement(type, props, children) {
	let normalizedProps = {},
		i;
	for (i in props) {
		if (i !== 'key' && i !== 'ref') normalizedProps[i] = props[i];
	}

	if (arguments.length > 3) {
		children = [children];
		// https://github.com/preactjs/preact/issues/1916
		for (i = 3; i < arguments.length; i++) {
			children.push(arguments[i]);
		}
	}
	if (children != null) {
		normalizedProps.children = children;
	}

	// If a Component VNode, check for and apply defaultProps
	// Note: type may be undefined in development, must never error here.
	if (typeof type === 'function' && type.defaultProps != null) {
		for (i in type.defaultProps) {
			if (normalizedProps[i] === undefined) {
				normalizedProps[i] = type.defaultProps[i];
			}
		}
	}

	return createVNode(
		type,
		normalizedProps,
		props && props.key,
		props && props.ref
	);
}

/**
 * Create a VNode (used internally by Preact)
 * @param {import('./internal').VNode["type"]} type The node name or Component
 * Constructor for this virtual node
 * @param {object | string | number | null} props The properties of this virtual node.
 * If this virtual node represents a text node, this is the text of the node (string or number).
 * @param {string | number | null} key The key for this virtual node, used when
 * diffing it against its children
 * @param {import('./internal').VNode["ref"]} ref The ref property that will
 * receive a reference to its created child
 * @returns {import('./internal').VNode}
 */
export function createVNode(type, props, key, ref) {
	// V8 seems to be better at detecting type shapes if the object is allocated from the same call site
	// Do not inline into createElement and coerceToVNode!
	const vnode = {
		type,
		props,
		key,
		ref,
		_children: null,
		_parent: null,
		_depth: 0,
		_dom: null,
		_lastDomChild: null,
		_component: null,
		constructor: undefined
	};

	if (options.vnode) options.vnode(vnode);

	return vnode;
}

export function createRef() {
	return {};
}

export function Fragment(props) {
	return props.children;
}

/**
 * Check if a the argument is a valid Preact VNode.
 * @param {*} vnode
 * @returns {vnode is import('./internal').VNode}
 */
export const isValidElement = vnode =>
	vnode != null && vnode.constructor === undefined;
<|endoftext|>


<commit_before>module.exports = {
  find: function (req, res) {
    Community.fetchAll({withRelated: [
        {memberships: q => q.column('community_id')}
    ]})
    .then(communities => communities.map(c => _.extend(c.toJSON(), {
      memberships: c.relations.memberships.length
    })))
    .then(res.ok, res.serverError)
  },

  findOne: function (req, res) {
    var community = res.locals.community
    var membership = res.locals.membership

    return Promise.method(() => community.get('network_id') ? community.load('network') : null)()
    .then(() => community.pick('id', 'name', 'slug', 'avatar_url', 'banner_url', 'description', 'settings', 'location'))
    .tap(data => {
      var network = community.relations.network
      if (network) data.network = network.pick('id', 'name', 'slug')
    })
    .tap(() => membership && membership.save({last_viewed_at: new Date()}, {patch: true}))
    .then(res.ok)
    .catch(res.serverError)
  },

  findSettings: function (req, res) {
    var leader
    Community.find(req.param('communityId'), {withRelated: ['leader']})
    .tap(community => leader = community.relations.leader)
    .then(community => _.merge(community.pick(
      'welcome_message', 'beta_access_code', 'settings'
    ), {
      leader: leader ? leader.pick('id', 'name', 'avatar_url') : null
    }))
    .then(res.ok)
    .catch(res.serverError)
  },

  update: function (req, res) {
    var whitelist = [
      'banner_url', 'avatar_url', 'name', 'description', 'settings',
      'welcome_message', 'leader_id', 'beta_access_code', 'location'
    ]
    var attributes = _.pick(req.allParams(), whitelist)
    var saneAttrs = _.clone(attributes)
    var community = new Community({id: req.param('communityId')})

    if (attributes.settings) {
      saneAttrs.settings = _.merge({}, community.get('settings'), attributes.settings)
    }

    community.save(saneAttrs, {patch: true})
    .then(() => res.ok({}))
    .catch(res.serverError)
  },

  findModerators: function (req, res) {
    Community.find(req.param('communityId')).then(function (community) {
      return community.moderators().fetch()
    }).then(function (moderators) {
      res.ok(moderators.map(function (user) {
        return {
          id: user.id,
          name: user.get('name'),
          avatar_url: user.get('avatar_url')
        }
      }))
    })
  },

  addModerator: function (req, res) {
    Membership.setModeratorRole(req.param('userId'), req.param('communityId'))
    .then(() => res.ok({}))
    .catch(res.serverError)
  },

  removeModerator: function (req, res) {
    Membership.removeModeratorRole(req.param('userId'), req.param('communityId'))
    .then(() => res.ok({}))
    .catch(res.serverError)
  },

  joinWithCode: function (req, res) {
    var community
    return Community.query('whereRaw', 'lower(beta_access_code) = lower(?)', req.param('code')).fetch()
    .tap(c => community = c)
    .tap(() => bookshelf.transaction(trx => Promise.join(
      Membership.create(req.session.userId, community.id, {transacting: trx}),
      Post.createWelcomePost(req.session.userId, community.id, trx)
    )))
    .catch(err => {
      if (err.message && err.message.includes('duplicate key value')) {
        return true
      } else {
        res.serverError(err)
        return false
      }
    })
    // we get here if the membership was created successfully, or if it already existed
    .then(ok => ok && Membership.find(req.session.userId, community.id, {includeInactive: true})
      .tap(membership => !membership.get('active') && membership.save({active: true}, {patch: true}))
      .then(membership => _.merge(membership.toJSON(), {
        community: community.pick('id', 'name', 'slug', 'avatar_url')
      }))
      .then(res.ok))
  },

  leave: function (req, res) {
    res.locals.membership.destroy()
    .then(() => res.ok({}))
    .catch(res.serverError)
  },

  removeMember: function (req, res) {
    Membership.query().where({
      user_id: req.param('userId'),
      community_id: req.param('communityId')
    }).update({
      active: false,
      deactivated_at: new Date(),
      deactivator_id: req.session.userId
    })
    .then(() => res.ok({}))
    .catch(res.serverError)
  },

  validate: function (req, res) {
    return Validation.validate(_.pick(req.allParams(), 'constraint', 'column', 'value'),
      Community, ['name', 'slug', 'beta_access_code'], ['exists', 'unique'])
    .then(validation => {
      if (validation.badRequest) {
        return res.badRequest(validation.badRequest)
      } else {
        return res.ok(validation)
      }
    })
    .catch(res.serverError)
  },

  create: function (req, res) {
    var attrs = _.pick(req.allParams(),
      'name', 'description', 'slug', 'category',
      'beta_access_code', 'banner_url', 'avatar_url', 'location')

    var community = new Community(_.merge(attrs, {
      created_at: new Date(),
      created_by_id: req.session.userId
    }))

    community.set('leader_id', req.session.userId)
    community.set('welcome_message', 'Thank you for joining us here at Hylo. ' +
      'Through our communities, we can find everything we need. If we share ' +
      'with each other the unique gifts and intentions we each have, we can ' +
      "create extraordinary things. Let's get started!")
    community.set('settings', {sends_email_prompts: true})

    return bookshelf.transaction(trx => {
      return community.save(null, {transacting: trx})
      .tap(community => community.createStarterPosts(trx)
        .catch(err => {
          if (err.message !== 'Starter posts community not found') throw err
        }))
      .then(() => Membership.create(req.session.userId, community.id, {
        role: Membership.MODERATOR_ROLE,
        transacting: trx
      }))
    })
    // Any assets were uploaded to /community/new, since we didn't have an id;
    // copy them over to /community/:id now
    .tap(() => Queue.classMethod('Community', 'copyAssets', {communityId: community.id}))
    .tap(() => Queue.classMethod('Community', 'notifyAboutCreate', {communityId: community.id}))
    .tap(() => Tour.skipOnboarding(req.session.userId))
    .then(membership => _.extend(membership.toJSON(), {community: community}))
    .then(res.ok)
    .catch(res.serverError)
  },

  findForNetwork: function (req, res) {
    var total

    return Network.find(req.param('networkId'))
    .then(network => {
      if (req.param('paginate')) {
        return Community.query(qb => {
          qb.where('network_id', network.get('id'))
          qb.limit(req.param('limit') || 10)
          qb.offset(req.param('offset') || 0)
          qb.select(bookshelf.knex.raw('community.*, count(*) over () as total'))
        })
        .fetchAll({withRelated: ['memberships']})
      } else {
        return Community.where('network_id', network.get('id'))
        .fetchAll({withRelated: ['memberships']})
      }
    })
    .tap(communities => total = (communities.length > 0 ? communities.first().get('total') : 0))
    .then(communities => communities.map(c => _.extend(c.pick('id', 'name', 'slug', 'avatar_url', 'banner_url'), {
      memberCount: c.relations.memberships.length
    })))
    .then(communities => _.sortBy(communities, c => -c.memberCount))
    .then(communities => {
      if (req.param('paginate')) {
        return {communities_total: total, communities: communities}
      } else {
        return communities
      }
    })
    .then(res.ok)
    .catch(res.serverError)
  }
}
<commit_msg>add correct ordering to pagination results<commit_after>module.exports = {
  find: function (req, res) {
    Community.fetchAll({withRelated: [
        {memberships: q => q.column('community_id')}
    ]})
    .then(communities => communities.map(c => _.extend(c.toJSON(), {
      memberships: c.relations.memberships.length
    })))
    .then(res.ok, res.serverError)
  },

  findOne: function (req, res) {
    var community = res.locals.community
    var membership = res.locals.membership

    return Promise.method(() => community.get('network_id') ? community.load('network') : null)()
    .then(() => community.pick('id', 'name', 'slug', 'avatar_url', 'banner_url', 'description', 'settings', 'location'))
    .tap(data => {
      var network = community.relations.network
      if (network) data.network = network.pick('id', 'name', 'slug')
    })
    .tap(() => membership && membership.save({last_viewed_at: new Date()}, {patch: true}))
    .then(res.ok)
    .catch(res.serverError)
  },

  findSettings: function (req, res) {
    var leader
    Community.find(req.param('communityId'), {withRelated: ['leader']})
    .tap(community => leader = community.relations.leader)
    .then(community => _.merge(community.pick(
      'welcome_message', 'beta_access_code', 'settings'
    ), {
      leader: leader ? leader.pick('id', 'name', 'avatar_url') : null
    }))
    .then(res.ok)
    .catch(res.serverError)
  },

  update: function (req, res) {
    var whitelist = [
      'banner_url', 'avatar_url', 'name', 'description', 'settings',
      'welcome_message', 'leader_id', 'beta_access_code', 'location'
    ]
    var attributes = _.pick(req.allParams(), whitelist)
    var saneAttrs = _.clone(attributes)
    var community = new Community({id: req.param('communityId')})

    if (attributes.settings) {
      saneAttrs.settings = _.merge({}, community.get('settings'), attributes.settings)
    }

    community.save(saneAttrs, {patch: true})
    .then(() => res.ok({}))
    .catch(res.serverError)
  },

  findModerators: function (req, res) {
    Community.find(req.param('communityId')).then(function (community) {
      return community.moderators().fetch()
    }).then(function (moderators) {
      res.ok(moderators.map(function (user) {
        return {
          id: user.id,
          name: user.get('name'),
          avatar_url: user.get('avatar_url')
        }
      }))
    })
  },

  addModerator: function (req, res) {
    Membership.setModeratorRole(req.param('userId'), req.param('communityId'))
    .then(() => res.ok({}))
    .catch(res.serverError)
  },

  removeModerator: function (req, res) {
    Membership.removeModeratorRole(req.param('userId'), req.param('communityId'))
    .then(() => res.ok({}))
    .catch(res.serverError)
  },

  joinWithCode: function (req, res) {
    var community
    return Community.query('whereRaw', 'lower(beta_access_code) = lower(?)', req.param('code')).fetch()
    .tap(c => community = c)
    .tap(() => bookshelf.transaction(trx => Promise.join(
      Membership.create(req.session.userId, community.id, {transacting: trx}),
      Post.createWelcomePost(req.session.userId, community.id, trx)
    )))
    .catch(err => {
      if (err.message && err.message.includes('duplicate key value')) {
        return true
      } else {
        res.serverError(err)
        return false
      }
    })
    // we get here if the membership was created successfully, or if it already existed
    .then(ok => ok && Membership.find(req.session.userId, community.id, {includeInactive: true})
      .tap(membership => !membership.get('active') && membership.save({active: true}, {patch: true}))
      .then(membership => _.merge(membership.toJSON(), {
        community: community.pick('id', 'name', 'slug', 'avatar_url')
      }))
      .then(res.ok))
  },

  leave: function (req, res) {
    res.locals.membership.destroy()
    .then(() => res.ok({}))
    .catch(res.serverError)
  },

  removeMember: function (req, res) {
    Membership.query().where({
      user_id: req.param('userId'),
      community_id: req.param('communityId')
    }).update({
      active: false,
      deactivated_at: new Date(),
      deactivator_id: req.session.userId
    })
    .then(() => res.ok({}))
    .catch(res.serverError)
  },

  validate: function (req, res) {
    return Validation.validate(_.pick(req.allParams(), 'constraint', 'column', 'value'),
      Community, ['name', 'slug', 'beta_access_code'], ['exists', 'unique'])
    .then(validation => {
      if (validation.badRequest) {
        return res.badRequest(validation.badRequest)
      } else {
        return res.ok(validation)
      }
    })
    .catch(res.serverError)
  },

  create: function (req, res) {
    var attrs = _.pick(req.allParams(),
      'name', 'description', 'slug', 'category',
      'beta_access_code', 'banner_url', 'avatar_url', 'location')

    var community = new Community(_.merge(attrs, {
      created_at: new Date(),
      created_by_id: req.session.userId
    }))

    community.set('leader_id', req.session.userId)
    community.set('welcome_message', 'Thank you for joining us here at Hylo. ' +
      'Through our communities, we can find everything we need. If we share ' +
      'with each other the unique gifts and intentions we each have, we can ' +
      "create extraordinary things. Let's get started!")
    community.set('settings', {sends_email_prompts: true})

    return bookshelf.transaction(trx => {
      return community.save(null, {transacting: trx})
      .tap(community => community.createStarterPosts(trx)
        .catch(err => {
          if (err.message !== 'Starter posts community not found') throw err
        }))
      .then(() => Membership.create(req.session.userId, community.id, {
        role: Membership.MODERATOR_ROLE,
        transacting: trx
      }))
    })
    // Any assets were uploaded to /community/new, since we didn't have an id;
    // copy them over to /community/:id now
    .tap(() => Queue.classMethod('Community', 'copyAssets', {communityId: community.id}))
    .tap(() => Queue.classMethod('Community', 'notifyAboutCreate', {communityId: community.id}))
    .tap(() => Tour.skipOnboarding(req.session.userId))
    .then(membership => _.extend(membership.toJSON(), {community: community}))
    .then(res.ok)
    .catch(res.serverError)
  },

  findForNetwork: function (req, res) {
    var total

    return Network.find(req.param('networkId'))
    .then(network => {
      if (req.param('paginate')) {
        return Community.query(qb => {
          qb.where('network_id', network.get('id'))
          qb.select(bookshelf.knex.raw('community.slug, count(users_community.user_id) as "memberCount", count(community.id) over () as total'))
          qb.leftJoin('users_community', function () {
            this.on('community.id', '=', 'users_community.community_id')
          })
          qb.groupBy('community.id')
          qb.orderBy('memberCount', 'desc')
          qb.limit(req.param('limit') || 20)
          qb.offset(req.param('offset') || 0)
        }).fetchAll()
        .tap(communities => total = (communities.length > 0 ? communities.first().get('total') : 0))
      } else {
        return Community.where('network_id', network.get('id'))
        .fetchAll({withRelated: ['memberships']})
        .then(communities => communities.map(c => _.extend(c.pick('id', 'name', 'slug', 'avatar_url', 'banner_url'), {
          memberCount: c.relations.memberships.length
        })))
        .then(communities => _.sortBy(communities, c => -c.memberCount))
      }
    })
    .then(communities => {
      if (req.param('paginate')) {
        return {communities_total: total, communities: communities}
      } else {
        return communities
      }
    })
    .then(res.ok)
    .catch(res.serverError)
  }
}
<|endoftext|>


<commit_before>require([
  "libs/text", // part of require js
  "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js",
  "libs/ejs_production"
  ],
    function(until)
    {
      require([
      "//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js",
      "libs/jquery.form"]);

      $.getJSON("api/phoxy", function(data)
      {
        phoxy.config = data;
        requirejs.config({baseUrl: phoxy.Config()['js_dir']});

        $('script[phoxy]').each(function()
        {
          phoxy.ApiRequest($(this).attr("phoxy"));
        });
      });
    }
  );

function PhoxyHashChangeCallback()
{
  if (phoxy.ChangeHash(location.hash))
    phoxy.ApiRequest(phoxy.hash);
}

var phoxy =
{
  loaded : false,
  hash : false,
  Load : function( )
    {
      this.loaded = true;
      var hash = location.hash.substring(1);
      if (hash.length)
        phoxy.ApiRequest(hash);
      $(window).bind('hashchange', PhoxyHashChangeCallback);
    }
  ,
  Defer : function(callback, time)
  {
    if (time == undefined)
      time = 0;
    var th = this;
    setTimeout(function()
    {
      callback.call(th);
    }, time);
  }
  ,
  WaitFor : function(callback_condition, callback, timeout, check_every)
    {
      var
        check_timeout = 60, // 1 minute for render to complete
        check_delay = 500; // check every 500ms

      if (timeout != undefined)
        check_timeout = timeout;
      if (check_every != undefined)
        check_delay = check_every;

      var func = function()
      {
        if (!callback_condition())
          return;
        callback();
      }
      if (callback_condition())
        return func();

      function WaitAndCallCountDown( i )
      {
        if (i <= 0)
          return func();

        phoxy.Defer(function()
        {
          if (callback_condition())
            i = 0;
          WaitAndCallCountDown(i - 1);
        }, check_delay);
      }

      WaitAndCallCountDown(check_timeout * 1000 / check_delay);
    }
  ,
  Appeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function IsDivAppeared()
      {
        return $(phoxy.OptimiseSelector(jquery_selector))[0] != undefined;
      }

      phoxy.WaitFor(IsDivAppeared, function()
      {
        phoxy.Defer(callback, call_delay);
      }, timeout);
    }
  ,
  Disappeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function IsDivDisappeared()
      {
        return $(phoxy.OptimiseSelector(jquery_selector))[0] == undefined;
      }

      phoxy.WaitFor(IsDivDisappeared, function()
      {
        phoxy.Defer(callback, call_delay);
      }, timeout);
    }
  ,
  GenerateUniqueID : function()
    {
      var ret = "";
      var dictonary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for (var i = 0; i < 10; i++)
        ret += dictonary.charAt(Math.floor(Math.random() * dictonary.length));

      return ret;
    }
  ,
  DeferRender : function (ejs, data, rendered_callback)
    {
      function GetElementCode( el )
      {
        return $(el).wrapAll('

').parent().html();
      }

      var id = phoxy.GenerateUniqueID();
      var div = GetElementCode($('
').attr('id', id).attr("data-debug_comment", "Staged for defer loading. Will be anigilated soon."));

      var func;

      if (typeof(data) == 'undefined')
      { // single param call
        if (typeof(ejs) == 'object')
        { // called as constructed object
          func = function()
          {
            ejs.result = id;
            phoxy.ApiAnswer(ejs, rendered_callback);
          };
        }
        else
        { // called as phoxy rpc
          func = function()
          {
            phoxy.AJAX(ejs, function( ata, callback)
            {
              data.result = id;
              phoxy.ApiAnswer(data, callback);
            }, [rendered_callback]);
          };
        }
      }
      else
      { // called as design submodule (only ejs string and that data)
        func = function()
        {
          phoxy.ApiAnswer({design : ejs, "data" : data, replace : id}, rendered_callback);
        };
      }

      phoxy.Appeared('#' + id, func);
      return div;
    }
  ,
  ChangeHash : function (hash)
    {
      var t;
      t = hash.split(location.origin)[1];
      if (t !== undefined)
        hash = t;
      var t = hash.split('#')[1];
      if (t !== undefined)
        hash = t;
      var ret = phoxy.hash != hash;
      phoxy.hash = hash;
      location.hash = hash;
      return ret;
    }
  ,
  Reset : function (url)
    {
      if (url == true || url == "true")
        location.reload();
      var parts = url.split('#');
      if (parts[1] == undefined)
        phoxy.ChangeHash('');
      else
        phoxy.ChangeHash("#" + parts[1]);
      var host = parts[0];
      if (host.length)
        location = host;
      else
        location.reload(parts[0]);
    }
  ,
  Render : function (design, result, data)
    {
      if (data === undefined)
        data = {};

      var html = new EJS({'url' : design}).render(data);
      if (result != undefined && result != '')
        $("#" + result).replaceWith(html);
      return html;
    }
  ,
  ApiAnswer : function( answer, callback )
    {
      if (answer.hash !== undefined)
      {
        if (answer.hash === null)
          answer.hash = "";
        this.ChangeHash(answer.hash);
      }
      if (answer.error)
      {
        alert(answer.error);
        if (answer.reset !== undefined)
          phoxy.Reset(answer.reset);
        return;
      }
      if (answer.reset !== undefined)
        phoxy.Reset(answer.reset);
      if (answer.script)
      {
        require(answer.script,
          function()
          {
            phoxy.ScriptsLoaded(answer, callback);
          }
        );
      }
      else
        phoxy.ScriptsLoaded(answer, callback);
    }
  ,
  ScriptsLoaded : function( answer, callback )
    {
      function ScriptsFiresUp()
      {
        if (answer.routeline !== undefined)
          window[answer.routeline](answer.data);
        if (callback)
          callback(answer.data);
        if (!phoxy.loaded)
          phoxy.Load();
      }
      if (answer.design === undefined)
        return ScriptsFiresUp();

      var id = phoxy.GenerateUniqueID();
      var render_id = id;

      var element =
        $('
')
        .attr('id', id)
        .attr('data-debug_comment', "Staged for render. Will be anigilated soon.");

      var url = phoxy.Config()['ejs_dir'] + "/" + answer.design;
      phoxy.ForwardDownload(url + ".ejs", function()
      {
        if (answer.replace === undefined)
          if (answer.result === undefined)
            $('body').append(element);
          else
            $('#' + answer.result).html(element);
        else
          render_id = answer.replace;

        phoxy.Render(
          url,
          render_id,
          answer.data);

        phoxy.Disappeared('#' + id, ScriptsFiresUp);
      });
    }
  ,
  ForwardDownload : function( url, callback )
  {
    $.get(url, callback);
  }
  ,
  AJAX : function( url, callback, params )
    {
      $(function()
      {
        $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            if (params == undefined)
              params = [];
            params.unshift(data);
            callback.apply(this, params);
          });
      });
    }
  ,
  ApiRequest : function( url, callback )
    {
      if (callback == undefined)
        phoxy.AJAX(url, phoxy.ApiAnswer);
      else
        phoxy.AJAX(url, phoxy.ApiAnswer, [callback]);
    }
  ,
  MenuCall : function( url, callback )
    {
        $(function()
        {
          $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            phoxy.ChangeHash(url);
            phoxy.ApiAnswer(data, callback);
          });
        });
    }
  ,
  Config : function()
    {
      return this.config;
    }
  ,
  OptimiseSelector : function( str )
    { // http://learn.jquery.com/performance/optimize-selectors/
      if (typeof(str) != 'string')
        return str;

      var last_id_tag = str.lastIndexOf('#');
      if (last_id_tag > 0)
        str = str.substr(last_id_tag);
      var elements = str.split(" ");
      var ret = $(elements[0]);
      var i = 0;
      while (++i < elements.length)
        if (elements[i].length != 0)
          ret = ret.find(elements[i]);
      return ret;
    }
}
<commit_msg>Appeared context - finded elements<commit_after>require([
  "libs/text", // part of require js
  "//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js",
  "libs/ejs_production"
  ],
    function(until)
    {
      require([
      "//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js",
      "libs/jquery.form"]);

      $.getJSON("api/phoxy", function(data)
      {
        phoxy.config = data;
        requirejs.config({baseUrl: phoxy.Config()['js_dir']});

        $('script[phoxy]').each(function()
        {
          phoxy.ApiRequest($(this).attr("phoxy"));
        });
      });
    }
  );

function PhoxyHashChangeCallback()
{
  if (phoxy.ChangeHash(location.hash))
    phoxy.ApiRequest(phoxy.hash);
}

var phoxy =
{
  loaded : false,
  hash : false,
  Load : function( )
    {
      this.loaded = true;
      var hash = location.hash.substring(1);
      if (hash.length)
        phoxy.ApiRequest(hash);
      $(window).bind('hashchange', PhoxyHashChangeCallback);
    }
  ,
  Defer : function(callback, time)
  {
    if (time == undefined)
      time = 0;
    var th = this;
    setTimeout(function()
    {
      callback.call(th);
    }, time);
  }
  ,
  WaitFor : function(callback_condition, callback, timeout, check_every)
    {
      var
        check_timeout = 60, // 1 minute for render to complete
        check_delay = 500; // check every 500ms

      if (timeout != undefined)
        check_timeout = timeout;
      if (check_every != undefined)
        check_delay = check_every;

      var func = function()
      {
        if (!callback_condition())
          return;
        callback();
      }
      if (callback_condition())
        return func();

      function WaitAndCallCountDown( i )
      {
        if (i <= 0)
          return func();

        phoxy.Defer(function()
        {
          if (callback_condition())
            i = 0;
          WaitAndCallCountDown(i - 1);
        }, check_delay);
      }

      WaitAndCallCountDown(check_timeout * 1000 / check_delay);
    }
  ,
  Appeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function Div()
      {
        return $(phoxy.OptimiseSelector(jquery_selector));
      }
      function IsDivAppeared()
      {
        return Div()[0] != undefined;
      }

      phoxy.WaitFor(IsDivAppeared, function()
      {
        phoxy.Defer.call(Div(), callback, call_delay);
      }, timeout);
    }
  ,
  Disappeared : function(jquery_selector, callback, timeout, call_delay)
    {
      function IsDivDisappeared()
      {
        return $(phoxy.OptimiseSelector(jquery_selector))[0] == undefined;
      }

      phoxy.WaitFor(IsDivDisappeared, function()
      {
        phoxy.Defer(callback, call_delay);
      }, timeout);
    }
  ,
  GenerateUniqueID : function()
    {
      var ret = "";
      var dictonary = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for (var i = 0; i < 10; i++)
        ret += dictonary.charAt(Math.floor(Math.random() * dictonary.length));

      return ret;
    }
  ,
  DeferRender : function (ejs, data, rendered_callback)
    {
      function GetElementCode( el )
      {
        return $(el).wrapAll('

').parent().html();
      }

      var id = phoxy.GenerateUniqueID();
      var div = GetElementCode($('
').attr('id', id).attr("data-debug_comment", "Staged for defer loading. Will be anigilated soon."));

      var func;

      if (typeof(data) == 'undefined')
      { // single param call
        if (typeof(ejs) == 'object')
        { // called as constructed object
          func = function()
          {
            ejs.result = id;
            phoxy.ApiAnswer(ejs, rendered_callback);
          };
        }
        else
        { // called as phoxy rpc
          func = function()
          {
            phoxy.AJAX(ejs, function( ata, callback)
            {
              data.result = id;
              phoxy.ApiAnswer(data, callback);
            }, [rendered_callback]);
          };
        }
      }
      else
      { // called as design submodule (only ejs string and that data)
        func = function()
        {
          phoxy.ApiAnswer({design : ejs, "data" : data, replace : id}, rendered_callback);
        };
      }

      phoxy.Appeared('#' + id, func);
      return div;
    }
  ,
  ChangeHash : function (hash)
    {
      var t;
      t = hash.split(location.origin)[1];
      if (t !== undefined)
        hash = t;
      var t = hash.split('#')[1];
      if (t !== undefined)
        hash = t;
      var ret = phoxy.hash != hash;
      phoxy.hash = hash;
      location.hash = hash;
      return ret;
    }
  ,
  Reset : function (url)
    {
      if (url == true || url == "true")
        location.reload();
      var parts = url.split('#');
      if (parts[1] == undefined)
        phoxy.ChangeHash('');
      else
        phoxy.ChangeHash("#" + parts[1]);
      var host = parts[0];
      if (host.length)
        location = host;
      else
        location.reload(parts[0]);
    }
  ,
  Render : function (design, result, data)
    {
      if (data === undefined)
        data = {};

      var html = new EJS({'url' : design}).render(data);
      if (result != undefined && result != '')
        $("#" + result).replaceWith(html);
      return html;
    }
  ,
  ApiAnswer : function( answer, callback )
    {
      if (answer.hash !== undefined)
      {
        if (answer.hash === null)
          answer.hash = "";
        this.ChangeHash(answer.hash);
      }
      if (answer.error)
      {
        alert(answer.error);
        if (answer.reset !== undefined)
          phoxy.Reset(answer.reset);
        return;
      }
      if (answer.reset !== undefined)
        phoxy.Reset(answer.reset);
      if (answer.script)
      {
        require(answer.script,
          function()
          {
            phoxy.ScriptsLoaded(answer, callback);
          }
        );
      }
      else
        phoxy.ScriptsLoaded(answer, callback);
    }
  ,
  ScriptsLoaded : function( answer, callback )
    {
      function ScriptsFiresUp()
      {
        if (answer.routeline !== undefined)
          window[answer.routeline](answer.data);
        if (callback)
          callback(answer.data);
        if (!phoxy.loaded)
          phoxy.Load();
      }
      if (answer.design === undefined)
        return ScriptsFiresUp();

      var id = phoxy.GenerateUniqueID();
      var render_id = id;

      var element =
        $('
')
        .attr('id', id)
        .attr('data-debug_comment', "Staged for render. Will be anigilated soon.");

      var url = phoxy.Config()['ejs_dir'] + "/" + answer.design;
      phoxy.ForwardDownload(url + ".ejs", function()
      {
        if (answer.replace === undefined)
          if (answer.result === undefined)
            $('body').append(element);
          else
            $('#' + answer.result).html(element);
        else
          render_id = answer.replace;

        phoxy.Render(
          url,
          render_id,
          answer.data);

        phoxy.Disappeared('#' + id, ScriptsFiresUp);
      });
    }
  ,
  ForwardDownload : function( url, callback )
  {
    $.get(url, callback);
  }
  ,
  AJAX : function( url, callback, params )
    {
      $(function()
      {
        $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            if (params == undefined)
              params = [];
            params.unshift(data);
            callback.apply(this, params);
          });
      });
    }
  ,
  ApiRequest : function( url, callback )
    {
      if (callback == undefined)
        phoxy.AJAX(url, phoxy.ApiAnswer);
      else
        phoxy.AJAX(url, phoxy.ApiAnswer, [callback]);
    }
  ,
  MenuCall : function( url, callback )
    {
        $(function()
        {
          $.getJSON(phoxy.Config()['api_dir'] + "/" + url, function(data)
          {
            phoxy.ChangeHash(url);
            phoxy.ApiAnswer(data, callback);
          });
        });
    }
  ,
  Config : function()
    {
      return this.config;
    }
  ,
  OptimiseSelector : function( str )
    { // http://learn.jquery.com/performance/optimize-selectors/
      if (typeof(str) != 'string')
        return str;

      var last_id_tag = str.lastIndexOf('#');
      if (last_id_tag > 0)
        str = str.substr(last_id_tag);
      var elements = str.split(" ");
      var ret = $(elements[0]);
      var i = 0;
      while (++i < elements.length)
        if (elements[i].length != 0)
          ret = ret.find(elements[i]);
      return ret;
    }
}
<|endoftext|>


<commit_before>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*
 *  This is a small ComponentJS plugin which just logs all
 *  captured tracing tuples to the console.
 */

/* global ComponentJS:false */
/* jshint unused:false */

ComponentJS.plugin("tracing-console", function (_cs, $cs, GLOBAL) {
    /*  ensure the tracing plugin is present  */
    if (!$cs.plugin("tracing"))
        throw _cs.exception("plugin:tracing-console", "sorry, required 'tracing' plugin not found");

    /*  log the tracing information to the console  */
    _cs.latch("ComponentJS:tracing", function (tracing) {
        if (   typeof GLOBAL.console     !== "undefined"
            && typeof GLOBAL.console.log !== "undefined") {

            /*  stringify component name or path  */
            var nameofcomp = function (comp) {
                if      (comp === _cs.none)     comp = "<none>";
                else if (comp === _cs.internal) comp = "<internal>";
                else                            comp = comp.path("/");
                return comp;
            };
            var source = nameofcomp(tracing.source());
            var origin = nameofcomp(tracing.origin());

            /*  stringify component type(s)  */
            var typeofcomp = function (type) {
                var txt = "";
                if (type.view)       txt += "V";
                if (type.model)      txt += "M";
                if (type.controller) txt += "C";
                if (type.service)    txt += "S";
                if (txt === "")      txt =  "-";
                return txt;
            };
            var sourceType = typeofcomp(tracing.sourceType());
            var originType = typeofcomp(tracing.originType());

            /*  stringify parameters  */
            var params = "";
            var p = tracing.parameters();
            for (var name in p) {
                if (params !== "")
                    params += ", ";
                params += name + ": " + JSON.stringify(p[name]);
            }
            if (params !== "")
                params = "{ " + params + " }";
            else
                params = "{}";

            /*  print the tracing tuple to the console  */
            GLOBAL.console.log("TRACING: " +
                "#" + tracing.id + ": < " +
                source + ", " +
                sourceType + ", " +
                origin + ", " +
                originType + ", " +
                tracing.operation() + ", " +
                params + " >"
            );
        }
    });
});

<commit_msg>Added timestamp to console logging plugin<commit_after>/*
**  ComponentJS -- Component System for JavaScript <http://componentjs.com>
**  Copyright (c) 2009-2013 Ralf S. Engelschall <http://engelschall.com>
**
**  This Source Code Form is subject to the terms of the Mozilla Public
**  License, v. 2.0. If a copy of the MPL was not distributed with this
**  file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

/*
 *  This is a small ComponentJS plugin which just logs all
 *  captured tracing tuples to the console.
 */

/* global ComponentJS:false */
/* jshint unused:false */

ComponentJS.plugin("tracing-console", function (_cs, $cs, GLOBAL) {
    /*  ensure the tracing plugin is present  */
    if (!$cs.plugin("tracing"))
        throw _cs.exception("plugin:tracing-console", "sorry, required 'tracing' plugin not found");

    /*  log the tracing information to the console  */
    _cs.latch("ComponentJS:tracing", function (tracing) {
        if (   typeof GLOBAL.console     !== "undefined"
            && typeof GLOBAL.console.log !== "undefined") {

            /*  stringify component name or path  */
            var nameofcomp = function (comp) {
                if      (comp === _cs.none)     comp = "<none>";
                else if (comp === _cs.internal) comp = "<internal>";
                else                            comp = comp.path("/");
                return comp;
            };
            var source = nameofcomp(tracing.source());
            var origin = nameofcomp(tracing.origin());

            /*  stringify component type(s)  */
            var typeofcomp = function (type) {
                var txt = "";
                if (type.view)       txt += "V";
                if (type.model)      txt += "M";
                if (type.controller) txt += "C";
                if (type.service)    txt += "S";
                if (txt === "")      txt =  "-";
                return txt;
            };
            var sourceType = typeofcomp(tracing.sourceType());
            var originType = typeofcomp(tracing.originType());

            /*  stringify parameters  */
            var params = "";
            var p = tracing.parameters();
            for (var name in p) {
                if (params !== "")
                    params += ", ";
                params += name + ": " + JSON.stringify(p[name]);
            }
            if (params !== "")
                params = "{ " + params + " }";
            else
                params = "{}";

            /*  print the tracing tuple to the console  */
            GLOBAL.console.log("TRACING: " +
                "#" + tracing.id + ": < " +
                tracing.timestamp() + ", " +
                source + ", " +
                sourceType + ", " +
                origin + ", " +
                originType + ", " +
                tracing.operation() + ", " +
                params + " >"
            );
        }
    });
});

<|endoftext|>


<commit_before>/**
 * @author Justin White
 * The formula for accessing methods and properties from box2d were adapted from
 * http://www.jeremyhubble.com/box2d.html
 * The method calls to box2d.js used in PhysicsSystem.js do not exactly match up to
 * the methods outlined in the above url since the box2d versions used differ between the url
 * and this project.
 */

goog.provide('CrunchJS.Systems.PhysicsSystem');
goog.require('box2d.World');
goog.require('CrunchJS.System');
goog.require('box2d.World');
goog.require('box2d.AABB');
goog.require('box2d.Vec2');
goog.require('box2d.PolyShape');
goog.require('box2d.CircleDef');
goog.require('box2d.BodyDef');
goog.require('box2d.Shape');//Provides method for finding x coorid of body in World
/**
 * Creates the Physics System
 * @extends {CrunchJS.System}
 * @constructor
 * @class Physics System
 */
CrunchJS.Systems.PhysicsSystem = function() {
	goog.base(this);
};

goog.inherits(CrunchJS.Systems.PhysicsSystem, CrunchJS.System);

CrunchJS.Systems.PhysicsSystem.prototype.name = 'PhysicsSystem';

CrunchJS.Systems.PhysicsSystem.prototype.activate = function() {
	goog.base(this, 'activate');
	this.setEntityComposition(this.getScene().createEntityComposition().one('ExampleComp', 'ExampleComp1').exclude('ExampleComp'));
};

/**
 *
    var b2AABB = box2d.AABB;
	var worldAABB = new b2AABB();
	var b2Vec2 = box2d.Vec2;
	worldAABB.minVertex.Set(-1000, -1000);
	worldAABB.maxVertex.Set(1000, 1000);
	var gravity = new b2Vec2(0, 0);
	var doSleep = true;
	var world = new box2d.World(worldAABB, gravity, doSleep);
	console.log(world);
 *
 *
 *
 *
 */

//var canvasw;
// CrunchJS.Systems.PhysicsSystem.prototype = function setcanvaswidth(canvaswidth){
// 	return canvasw = canvaswidth;
// }

// var canvash;
// function setcanvaswidth(canvaswidth){
// 	return canvash = canvaswidth;
// }

/**
 * Initializes world and objects.  Sets regular interval
 */
CrunchJS.Systems.PhysicsSystem.prototype.init = function (){

	var worldAABB = new box2d.AABB();
	worldAABB.minVertex.Set(-1000, -1000);
	worldAABB.maxVertex.Set(1000, 1000);
	var gravity = new box2d.Vec2(0, 0);
	var doSleep = true;
	var world = new box2d.World(worldAABB, gravity, doSleep);
	this.addCircle(5, world);
	return world;

	//This will be called from the scene not from the init() function
	/**
	 * Calls update() method repeatedly at the rate indiciated by the int passed into the method
	 * @type {int}
	 */
	//window.setInterval(update(world), (1000/50));
};

 /**
 * Helper method to get collisions that have happened during that step
 */
//b is linked list of bodies in world
CrunchJS.Systems.PhysicsSystem.prototype.collisionCollect = function (b){
	//var edge = b.GetContactList();
	//return edge;
	//can iterate over edges to evaluate the collisions that happened
};

/**
 * main function
 * called at the regular interval as defined in init()
 * edits the transform component once an object moves after a step()
 */
CrunchJS.Systems.PhysicsSystem.prototype.update = function (world){

	var timeStep = 1.0/60;
	var iteration = 1;
	world.Step(timeStep, iteration);
	var node = world.GetBodyList();
	CrunchJS.world.log(world, CrunchJS.LogLevels.DEBUG);
	CrunchJS.world.log(node, CrunchJS.LogLevels.DEBUG);
	//var listCollisions = this.collisionCollect(node);

		while (node){
			var b = node;
			node = node.GetNext();

			var shape = b.GetShapeList();
			while (shape){
				var shape1 = shape;
				shape = shape.GetNext();

				if (shape1 != null){

					var shapeType = shape1.GetType();

					//CrunchJS.world.log(shapeType + " test1", CrunchJS.LogLevels.DEBUG);

				//ensures that the current shape is a circle object
				if (shapeType === box2d.ShapeDef.Type.circleShape){

					//This gets the x and y cooridiniate of each circle object in the world
					var position = shape1.GetPosition();
					CrunchJS.world.log(position, CrunchJS.LogLevels.DEBUG);

				}

				}
			}
		}

		this.addCircle(4, world);
};
//TO DO: Have to adjust how vertexes are added to Box2D world
/**
 * Adds rectangle to Box2D simulation
 * Sets width, height, mass, and placement of object
 * Creates object in Box2D world
 * @param {int} canvaswidth
 * @param {int} canvasheight
 */
// CrunchJS.Systems.PhysicsSystem.prototype = function addRectangle(canvaswidth, canvasheight, world){
// 	//create rectangle
// 	var canvaswidth = 100;
// 	var canvasheight = 100;
// 	var bodyDef = new box2d.BodyDef();
// 	bodyDef.type = box2d.b2Body.b2_dynamicBody;
// 	var scale = 30;
//
////fixDef() doesnt exist in this version of box2D we are using
//
// 	bodyDef.position.x = (canvaswidth - scale*2)*Math.random()+scale*2;
// 	bodyDef.position.y = canvasheight - (scale*Math.random() +scale);
// 	world.CreateBody(bodyDef).CreateFixture(fixDef);
// };

CrunchJS.Systems.PhysicsSystem.prototype.addCircle = function (radius, world){
	var circleSd = new box2d.CircleDef();
	circleSd.density = 1.0;
	circleSd.radius = radius;
	circleSd.restitution = 1.0;
	circleSd.friction = 0;
	var circleBd = new box2d.BodyDef();
	circleBd.AddShape(circleSd);
	circleBd.position.Set(50,50);
	var circleBody = world.CreateBody(circleBd);

	//Add new physics component representing this circle in box2d world

};

/**
 * Adds force to objectID over time
 * @param  {String} objectID id of object
 * @param  {int} degree    angle of force to be applied
 * @param  {int} power     magnitude of the force
 */
CrunchJS.Systems.PhysicsSystem.prototype.addForce = function (objectID, degree, power){
	var body = this.bodiesMap[objectID];
	body.ApplyForce(new box2d.Vec2(Math.cos(degree * (Math.PI / 180)) * power,
        Math.sin(degree * (Math.PI / 180)) * power),
        body.GetWorldCenter());
};

/**
 * Adds force to objectID within in physics simulation
 *
 * ApplyImpulse method signiture from Box2D file
 * box2d.Body.prototype.ApplyImpulse = function(impulse, point)
 *
 * @param {int} objectID Entity
 * @param {vector} v is a vector composed of x and y components representing velocity in each direction
 */
CrunchJS.Systems.PhysicsSystem.prototype.addImpulse = function (objectID, degree, power){
	var body = this.bodiesMap[objectID];
    body.ApplyImpulse(new box2d.Vec2(Math.cos(degree * (Math.PI / 180)) * power,
        Math.sin(degree * (Math.PI / 180)) * power),
        body.GetWorldCenter());
};

/**
 * Stops the execution of the setInterval
 * @param  {int} intervalVariable global variable set by initial setInterval() call
 */
CrunchJS.Systems.PhysicsSystem.prototype.cancelUpdate = function (intervalVariable){
	clearInterval(intervalVariable);
};<commit_msg>Made skeleton for physics process<commit_after>/**
 * @author Justin White
 * The formula for accessing methods and properties from box2d were adapted from
 * http://www.jeremyhubble.com/box2d.html
 * The method calls to box2d.js used in PhysicsSystem.js do not exactly match up to
 * the methods outlined in the above url since the box2d versions used differ between the url
 * and this project.
 */

goog.provide('CrunchJS.Systems.PhysicsSystem');
goog.require('CrunchJS.System');
goog.require('box2d.World');
goog.require('CrunchJS.System');
goog.require('box2d.World');
goog.require('box2d.AABB');
goog.require('box2d.Vec2');
goog.require('box2d.PolyShape');
goog.require('box2d.CircleDef');
goog.require('box2d.BodyDef');
goog.require('box2d.Shape');//Provides method for finding x coorid of body in World
/**
 * Creates the Physics System
 * @extends {CrunchJS.System}
 * @constructor
 * @class Physics System
 */
CrunchJS.Systems.PhysicsSystem = function() {
	this.phys = new goog.structs.Set();
};

goog.inherits(CrunchJS.Systems.PhysicsSystem, CrunchJS.System);

CrunchJS.Systems.PhysicsSystem.prototype.name = 'PhysicsSystem';

CrunchJS.Systems.PhysicsSystem.prototype.activate = function() {
	goog.base(this, 'activate');
	this.physComp = this.getScene().createEntityComposition().all('PhysicsComponent');
	this.setEntityComposition(this.getScene().createEntityComposition().one('Transform', 'Body', 'Physics'));//.exclude('ExampleComp')
	var box2dWorld = this.init();
};

CrunchJS.Systems.PhysicsSystem.prototype.process = function(frame) {
	goog.structs.forEach(this.phys, function(physId) {
		var physComp = this.getScene().getComponent(physID, 'PhysicsComponent');

		goog.structs.forEach(this.getActiveEntities(), function(ent) {

		//if physics component has a correspondinng body in box2d

		//update box2d objects to match component's values
		physComp.updateBox2dBody(ent);
		//else create a body in box2d to match new physics component
		box2dWorld.addRectangle(ent);
		}, this);

	}, this);

	//step physics world
	this.update(box2dWorld);

	//update physics component with updated values from box2d
	goog.structs.forEach(this.phys, function(physId) {
		var physComp = this.getScene().getComponent(physID, 'PhysicsComponent');

		goog.structs.forEach(this.getActiveEntities(), function(ent) {

		//if physics component has different value then corresponding box2d body

		//update physics component to match box2d's values
		physComp.updatePhysComponent(ent);
		}, this);

	}, this);
}

/**
 *
    var b2AABB = box2d.AABB;
	var worldAABB = new b2AABB();
	var b2Vec2 = box2d.Vec2;
	worldAABB.minVertex.Set(-1000, -1000);
	worldAABB.maxVertex.Set(1000, 1000);
	var gravity = new b2Vec2(0, 0);
	var doSleep = true;
	var world = new box2d.World(worldAABB, gravity, doSleep);
	console.log(world);
 *
 *
 *
 *
 */

//var canvasw;
// CrunchJS.Systems.PhysicsSystem.prototype = function setcanvaswidth(canvaswidth){
// 	return canvasw = canvaswidth;
// }

// var canvash;
// function setcanvaswidth(canvaswidth){
// 	return canvash = canvaswidth;
// }

/**
 * Initializes world and objects.
 */
CrunchJS.Systems.PhysicsSystem.prototype.init = function (){

	var worldAABB = new box2d.AABB();
	worldAABB.minVertex.Set(-1000, -1000);
	worldAABB.maxVertex.Set(1000, 1000);
	var gravity = new box2d.Vec2(0, 0);
	var doSleep = true;
	var world = new box2d.World(worldAABB, gravity, doSleep);
	this.addCircle(5, world);
	return world;

	//This will be called from the scene not from the init() function
	/**
	 * Calls update() method repeatedly at the rate indiciated by the int passed into the method
	 * @type {int}
	 */
	//window.setInterval(update(world), (1000/50));
};

 /**
 * Helper method to get collisions that have happened during that step
 */
//b is linked list of bodies in world
CrunchJS.Systems.PhysicsSystem.prototype.collisionCollect = function (b){
	//var edge = b.GetContactList();
	//return edge;
	//can iterate over edges to evaluate the collisions that happened
};

/**
 * main function
 * called at the regular interval as defined in init()
 * edits the transform component once an object moves after a step()
 */
CrunchJS.Systems.PhysicsSystem.prototype.update = function (world){

	var timeStep = 1.0/60;
	var iteration = 1;
	world.Step(timeStep, iteration);
	var node = world.GetBodyList();
	CrunchJS.world.log(world, CrunchJS.LogLevels.DEBUG);
	CrunchJS.world.log(node, CrunchJS.LogLevels.DEBUG);
	//var listCollisions = this.collisionCollect(node);

		while (node){
			var b = node;
			node = node.GetNext();

			var shape = b.GetShapeList();

			while (shape){
				var shape1 = shape;
				shape = shape.GetNext();

				if (shape1 != null){

					var shapeType = shape1.GetType();

					//CrunchJS.world.log(shapeType + " test1", CrunchJS.LogLevels.DEBUG);

				//ensures that the current shape is a circle object
				if (shapeType === box2d.ShapeDef.Type.circleShape){
					CrunchJS.world.log(node.GetUserData(), CrunchJS.LogLevels.DEBUG);
					//This gets the x and y cooridiniate of each circle object in the world
					var position = shape1.GetPosition();
					CrunchJS.world.log(position, CrunchJS.LogLevels.DEBUG);
					//Update the physics components with the updated positions

				}

				}
			}
		}

		this.addCircle(4, world);
};
//TO DO: Have to adjust how vertexes are added to Box2D world
/**
 * Adds rectangle to Box2D simulation
 * Sets width, height, mass, and placement of object
 * Creates object in Box2D world
 * @param {int} canvaswidth
 * @param {int} canvasheight
 */
// CrunchJS.Systems.PhysicsSystem.prototype = function addRectangle(canvaswidth, canvasheight, world){
// 	//create rectangle
// 	var canvaswidth = 100;
// 	var canvasheight = 100;
// 	var bodyDef = new box2d.BodyDef();
// 	bodyDef.type = box2d.b2Body.b2_dynamicBody;
// 	var scale = 30;
//
////fixDef() doesnt exist in this version of box2D we are using
//
// 	bodyDef.position.x = (canvaswidth - scale*2)*Math.random()+scale*2;
// 	bodyDef.position.y = canvasheight - (scale*Math.random() +scale);
// 	world.CreateBody(bodyDef).CreateFixture(fixDef);
// };

CrunchJS.Systems.PhysicsSystem.prototype.addCircle = function (radius, world){
	var circleSd = new box2d.CircleDef();
	circleSd.density = 1.0;
	circleSd.radius = radius;
	circleSd.restitution = 1.0;
	circleSd.friction = 0;
	var circleBd = new box2d.BodyDef();
	circleBd.AddShape(circleSd);
	circleBd.position.Set(50,50);
	circleBd.userData = 1;
	var circleBody = world.CreateBody(circleBd);

	//Add new physics component representing this circle in box2d world

};

/**
 * Adds force to objectID over time
 * @param  {String} objectID id of object
 * @param  {int} degree    angle of force to be applied
 * @param  {int} power     magnitude of the force
 */
CrunchJS.Systems.PhysicsSystem.prototype.addForce = function (objectID, degree, power){
	var body = this.bodiesMap[objectID];
	body.ApplyForce(new box2d.Vec2(Math.cos(degree * (Math.PI / 180)) * power,
        Math.sin(degree * (Math.PI / 180)) * power),
        body.GetWorldCenter());
};

/**
 * Adds force to objectID within in physics simulation
 *
 * ApplyImpulse method signiture from Box2D file
 * box2d.Body.prototype.ApplyImpulse = function(impulse, point)
 *
 * @param {int} objectID Entity
 * @param {vector} v is a vector composed of x and y components representing velocity in each direction
 */
CrunchJS.Systems.PhysicsSystem.prototype.addImpulse = function (objectID, degree, power){
	var body = this.bodiesMap[objectID];
    body.ApplyImpulse(new box2d.Vec2(Math.cos(degree * (Math.PI / 180)) * power,
        Math.sin(degree * (Math.PI / 180)) * power),
        body.GetWorldCenter());
};

/**
 * Stops the execution of the setInterval
 * @param  {int} intervalVariable global variable set by initial setInterval() call
 */
CrunchJS.Systems.PhysicsSystem.prototype.cancelUpdate = function (intervalVariable){
	clearInterval(intervalVariable);
};<|endoftext|>


<commit_before>// https://gist.github.com/mojodna/1251812

const models = require("../../models");
const log = require('../utils/logger');
const toJson = require('../utils/to_json');
const async = require('async');

let airbrake = null;

if(process.env.AIRBRAKE_PROJECT_ID) {
  airbrake = require('../utils/airbrake');
}

const generatePostNotification = require('../engine/notifications/generate_post_notifications.js');
const generatePointNotification = require('../engine/notifications/generate_point_notifications.js');
const generateRecommendationEvent = require('../engine/recommendations/events_manager').generateRecommendationEvent;
const generatePostStatusChangeNotification = require('../engine/notifications/generate_post_status_change_notifications.js');

const ActivityWorker = function () {};

ActivityWorker.prototype.process = (activityJson, callback) => {
  let activity;
  log.info('Processing activity Started');
  async.series([
    (seriesCallback) => {
      models.AcActivity.find({
        where: { id: activityJson.id },
        include: [
          {
            model: models.User,
            attributes: ['id','notifications_settings','email','name','created_at'],
            required: false
          },
          {
            model: models.Domain,
            required: false
          },
          {
            model: models.Community,
            required: false
          },
          {
            model: models.Group,
            required: false
          },
          {
            model: models.Post,
            required: false
          },
          {
            model: models.Point,
            required: false,
            include: [
              {
                model: models.Post,
                required: false
              }
            ]
          }
        ]
      }).then((results) => {
        if (results) {
          activity = results;
          seriesCallback();
        } else {
          seriesCallback('Activity not found');
        }
      }).catch((error) => {
        seriesCallback(error);
      });
    },
    (seriesCallback) => {
      log.info('Processing Activity Started', {type: activity.type});
      try {
        switch (activity.type) {
          case "activity.user.invite":
            models.AcNotification.createNotificationFromActivity(activity.actor.user_id, activity, "notification.user.invite", "priority", 70, (error) => {
              log.info('Processing activity.user.invite Completed', {type: activity.type, err: error});
              seriesCallback(error);
            });
            break;
          case "activity.password.recovery":
            models.AcNotification.createNotificationFromActivity(activity.actor.user, activity, "notification.password.recovery", "priority", 100, (error) => {
              log.info('Processing activity.password.recovery Completed', {type: activity.type, err: error});
              seriesCallback(error);
            });
            break;
          case "activity.password.changed":
            models.AcNotification.createNotificationFromActivity(activity.actor.user, activity, "notification.password.changed", "priority", 100, (error) => {
              log.info('Processing activity.password.changed Completed', {type: activity.type, err: error});
              seriesCallback(error);
            });
            break;
          case "activity.system.generalUserNotification":
            models.AcNotification.createNotificationFromActivity(activity.actor.userId, activity, "notification.generalUserNotification", "priority", 100, (error) => {
              log.info('Processing activity.system.generalUserNotification', {type: activity.type, err: error});
              seriesCallback(error);
            });
            break;
          case "activity.report.content":
            models.AcNotification.createReportNotifications(activity.actor.user, activity, (error) => {
              log.info('Processing activity.report.content Completed', {type: activity.type, err: error});
              seriesCallback(error);
            });
            break;
          case "activity.bulk.status.update":
            models.AcNotification.createNotificationFromActivity(activity.actor.user, activity, "notification.bulk.status.update", "priority", 100,  (error) => {
              log.info('Processing activity.bulk.status.update Completed', {type: activity.type, err: error});
              seriesCallback(error);
            });
            break;
          case "activity.post.new":
          case "activity.post.opposition.new":
          case "activity.post.endorsement.new":
            generatePostNotification(activity, activity.User,  (error) => {
              if (error) {
                log.error('Processing activity.post.* Error', {type: activity.type, err: error});
                seriesCallback(error);
              } else {
                log.info('Processing activity.post.* Completed', {type: activity.type});
                seriesCallback();
              }
            });
            break;
          case "Xactivity.point.new":
          case "Xactivity.point.helpful.new":
          case "Xactivity.point.unhelpful.new":
          case "Xactivity.point.newsStory.new":
          case "Xactivity.point.comment.new":
            generatePointNotification(activity, activity.User,  (error) => {
              if (error) {
                log.error('Processing activity.point.* Completed', {type: activity.type, err: error});
                seriesCallback(error);
              } else {
                log.info('Processing activity.point.* Completed', {type: activity.type});
                seriesCallback();
              }
            });
            break;
          case "activity.post.status.change":
            if (activity.object && activity.object.bulkStatusUpdate) {
              log.info('Processing activity.post.status.change not creating notifications', {type: activity.type});
              seriesCallback();
            } else {
              generatePostStatusChangeNotification(activity, activity.User, (error) => {
                if (error) {
                  log.error('Processing activity.post.status.change Completed', {type: activity.type, err: error});
                  seriesCallback(error);
                } else {
                  log.info('Processing activity.post.status.change Completed', {type: activity.type});
                  seriesCallback();
                }
              });
            }
            break;
          default:
            seriesCallback();
        }
      } catch (error) {
        log.error("Processing Activity Error", {err: error});
        seriesCallback(error);
      }
    },

    (seriesCallback) => {
      generateRecommendationEvent(activity, seriesCallback);
    }
  ],  (error) => {
    if (error) {
      log.error("Processing Activity Error", {err: error});
      if (airbrake) {
        airbrake.notify(error).then((airbrakeErr)=> {
          if (airbrakeErr.error) {
            log.error("AirBrake Error", { context: 'airbrake', err: airbrakeErr.error, errorStatus: 500 });
          }
          callback(error);
        });
      } else {
        callback(error);
      }
    } else {
      log.info('Processing Activity and Recommendation Completed', {type: activity.type});
      callback();
    }
  });
};

module.exports = new ActivityWorker();
<commit_msg>Work on debug<commit_after>// https://gist.github.com/mojodna/1251812

const models = require("../../models");
const log = require('../utils/logger');
const toJson = require('../utils/to_json');
const async = require('async');

let airbrake = null;

if(process.env.AIRBRAKE_PROJECT_ID) {
  airbrake = require('../utils/airbrake');
}

const generatePostNotification = require('../engine/notifications/generate_post_notifications.js');
const generatePointNotification = require('../engine/notifications/generate_point_notifications.js');
const generateRecommendationEvent = require('../engine/recommendations/events_manager').generateRecommendationEvent;
const generatePostStatusChangeNotification = require('../engine/notifications/generate_post_status_change_notifications.js');

const ActivityWorker = function () {};

ActivityWorker.prototype.process = (activityJson, callback) => {
  let activity;
  log.info('Processing activity Started');
  async.series([
    (seriesCallback) => {
      models.AcActivity.find({
        where: { id: activityJson.id },
        include: [
          {
            model: models.User,
            attributes: ['id','notifications_settings','email','name','created_at'],
            required: false
          },
          {
            model: models.Domain,
            required: false
          },
          {
            model: models.Community,
            required: false
          },
          {
            model: models.Group,
            required: false
          },
          {
            model: models.Post,
            required: false
          },
          {
            model: models.Point,
            required: false,
            include: [
              {
                model: models.Post,
                required: false
              }
            ]
          }
        ]
      }).then((results) => {
        if (results) {
          activity = results;
          seriesCallback();
        } else {
          seriesCallback('Activity not found');
        }
      }).catch((error) => {
        seriesCallback(error);
      });
    },
    (seriesCallback) => {
      log.info('Processing Activity Started', {type: activity.type});
      try {
        switch (activity.type) {
          case "activity.user.invite":
            models.AcNotification.createNotificationFromActivity(activity.actor.user_id, activity, "notification.user.invite", "priority", 70, (error) => {
              log.info('Processing activity.user.invite Completed', {type: activity.type, err: error});
              seriesCallback(error);
            });
            break;
          case "activity.password.recovery":
            models.AcNotification.createNotificationFromActivity(activity.actor.user, activity, "notification.password.recovery", "priority", 100, (error) => {
              log.info('Processing activity.password.recovery Completed', {type: activity.type, err: error});
              seriesCallback(error);
            });
            break;
          case "activity.password.changed":
            models.AcNotification.createNotificationFromActivity(activity.actor.user, activity, "notification.password.changed", "priority", 100, (error) => {
              log.info('Processing activity.password.changed Completed', {type: activity.type, err: error});
              seriesCallback(error);
            });
            break;
          case "activity.system.generalUserNotification":
            models.AcNotification.createNotificationFromActivity(activity.actor.userId, activity, "notification.generalUserNotification", "priority", 100, (error) => {
              log.info('Processing activity.system.generalUserNotification', {type: activity.type, err: error});
              seriesCallback(error);
            });
            break;
          case "activity.report.content":
            models.AcNotification.createReportNotifications(activity.actor.user, activity, (error) => {
              log.info('Processing activity.report.content Completed', {type: activity.type, err: error});
              seriesCallback(error);
            });
            break;
          case "activity.bulk.status.update":
            models.AcNotification.createNotificationFromActivity(activity.actor.user, activity, "notification.bulk.status.update", "priority", 100,  (error) => {
              log.info('Processing activity.bulk.status.update Completed', {type: activity.type, err: error});
              seriesCallback(error);
            });
            break;
          case "activity.post.new":
          case "activity.post.opposition.new":
          case "activity.post.endorsement.new":
            generatePostNotification(activity, activity.User,  (error) => {
              if (error) {
                log.error('Processing activity.post.* Error', {type: activity.type, err: error});
                seriesCallback(error);
              } else {
                log.info('Processing activity.post.* Completed', {type: activity.type});
                seriesCallback();
              }
            });
            break;
          case "activity.point.new":
          case "activity.point.helpful.new":
          case "activity.point.unhelpful.new":
          case "activity.point.newsStory.new":
          case "activity.point.comment.new":
            generatePointNotification(activity, activity.User,  (error) => {
              if (error) {
                log.error('Processing activity.point.* Completed', {type: activity.type, err: error});
                seriesCallback(error);
              } else {
                log.info('Processing activity.point.* Completed', {type: activity.type});
                seriesCallback();
              }
            });
            break;
          case "activity.post.status.change":
            if (activity.object && activity.object.bulkStatusUpdate) {
              log.info('Processing activity.post.status.change not creating notifications', {type: activity.type});
              seriesCallback();
            } else {
              generatePostStatusChangeNotification(activity, activity.User, (error) => {
                if (error) {
                  log.error('Processing activity.post.status.change Completed', {type: activity.type, err: error});
                  seriesCallback(error);
                } else {
                  log.info('Processing activity.post.status.change Completed', {type: activity.type});
                  seriesCallback();
                }
              });
            }
            break;
          default:
            seriesCallback();
        }
      } catch (error) {
        log.error("Processing Activity Error", {err: error});
        seriesCallback(error);
      }
    },

    (seriesCallback) => {
      generateRecommendationEvent(activity, seriesCallback);
    }
  ],  (error) => {
    if (error) {
      log.error("Processing Activity Error", {err: error});
      if (airbrake) {
        airbrake.notify(error).then((airbrakeErr)=> {
          if (airbrakeErr.error) {
            log.error("AirBrake Error", { context: 'airbrake', err: airbrakeErr.error, errorStatus: 500 });
          }
          callback(error);
        });
      } else {
        callback(error);
      }
    } else {
      log.info('Processing Activity and Recommendation Completed', {type: activity.type});
      callback();
    }
  });
};

module.exports = new ActivityWorker();
<|endoftext|>