<commit_before>module.exports = EmbeddedPlayground;

var _ = require('lodash');
var http = require('http');
var mercury = require('mercury');
var moment = require('moment');
var path = require('path');
var url = require('url');

var Editor = require('./editor');

var m = mercury;
var h = mercury.h;

// Shows each file in a tab.
// * el: The DOM element to mount on.
// * id: Identifier for this playground instance, used in debug messages.
// * files: List of {name, body}, as written by bundler.
function EmbeddedPlayground(el, id, files) {
  this.id_ = id;
  this.files_ = _.map(files, function(file) {
    return _.assign({}, file, {
      basename: path.basename(file.name),
      type: path.extname(file.name).substr(1)
    });
  });
  this.editors_ = _.map(this.files_, function(file) {
    return new Editor(file.type, file.body);
  });
  this.state_ = m.struct({
    activeTab: m.value(0),
    nextRunId: m.value(0),
    running: m.value(false),
    hasRun: m.value(false),
    consoleEvents: m.value([])
  });
  mercury.app(el, this.state_, this.render_.bind(this));
}

EmbeddedPlayground.prototype.renderTopBar_ = function(state) {
  var that = this;

  var tabs = _.map(this.files_, function(file, i) {
    var selector = 'div.tab';
    if (i === state.activeTab) {
      selector += '.active';
    }
    return h(selector, {
      'ev-click': function() {
        that.state_.activeTab.set(i);
      }
    }, file.basename);
  });

  var runBtn = h('button.btn', {
    'ev-click': that.run.bind(that)
  }, 'Run');
  var resetBtn = h('button.btn', {
    'ev-click': that.reset.bind(that)
  }, 'Reset');

  return h('div.top-bar', [h('div', tabs), h('div.btns', [runBtn, resetBtn])]);
};

EmbeddedPlayground.prototype.renderEditors_ = function(state) {
  var editors = _.map(this.editors_, function(editor, i) {
    var properties = {};
    if (i !== state.activeTab) {
      // Use "visibility: hidden" rather than "display: none" because the latter
      // causes the editor to initialize lazily and thus flicker when it's first
      // opened.
      properties['style'] = {visibility: 'hidden'};
    }
    return h('div.editor', properties, editor);
  });

  return h('div.editors', editors);
};

function renderConsoleEvent(event) {
  var children = [];
  if (event.Timestamp) {
    // Convert UTC to local time.
    var t = moment(event.Timestamp / 1e6);
    children.push(h('span.timestamp', t.format('H:mm:ss.SSS') + ' '));
  }
  if (event.File) {
    children.push(h('span.filename', path.basename(event.File) + ': '));
  }
  children.push(h('span.' + (event.Stream || 'unknown'), event.Message));
  return h('div', children);
}

EmbeddedPlayground.prototype.renderConsole_ = function(state) {
  if (state.hasRun) {
    return h('div.console.open', [
      h('div.text', _.map(state.consoleEvents, renderConsoleEvent))
    ]);
  }
  return h('div.console');
};

EmbeddedPlayground.prototype.render_ = function(state) {
  return h('div.pg', [
    this.renderTopBar_(state),
    this.renderEditors_(state),
    this.renderConsole_(state)
  ]);
};

// Sends the files to the backend, then injects the response in the console.
EmbeddedPlayground.prototype.run = function() {
  if (this.state_.running()) {
    console.log('Already running', this.id_);
    return;
  }
  var runId = this.state_.nextRunId();

  // TODO(sadovsky): Visually disable the "Run" button or change it to a "Stop"
  // button.
  this.state_.running.set(true);
  this.state_.hasRun.set(true);
  this.state_.consoleEvents.set([{Message: 'Running...'}]);

  var myUrl = url.parse(window.location.href, true);
  var pgaddr = myUrl.query.pgaddr;
  if (pgaddr) {
    console.log('Using pgaddr', pgaddr);
  } else {
    pgaddr = 'https://staging.v.io/playground';
  }
  var compileUrl = pgaddr + '/compile';
  if (myUrl.query.debug === '1') {
    compileUrl += '?debug=1';
  }

  var editors = this.editors_;
  var reqData = {
    files: _.map(this.files_, function(file, i) {
      var editor = editors[i];
      return {
        Name: file.name,
        Body: editor.getText()
      };
    }),
    Identities: []
  };

  // TODO(sadovsky): To deal with cached responses, shift timestamps (based on
  // current time) and introduce a fake delay. Also, switch to streaming
  // messages, for usability.
  var that = this, state = this.state_;

  // If the user stops the current run or resets the playground, functions
  // wrapped with ifRunActive become no-ops.
  var ifRunActive = function(cb) {
    return function() {
      if (runId === state.nextRunId()) {
        cb.apply(this, arguments);
      }
    };
  };

  var appendToConsole = function(events) {
    state.consoleEvents.set(state.consoleEvents().concat(events));
  };
  var makeEvent = function(stream, message) {
    return {Stream: stream, Message: message};
  };
  var endRunIfActive = ifRunActive(function() {
    that.endRun_();
  });

  var urlp = url.parse(compileUrl);

  var options = {
    method: 'POST',
    protocol: urlp.protocol,
    hostname: urlp.hostname,
    port: urlp.port || (urlp.protocol === 'https:' ? '443' : '80'),
    path: urlp.path,
    // TODO(ivanpi): Change once deployed.
    withCredentials: false,
    headers: {
      'accept': 'application/json',
      'content-type': 'application/json'
    }
  };

  var req = http.request(options);

  // error and close callbacks call endRunIfActive in the next tick to ensure
  // that if both events are triggered, both are executed before the run is
  // ended by either.
  req.on('error', ifRunActive(function(err) {
    console.error('Connection error: ' + err.message + '\n' + err.stack);
    appendToConsole(makeEvent('syserr', 'Error connecting to server.'));
    process.nextTick(endRunIfActive);
  }));

  // Holds partial prefix of next response line.
  var partialLine = '';

  req.on('response', ifRunActive(function(res) {
    if (res.statusCode !== 0 && res.statusCode !== 200) {
      appendToConsole(makeEvent('syserr', 'HTTP status ' + res.statusCode));
    }
    res.on('data', ifRunActive(function(chunk) {
      // Each complete line is one JSON Event.
      var eventsJson = (partialLine + chunk).split('\n');
      partialLine = eventsJson.pop();
      var events = [];
      _.forEach(eventsJson, function(line) {
        // Ignore empty lines.
        line = line.trim();
        if (line) {
          var ev;
          try {
            ev = JSON.parse(line);
          } catch (err) {
            console.error('Error parsing line: ' + line + '\n' + err.message);
            events.push(makeEvent('syserr', 'Error parsing server response.'));
            endRunIfActive();
            return false;
          }
          events.push(ev);
        }
      });
      appendToConsole(events);
    }));
  }));

  req.on('close', ifRunActive(function() {
    // partialLine should be empty when connection is closed.
    partialLine = partialLine.trim();
    if (partialLine) {
      console.error('Connection closed without newline after: ' + partialLine);
      appendToConsole(makeEvent('syserr', 'Error parsing server response.'));
    }
    process.nextTick(endRunIfActive);
  }));

  req.write(JSON.stringify(reqData));
  req.end();
};

// Clears the console and resets all editors to their original contents.
EmbeddedPlayground.prototype.reset = function() {
  this.state_.consoleEvents.set([]);
  _.forEach(this.editors_, function(editor) {
    editor.reset();
  });
  this.endRun_();
  this.state_.hasRun.set(false);
};

EmbeddedPlayground.prototype.endRun_ = function() {
  this.state_.nextRunId.set(this.state_.nextRunId() + 1);
  this.state_.running.set(false);
};
<commit_msg>playground: Improve client error messages.<commit_after>module.exports = EmbeddedPlayground;

var _ = require('lodash');
var http = require('http');
var mercury = require('mercury');
var moment = require('moment');
var path = require('path');
var url = require('url');

var Editor = require('./editor');

var m = mercury;
var h = mercury.h;

// Shows each file in a tab.
// * el: The DOM element to mount on.
// * id: Identifier for this playground instance, used in debug messages.
// * files: List of {name, body}, as written by bundler.
function EmbeddedPlayground(el, id, files) {
  this.id_ = id;
  this.files_ = _.map(files, function(file) {
    return _.assign({}, file, {
      basename: path.basename(file.name),
      type: path.extname(file.name).substr(1)
    });
  });
  this.editors_ = _.map(this.files_, function(file) {
    return new Editor(file.type, file.body);
  });
  this.state_ = m.struct({
    activeTab: m.value(0),
    nextRunId: m.value(0),
    running: m.value(false),
    hasRun: m.value(false),
    consoleEvents: m.value([])
  });
  mercury.app(el, this.state_, this.render_.bind(this));
}

EmbeddedPlayground.prototype.renderTopBar_ = function(state) {
  var that = this;

  var tabs = _.map(this.files_, function(file, i) {
    var selector = 'div.tab';
    if (i === state.activeTab) {
      selector += '.active';
    }
    return h(selector, {
      'ev-click': function() {
        that.state_.activeTab.set(i);
      }
    }, file.basename);
  });

  var runBtn = h('button.btn', {
    'ev-click': that.run.bind(that)
  }, 'Run');
  var resetBtn = h('button.btn', {
    'ev-click': that.reset.bind(that)
  }, 'Reset');

  return h('div.top-bar', [h('div', tabs), h('div.btns', [runBtn, resetBtn])]);
};

EmbeddedPlayground.prototype.renderEditors_ = function(state) {
  var editors = _.map(this.editors_, function(editor, i) {
    var properties = {};
    if (i !== state.activeTab) {
      // Use "visibility: hidden" rather than "display: none" because the latter
      // causes the editor to initialize lazily and thus flicker when it's first
      // opened.
      properties['style'] = {visibility: 'hidden'};
    }
    return h('div.editor', properties, editor);
  });

  return h('div.editors', editors);
};

function renderConsoleEvent(event) {
  var children = [];
  if (event.Timestamp) {
    // Convert UTC to local time.
    var t = moment(event.Timestamp / 1e6);
    children.push(h('span.timestamp', t.format('H:mm:ss.SSS') + ' '));
  }
  if (event.File) {
    children.push(h('span.filename', path.basename(event.File) + ': '));
  }
  children.push(h('span.' + (event.Stream || 'unknown'), event.Message));
  return h('div', children);
}

EmbeddedPlayground.prototype.renderConsole_ = function(state) {
  if (state.hasRun) {
    return h('div.console.open', [
      h('div.text', _.map(state.consoleEvents, renderConsoleEvent))
    ]);
  }
  return h('div.console');
};

EmbeddedPlayground.prototype.render_ = function(state) {
  return h('div.pg', [
    this.renderTopBar_(state),
    this.renderEditors_(state),
    this.renderConsole_(state)
  ]);
};

// Sends the files to the backend, then injects the response in the console.
EmbeddedPlayground.prototype.run = function() {
  if (this.state_.running()) {
    console.log('Already running', this.id_);
    return;
  }
  var runId = this.state_.nextRunId();

  // TODO(sadovsky): Visually disable the "Run" button or change it to a "Stop"
  // button.
  this.state_.running.set(true);
  this.state_.hasRun.set(true);
  this.state_.consoleEvents.set([{Message: 'Running...'}]);

  var myUrl = url.parse(window.location.href, true);
  var pgaddr = myUrl.query.pgaddr;
  if (pgaddr) {
    console.log('Using pgaddr', pgaddr);
  } else {
    pgaddr = 'https://staging.v.io/playground';
  }
  var compileUrl = pgaddr + '/compile';
  if (myUrl.query.debug === '1') {
    compileUrl += '?debug=1';
  }

  var editors = this.editors_;
  var reqData = {
    files: _.map(this.files_, function(file, i) {
      var editor = editors[i];
      return {
        Name: file.name,
        Body: editor.getText()
      };
    }),
    Identities: []
  };

  // TODO(sadovsky): To deal with cached responses, shift timestamps (based on
  // current time) and introduce a fake delay. Also, switch to streaming
  // messages, for usability.
  var that = this, state = this.state_;

  // If the user stops the current run or resets the playground, functions
  // wrapped with ifRunActive become no-ops.
  var ifRunActive = function(cb) {
    return function() {
      if (runId === state.nextRunId()) {
        cb.apply(this, arguments);
      }
    };
  };

  var appendToConsole = function(events) {
    state.consoleEvents.set(state.consoleEvents().concat(events));
  };
  var makeEvent = function(stream, message) {
    return {Stream: stream, Message: message};
  };
  var endRunIfActive = ifRunActive(function() {
    that.endRun_();
  });

  var urlp = url.parse(compileUrl);

  var options = {
    method: 'POST',
    protocol: urlp.protocol,
    hostname: urlp.hostname,
    port: urlp.port || (urlp.protocol === 'https:' ? '443' : '80'),
    path: urlp.path,
    // TODO(ivanpi): Change once deployed.
    withCredentials: false,
    headers: {
      'accept': 'application/json',
      'content-type': 'application/json'
    }
  };

  var req = http.request(options);

  // error and close callbacks call endRunIfActive in the next tick to ensure
  // that if both events are triggered, both are executed before the run is
  // ended by either.
  req.on('error', ifRunActive(function(err) {
    console.error('Connection error: ' + err.message + '\n' + err.stack);
    appendToConsole(makeEvent('syserr', 'Error connecting to server.'));
    process.nextTick(endRunIfActive);
  }));

  // Holds partial prefix of next response line.
  var partialLine = '';

  req.on('response', ifRunActive(function(res) {
    if (res.statusCode !== 0 && res.statusCode !== 200) {
      appendToConsole(makeEvent('syserr', 'HTTP status ' + res.statusCode));
    }
    res.on('data', ifRunActive(function(chunk) {
      // Each complete line is one JSON Event.
      var eventsJson = (partialLine + chunk).split('\n');
      partialLine = eventsJson.pop();
      var events = [];
      _.forEach(eventsJson, function(line) {
        // Ignore empty lines.
        line = line.trim();
        if (line) {
          var ev;
          try {
            ev = JSON.parse(line);
          } catch (err) {
            console.error('Error parsing line: ' + line + '\n' + err.message);
            events.push(makeEvent('syserr', 'Error parsing server response.'));
            endRunIfActive();
            return false;
          }
          events.push(ev);
        }
      });
      appendToConsole(events);
    }));
  }));

  req.on('close', ifRunActive(function() {
    // Sanity check: partialLine should be empty when connection is closed.
    partialLine = partialLine.trim();
    if (partialLine) {
      console.error('Connection closed without newline after: ' + partialLine);
      appendToConsole(makeEvent('syserr', 'Error parsing server response.'));
    }
    process.nextTick(endRunIfActive);
  }));

  req.write(JSON.stringify(reqData));
  req.end();
};

// Clears the console and resets all editors to their original contents.
EmbeddedPlayground.prototype.reset = function() {
  this.state_.consoleEvents.set([]);
  _.forEach(this.editors_, function(editor) {
    editor.reset();
  });
  this.endRun_();
  this.state_.hasRun.set(false);
};

EmbeddedPlayground.prototype.endRun_ = function() {
  this.state_.nextRunId.set(this.state_.nextRunId() + 1);
  this.state_.running.set(false);
};
<|endoftext|>


<commit_before>'use strict';

angular.module('oregamiClientApp')
  .service('gamesService', [ 'mySettings' , '$http',  function gamesService($mySettings, $http) {

        return {
            test: function(callback) {
                console.log('gamesService.test() called');
            },
            getGames: function() {
                // $http returns a promise, which has a then function, which also returns a promise
                var url = $mySettings.apiUri + '/games';
                console.log('gamesService.test() called => ' + url);
                var promise = $http.get(url).then(function (response) {
                    // The then function here is an opportunity to modify the response
                    console.log(url + '->' + response);
                    // The return value gets picked up by the then in the controller.
                    return response.data;
                });
                // Return the promise to the controller
                return promise;
            }
        }

  }]);
<commit_msg>custom url<commit_after>'use strict';

angular.module('oregamiClientApp')
  .service('gamesService', [ 'mySettings' , '$http',  function gamesService($mySettings, $http) {

        return {
            test: function(callback) {
                console.log('gamesService.test() called');
            },
            getGames: function() {
                // $http returns a promise, which has a then function, which also returns a promise
                var url = $mySettings.apiUri + '/games';
                if (getCookie("customUrl")!=null) {
                    url = getCookie("customUrl") + '/games'
                }
                console.log('gamesService.test() called => ' + url);
                var promise = $http.get(url).then(function (response) {
                    // The then function here is an opportunity to modify the response
                    console.log(url + '->' + response);
                    // The return value gets picked up by the then in the controller.
                    return response.data;
                });
                // Return the promise to the controller
                return promise;
            } ,
/*
            updateGame: function(game) {
                var url = $mySettings.apiUri + '/games';
                if (game.id==null) {
                    $http({
                        url: url,
                        method: "POST",
                        data: game,
                        headers: {'Content-Type': 'application/json'}
                    }).success(function (data, status, headers, config) {
                            //$scope.persons = data; // assign  $scope.persons here as promise is resolved here
                            console.log("post / insert / success");
                        }).error(function (data, status, headers, config) {
                            //$scope.status = status;
                            console.log("post / insert / error");
                        });
                } else {
                    $http({
                        url: url,
                        method: "PUT",
                        data: game,
                        headers: {
                            //'Content-Type': 'application/json',
                            //'Access-Control-Allow-Headers': 'Access-Control-Allow-Origin',
                            //'Access-Control-Allow-Origin' : '*'
                            'Access-Control-Allow-Origin': '*',
                            'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With, Access-Control-Allow-Methods, Access-Control-Allow-Origin',
                            'Access-Control-Allow-Methods': 'GET, POST, OPTIONS, PUT',
                            'Content-Type': 'application/json'
                        }
                    }).success(function (data, status, headers, config) {
                            //$scope.persons = data; // assign  $scope.persons here as promise is resolved here
                            console.log("put / update / success");
                        }).error(function (data, status, headers, config) {
                            //$scope.status = status;
                            console.log("put / update / error");
                        });
                }
            }
 */
        }

  }]);
<|endoftext|>


<commit_before>const structurePostItMembersFromDb = (state, allMembers) => {
  const postItMembers = Object.assign({}, state);
  for (let i = 0; i < allMembers.length; i += 1) {
    postItMembers.members[allMembers[i].id] = allMembers[i];
  }
  return postItMembers;
};

const structurePostitGroupsFromDb = (state, allGroups) => {
  const postItGroups = Object.assign({}, state);
  for (let i = 0; i < allGroups.length; i += 1) {
    postItGroups.groups[allGroups[i].id] = allGroups[i];
  }
  return postItGroups;
};

const postItInfoReducer = (state = {}, action) => {
  const appState = Object.assign({}, state);
  switch (action.type) {
    case 'GET_POSTIT_MEMBERS_SUCCESS':
      return structurePostItMembersFromDb(appState, action.postItUsers);
    case 'GET_ALL_GROUPS_SUCCESS':
      return structurePostitGroupsFromDb(state, action.postItGroups);
    default:
      return appState;
  }
};

export default postItInfoReducer;
<commit_msg>update postInfoReducer to structure data from db<commit_after>const structurePostItMembersFromDb = (state, dbSnapshot) => {
  const appState = Object.assign({}, state);
  const membersRows = dbSnapshot.rows;
  for (let i = 0; i < membersRows.length; i += 1) {
    const userId = membersRows[i].id;
    appState.members.postItMembers[userId] = membersRows[i];
  }
  appState.members.meta.count = dbSnapshot.count;
  return appState;
};

const structurePostitGroupsFromDb = (state, dbSnapshot) => {
  const appState = Object.assign({}, state);
  const groupRows = dbSnapshot.rows;
  for (let i = 0; i < groupRows.length; i += 1) {
    const groupId = groupRows[i].id;
    appState.groups.postItMembers[groupId] = groupRows[i];
  }
  appState.groups.meta.count = dbSnapshot.count;
  return appState;
};

const postItInfoReducer = (state = {}, action) => {
  const appState = Object.assign({}, state);
  switch (action.type) {
    case 'GET_POST_IT_MEMBERS_SUCCESS':
      return structurePostItMembersFromDb(appState, action.dbSnapShot);
    case 'GET_ALL_GROUPS_SUCCESS':
      return structurePostitGroupsFromDb(state, action.postItGroups);
    default:
      return appState;
  }
};

export default postItInfoReducer;
<|endoftext|>


<commit_before>'use strict';
import { $ } from 'meteor/jquery';
import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { dbRuleAgendas } from '../../db/dbRuleAgendas';
import { inheritedShowLoadingOnSubscribing } from '../layout/loading';
import { formatDateText } from '../utils/helpers';
import { alertDialog } from '../layout/alertDialog';
import { shouldStopSubscribe } from '../utils/idle';

inheritedShowLoadingOnSubscribing(Template.ruleAgendaList);
Template.ruleAgendaList.onCreated(function() {
  this.autorun(() => {
    if (shouldStopSubscribe()) {
      return false;
    }
    this.subscribe('allRuleAgenda');
  });
});
Template.ruleAgendaList.helpers({
  getNewAgendaHref() {
    return FlowRouter.path('createRuleAgenda');
  },
  getAgendaHref(agendaId) {
    return FlowRouter.path('ruleAgendaDetail', {agendaId});
  },
  processingAgendaList() {
    const currentDate = Date.now();
    const agendaList = [];
    dbRuleAgendas.find({}, {
      sort: {
        createdAt: -1
      }
    }).forEach((agenda) => {
      const expireDate = new Date(agenda.createdAt.getTime() + (agenda.duration * 60 * 60 * 1000));
      if (expireDate >= currentDate) {
        agendaList.push(agenda);
      }
    });

    return agendaList;
  },
  finishAgendaList() {
    const currentDate = Date.now();
    const agendaList = [];
    dbRuleAgendas.find({}, {
      sort: {
        createdAt: -1
      }
    }).forEach((agenda) => {
      const expireDate = new Date(agenda.createdAt.getTime() + (agenda.duration * 60 * 60 * 1000));
      if (expireDate < currentDate) {
        agendaList.push(agenda);
      }
    });

    return agendaList;
  },
  formatExpireDate(agenda) {
    const expireDate = new Date(agenda.createdAt.getTime() + (agenda.duration * 60 * 60 * 1000));

    return formatDateText(expireDate);
  }
});
<commit_msg>eslint<commit_after>'use strict';
import { Template } from 'meteor/templating';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { dbRuleAgendas } from '../../db/dbRuleAgendas';
import { inheritedShowLoadingOnSubscribing } from '../layout/loading';
import { formatDateText } from '../utils/helpers';
import { shouldStopSubscribe } from '../utils/idle';

inheritedShowLoadingOnSubscribing(Template.ruleAgendaList);
Template.ruleAgendaList.onCreated(function() {
  this.autorun(() => {
    if (shouldStopSubscribe()) {
      return false;
    }
    this.subscribe('allRuleAgenda');
  });
});
Template.ruleAgendaList.helpers({
  getNewAgendaHref() {
    return FlowRouter.path('createRuleAgenda');
  },
  getAgendaHref(agendaId) {
    return FlowRouter.path('ruleAgendaDetail', {agendaId});
  },
  processingAgendaList() {
    const currentDate = Date.now();
    const agendaList = [];
    dbRuleAgendas.find({}, {
      sort: {
        createdAt: -1
      }
    }).forEach((agenda) => {
      const expireDate = new Date(agenda.createdAt.getTime() + (agenda.duration * 60 * 60 * 1000));
      if (expireDate >= currentDate) {
        agendaList.push(agenda);
      }
    });

    return agendaList;
  },
  finishAgendaList() {
    const currentDate = Date.now();
    const agendaList = [];
    dbRuleAgendas.find({}, {
      sort: {
        createdAt: -1
      }
    }).forEach((agenda) => {
      const expireDate = new Date(agenda.createdAt.getTime() + (agenda.duration * 60 * 60 * 1000));
      if (expireDate < currentDate) {
        agendaList.push(agenda);
      }
    });

    return agendaList;
  },
  formatExpireDate(agenda) {
    const expireDate = new Date(agenda.createdAt.getTime() + (agenda.duration * 60 * 60 * 1000));

    return formatDateText(expireDate);
  }
});
<|endoftext|>


<commit_before>Template.buildingsGrid.helpers({
    bldgKey: function() {
        var bldgAddr = Session.get("currentBldg");
        var bldg = Buildings.findOne({address: bldgAddr});
        if (bldg) {
            return bldg.key;
        }
        else {
            return Session.get("currentAddress");
        }
    }
});

function openBldgURL(externalUrl) {
    if (externalUrl) {
        var target = '_top';
        if (externalUrl.length > 4 && externalUrl.substr(0, 4) == "http")
            target = '_blank';
        window.open(externalUrl, target);
    }
}
Template.buildingsGrid.events({
    "mousedown .bldg": function(event) {
        var externalUrl = $(event.currentTarget).attr("href");
        openBldgURL(externalUrl);
    },
    "click .navigate-up": function() {
        var currentAddress = Session.get("currentAddress");
        var parts = currentAddress.split("-");
        parts.pop();
        // if it's a flr, get out to the containing bldg
        if (parts[parts.length - 1][0] == "l") {
            parts.pop();
        }
        var newAddress = parts.join("-");
        window.open("/buildings/" + newAddress, "_top");
    }
});

Template.buildingsGrid.rendered = function () {
    var WIDTH = 1200,
        HEIGHT = 600,
        BOUNDING_WIDTH = 1220,
        BOUNDING_HEIGHT = 620,
        SQUARE_WIDTH = 10,
        SQUARE_HEIGHT = 10,
        MAX_ZOOM_OUT = 0.8,
        MAX_ZOOM_IN = 60;

    var self = this;
    var dom = {};

    var zoom = function() {
        dom.svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    };
    var zoomBehavior = d3.behavior.zoom().scaleExtent([MAX_ZOOM_OUT, MAX_ZOOM_IN]).on("zoom", zoom);

    dom.svg = d3.select("#display").append("svg")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .append("g")
        .call(zoomBehavior)
        .append("g");

    dom.svg.append("rect")
        .attr("class", "overlay")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .attr("fill", "lightblue");

    var xScale = d3.scale.linear().domain([0, FLOOR_W * SQUARE_WIDTH]).range([0, WIDTH]);
    var yScale = d3.scale.linear().domain([0, FLOOR_H * SQUARE_HEIGHT]).range([0, HEIGHT]);

    if (!self.handle) {
        self.handle = Meteor.autorun(function () {
            var query = {};
            if (Session.get("currentBldg") != Session.get("currentAddress")) {
                // if we're in a flr, don't render the containing bldg
                query = {flr: Session.get("currentAddress")};
            }
            dom.bldgs = dom.svg.selectAll('.bldg')
                .data(Buildings.find(query).fetch())
                .enter()
                .append("g")
                .attr("class", "bldg")
                .attr("xlink:href", function(d) {
                    if (d.payload.external_url) {
                        return d.payload.external_url;
                    }
                    else {
                        // if no external link, link to the 1st flr of the blsg
                        return "/buildings/" + d.address + "-l0";
                    }
                });

            dom.bldgs
                .append('rect')
                .attr({
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_HEIGHT)
                    },
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_HEIGHT),
                    stroke: 'grey',
                    "stroke-width": 0.01,
                    fill: function (d) {
                        if (d.contentType)
                            return "white";
                    }
                });

            dom.bldgs
                .append("foreignObject")
                .attr({
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_WIDTH),
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_HEIGHT)
                    },
                    fill: 'none'
                })
                .append("xhtml:body").append("xhtml:p")
                .style({
                    "color": function (d) {
                        // different color for posts with links
                        // TODO this ain't generic
                        if (d.payload.urls && d.payload.urls.length)
                            return "blue";
                        else
                            return "navy";
                    },
                    "font-size": "0.6px"
                })
                .html(function (d) {
                    if (d.contentType == 'twitter-social-post') {
                        return d.payload.text;
                    }
                    else if (d.contentType == 'daily-feed') {
                        return d.key;
                    }
                    else if (d.contentType == 'user') {
                        return d.payload.screenName;
                    }
                });

            // zoom on the current bldg
            if (Session.get("currentAddress")) {
                var addr = Session.get("currentAddress");
                var bldgAddr = getBldg(addr);
                if (bldgAddr == addr) {
                    // given a bldg address, so zoom on it
                    var parts = bldgAddr.split("-");

                    var part = parts[parts.length - 1];
                    var coords = part.substring(2, part.length - 1);
                    var x_y = coords.split(",");
                    var x = xScale(x_y[0] * SQUARE_WIDTH),
                        y = yScale(x_y[1] * SQUARE_WIDTH);
                    var X_OFFSET = 10,
                        Y_OFFSET = 5;
                    if (x >  xScale(X_OFFSET)) x -= xScale(X_OFFSET);
                    if (y >  yScale(Y_OFFSET)) y -=  yScale(Y_OFFSET);
                    var scale = MAX_ZOOM_IN;
                    zoomBehavior.scale(scale);
                    zoomBehavior.translate([-(x*scale), -(y*scale)]);
                    dom.svg.attr("transform", "translate(-" + (x*scale) + ',-' + (y*scale) + ")scale(" + scale + ")");
                }
            }
        });
    }

};<commit_msg>refactoring<commit_after>Template.buildingsGrid.helpers({
    bldgKey: function() {
        var bldgAddr = Session.get("currentBldg");
        var bldg = Buildings.findOne({address: bldgAddr});
        if (bldg) {
            return bldg.key;
        }
        else {
            return Session.get("currentAddress");
        }
    }
});

function openBldgURL(externalUrl) {
    if (externalUrl) {
        var target = '_top';
        if (externalUrl.length > 4 && externalUrl.substr(0, 4) == "http")
            target = '_blank';
        window.open(externalUrl, target);
    }
}
Template.buildingsGrid.events({
    "mousedown .bldg": function(event) {
        var externalUrl = $(event.currentTarget).attr("href");
        openBldgURL(externalUrl);
    },
    "click .navigate-up": function() {
        var currentAddress = Session.get("currentAddress");
        var parts = currentAddress.split("-");
        parts.pop();
        // if it's a flr, get out to the containing bldg
        if (parts[parts.length - 1][0] == "l") {
            parts.pop();
        }
        var newAddress = parts.join("-");
        window.open("/buildings/" + newAddress, "_top");
    }
});

Template.buildingsGrid.rendered = function () {
    var WIDTH = 1200,
        HEIGHT = 600,
        BOUNDING_WIDTH = 1220,
        BOUNDING_HEIGHT = 620,
        SQUARE_WIDTH = 10,
        SQUARE_HEIGHT = 10,
        MAX_ZOOM_OUT = 0.8,
        MAX_ZOOM_IN = 60;

    var self = this;
    var dom = {};

    var _zoom = function(_translate, _scale) {
        dom.svg.attr("transform", "translate(" + _translate + ")scale(" + _scale + ")");
    };

    var zoom = function() {
        _zoom(d3.event.translate, d3.event.scale);
    };

    var zoomBehavior = d3.behavior.zoom().scaleExtent([MAX_ZOOM_OUT, MAX_ZOOM_IN]).on("zoom", zoom);

    dom.svg = d3.select("#display").append("svg")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .append("g")
        .call(zoomBehavior)
        .append("g");

    dom.svg.append("rect")
        .attr("class", "overlay")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .attr("fill", "lightblue");

    var xScale = d3.scale.linear().domain([0, FLOOR_W * SQUARE_WIDTH]).range([0, WIDTH]);
    var yScale = d3.scale.linear().domain([0, FLOOR_H * SQUARE_HEIGHT]).range([0, HEIGHT]);

    if (!self.handle) {
        self.handle = Meteor.autorun(function () {
            var query = {};
            if (Session.get("currentBldg") != Session.get("currentAddress")) {
                // if we're in a flr, don't render the containing bldg
                query = {flr: Session.get("currentAddress")};
            }
            dom.bldgs = dom.svg.selectAll('.bldg')
                .data(Buildings.find(query).fetch())
                .enter()
                .append("g")
                .attr("class", "bldg")
                .attr("xlink:href", function(d) {
                    if (d.payload.external_url) {
                        return d.payload.external_url;
                    }
                    else {
                        // if no external link, link to the 1st flr of the blsg
                        return "/buildings/" + d.address + "-l0";
                    }
                });

            dom.bldgs
                .append('rect')
                .attr({
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_HEIGHT)
                    },
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_HEIGHT),
                    stroke: 'grey',
                    "stroke-width": 0.01,
                    fill: function (d) {
                        if (d.contentType)
                            return "white";
                    }
                });

            dom.bldgs
                .append("foreignObject")
                .attr({
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_WIDTH),
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_HEIGHT)
                    },
                    fill: 'none'
                })
                .append("xhtml:body").append("xhtml:p")
                .style({
                    "color": function (d) {
                        // different color for posts with links
                        // TODO this ain't generic
                        if (d.payload.urls && d.payload.urls.length)
                            return "blue";
                        else
                            return "navy";
                    },
                    "font-size": "0.6px"
                })
                .html(function (d) {
                    if (d.contentType == 'twitter-social-post') {
                        return d.payload.text;
                    }
                    else if (d.contentType == 'daily-feed') {
                        return d.key;
                    }
                    else if (d.contentType == 'user') {
                        return d.payload.screenName;
                    }
                });

            // if given a bldg address, zoom on it
            if (Session.get("currentAddress") && Session.get("currentAddress") == Session.get("currentBldg")) {
                var parts = Session.get("currentBldg").split("-");
                var part = parts[parts.length - 1];
                var coords = part.substring(2, part.length - 1);
                var x_y = coords.split(",");
                var x = xScale(x_y[0] * SQUARE_WIDTH),
                    y = yScale(x_y[1] * SQUARE_WIDTH);
                // if possible, show some offset
                var X_OFFSET = 10,
                    Y_OFFSET = 5;
                if (x > xScale(X_OFFSET)) x -= xScale(X_OFFSET);
                if (y > yScale(Y_OFFSET)) y -=  yScale(Y_OFFSET);
                var scale = MAX_ZOOM_IN;
                zoomBehavior.scale(scale);
                var translate_vector = [-(x * scale), -(y * scale)];
                zoomBehavior.translate(translate_vector);
                _zoom(translate_vector, scale);
            }
        });
    }

};<|endoftext|>


<commit_before>Template.buildingsGrid.helpers({
    bldgKey: function() {
        var bldgAddr = Session.get("currentBldg");
        var bldg = Buildings.findOne({address: bldgAddr});
        if (bldg) {
            return bldg.key;
        }
        else {
            return Session.get("currentAddress");
        }
    }
});

function openBldgURL(externalUrl) {
    if (externalUrl) {
        var target = '_top';
        if (externalUrl.length > 4 && externalUrl.substr(0, 4) == "http")
            target = '_blank';
        window.open(externalUrl, target);
    }
}
Template.buildingsGrid.events({
    "mousedown .bldg": function(event) {
        var externalUrl = $(event.currentTarget).attr("href");
        openBldgURL(externalUrl);
    },
    "click .navigate-up": function() {
        var currentAddress = Session.get("currentAddress");
        var parts = currentAddress.split("-");
        parts.pop();
        // if it's a flr, get out to the containing bldg
        if (parts[parts.length - 1][0] == "l") {
            parts.pop();
        }
        var newAddress = parts.join("-");
        window.open("/buildings/" + newAddress, "_top");
    }
});

Template.buildingsGrid.rendered = function () {
    var WIDTH = 1200,
        HEIGHT = 600,
        BOUNDING_WIDTH = 1220,
        BOUNDING_HEIGHT = 620,
        SQUARE_WIDTH = 10,
        SQUARE_HEIGHT = 10,
        MAX_ZOOM_OUT = 0.8,
        MAX_ZOOM_IN = 60;

    var self = this;
    var dom = {};

    var zoom = function() {
        dom.svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    };
    var zoomBehavior = d3.behavior.zoom().scaleExtent([MAX_ZOOM_OUT, MAX_ZOOM_IN]).on("zoom", zoom);

    dom.svg = d3.select("#display").append("svg")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .append("g")
        .call(zoomBehavior)
        .append("g");

    dom.svg.append("rect")
        .attr("class", "overlay")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .attr("fill", "lightblue");

    var xScale = d3.scale.linear().domain([0, FLOOR_W * SQUARE_WIDTH]).range([0, WIDTH]);
    var yScale = d3.scale.linear().domain([0, FLOOR_H * SQUARE_HEIGHT]).range([0, HEIGHT]);

    if (!self.handle) {
        self.handle = Meteor.autorun(function () {
            var query = {};
            if (Session.get("currentBldg") != Session.get("currentAddress")) {
                // if we're in a flr, don't render the containing bldg
                query = {flr: Session.get("currentAddress")};
            }
            dom.bldgs = dom.svg.selectAll('.bldg')
                .data(Buildings.find(query).fetch())
                .enter()
                .append("g")
                .attr("class", "bldg")
                .attr("xlink:href", function(d) {
                    if (d.payload.external_url) {
                        return d.payload.external_url;
                    }
                    else {
                        // if no external link, link to the 1st flr of the blsg
                        return "/buildings/" + d.address + "-l0";
                    }
                });

            dom.bldgs
                .append('rect')
                .attr({
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_WIDTH)
                    },
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_WIDTH),
                    stroke: 'grey',
                    "stroke-width": 0.05,
                    fill: function (d) {
                        if (d.contentType)
                            return "white";
                    }
                });

            dom.bldgs
                .append("foreignObject")
                .attr({
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_WIDTH),
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_WIDTH)
                    },
                    fill: 'none'
                })
                .append("xhtml:body").append("xhtml:p")
                .style({
                    "color": function (d) {
                        // different color for posts with links
                        // TODO this ain't generic
                        if (d.payload.urls && d.payload.urls.length)
                            return "blue";
                        else
                            return "navy";
                    },
                    "font-size": "0.6px"
                })
                .html(function (d) {
                    if (d.contentType == 'twitter-social-post') {
                        return d.payload.text;
                    }
                    else if (d.contentType == 'daily-feed') {
                        return d.key;
                    }
                    else if (d.contentType == 'user') {
                        return d.payload.screenName;
                    }
                });

            // zoom on the current bldg
            if (Session.get("currentAddress")) {
                var addr = Session.get("currentAddress");
                var bldgAddr = getBldg(addr);
                if (bldgAddr == addr) {
                    // given a bldg address, so zoom on it
                    var parts = bldgAddr.split("-");

                    var part = parts[parts.length - 1];
                    var coords = part.substring(2, part.length - 1);
                    var x_y = coords.split(",");
                    var x = xScale(x_y[0] * SQUARE_WIDTH),
                        y = yScale(x_y[1] * SQUARE_WIDTH);
                    var X_OFFSET = 10,
                        Y_OFFSET = 5;
                    if (x >  xScale(X_OFFSET)) x -= xScale(X_OFFSET);
                    if (y >  yScale(Y_OFFSET)) y -=  yScale(Y_OFFSET);
                    var scale = MAX_ZOOM_IN;
                    zoomBehavior.scale(scale);
                    zoomBehavior.translate([-(x*scale), -(y*scale)]);
                    dom.svg.attr("transform", "translate(-" + (x*scale) + ',-' + (y*scale) + ")scale(" + scale + ")");
                }
            }
        });
    }

};<commit_msg>refactoring<commit_after>Template.buildingsGrid.helpers({
    bldgKey: function() {
        var bldgAddr = Session.get("currentBldg");
        var bldg = Buildings.findOne({address: bldgAddr});
        if (bldg) {
            return bldg.key;
        }
        else {
            return Session.get("currentAddress");
        }
    }
});

function openBldgURL(externalUrl) {
    if (externalUrl) {
        var target = '_top';
        if (externalUrl.length > 4 && externalUrl.substr(0, 4) == "http")
            target = '_blank';
        window.open(externalUrl, target);
    }
}
Template.buildingsGrid.events({
    "mousedown .bldg": function(event) {
        var externalUrl = $(event.currentTarget).attr("href");
        openBldgURL(externalUrl);
    },
    "click .navigate-up": function() {
        var currentAddress = Session.get("currentAddress");
        var parts = currentAddress.split("-");
        parts.pop();
        // if it's a flr, get out to the containing bldg
        if (parts[parts.length - 1][0] == "l") {
            parts.pop();
        }
        var newAddress = parts.join("-");
        window.open("/buildings/" + newAddress, "_top");
    }
});

Template.buildingsGrid.rendered = function () {
    var WIDTH = 1200,
        HEIGHT = 600,
        BOUNDING_WIDTH = 1220,
        BOUNDING_HEIGHT = 620,
        SQUARE_WIDTH = 10,
        SQUARE_HEIGHT = 10,
        MAX_ZOOM_OUT = 0.8,
        MAX_ZOOM_IN = 60;

    var self = this;
    var dom = {};

    var zoom = function() {
        dom.svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    };
    var zoomBehavior = d3.behavior.zoom().scaleExtent([MAX_ZOOM_OUT, MAX_ZOOM_IN]).on("zoom", zoom);

    dom.svg = d3.select("#display").append("svg")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .append("g")
        .call(zoomBehavior)
        .append("g");

    dom.svg.append("rect")
        .attr("class", "overlay")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .attr("fill", "lightblue");

    var xScale = d3.scale.linear().domain([0, FLOOR_W * SQUARE_WIDTH]).range([0, WIDTH]);
    var yScale = d3.scale.linear().domain([0, FLOOR_H * SQUARE_HEIGHT]).range([0, HEIGHT]);

    if (!self.handle) {
        self.handle = Meteor.autorun(function () {
            var query = {};
            if (Session.get("currentBldg") != Session.get("currentAddress")) {
                // if we're in a flr, don't render the containing bldg
                query = {flr: Session.get("currentAddress")};
            }
            dom.bldgs = dom.svg.selectAll('.bldg')
                .data(Buildings.find(query).fetch())
                .enter()
                .append("g")
                .attr("class", "bldg")
                .attr("xlink:href", function(d) {
                    if (d.payload.external_url) {
                        return d.payload.external_url;
                    }
                    else {
                        // if no external link, link to the 1st flr of the blsg
                        return "/buildings/" + d.address + "-l0";
                    }
                });

            dom.bldgs
                .append('rect')
                .attr({
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_HEIGHT)
                    },
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_HEIGHT),
                    stroke: 'grey',
                    "stroke-width": 0.01,
                    fill: function (d) {
                        if (d.contentType)
                            return "white";
                    }
                });

            dom.bldgs
                .append("foreignObject")
                .attr({
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_WIDTH),
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_HEIGHT)
                    },
                    fill: 'none'
                })
                .append("xhtml:body").append("xhtml:p")
                .style({
                    "color": function (d) {
                        // different color for posts with links
                        // TODO this ain't generic
                        if (d.payload.urls && d.payload.urls.length)
                            return "blue";
                        else
                            return "navy";
                    },
                    "font-size": "0.6px"
                })
                .html(function (d) {
                    if (d.contentType == 'twitter-social-post') {
                        return d.payload.text;
                    }
                    else if (d.contentType == 'daily-feed') {
                        return d.key;
                    }
                    else if (d.contentType == 'user') {
                        return d.payload.screenName;
                    }
                });

            // zoom on the current bldg
            if (Session.get("currentAddress")) {
                var addr = Session.get("currentAddress");
                var bldgAddr = getBldg(addr);
                if (bldgAddr == addr) {
                    // given a bldg address, so zoom on it
                    var parts = bldgAddr.split("-");

                    var part = parts[parts.length - 1];
                    var coords = part.substring(2, part.length - 1);
                    var x_y = coords.split(",");
                    var x = xScale(x_y[0] * SQUARE_WIDTH),
                        y = yScale(x_y[1] * SQUARE_WIDTH);
                    var X_OFFSET = 10,
                        Y_OFFSET = 5;
                    if (x >  xScale(X_OFFSET)) x -= xScale(X_OFFSET);
                    if (y >  yScale(Y_OFFSET)) y -=  yScale(Y_OFFSET);
                    var scale = MAX_ZOOM_IN;
                    zoomBehavior.scale(scale);
                    zoomBehavior.translate([-(x*scale), -(y*scale)]);
                    dom.svg.attr("transform", "translate(-" + (x*scale) + ',-' + (y*scale) + ")scale(" + scale + ")");
                }
            }
        });
    }

};<|endoftext|>


<commit_before>class DisplayTable {
  constructor (headings, rows) {
    this.headings = headings
    this.rows = rows
    this.isValid()
  }

  isValid () {
    if (this.headings.length < 1) {
      throw new Error('No headings found')
    }
  }
}

module.exports = DisplayTable
<commit_msg>Stop app crashing when worklaod user not found (#12)<commit_after>class DisplayTable {
  constructor (headings, rows) {
    this.headings = headings
    this.rows = rows
  }
}

module.exports = DisplayTable
<|endoftext|>


<commit_before>class Page {
  static DEFAULT_CREDENTIALS = {
    user: "erin",
    superUser: "rebecca",
    adminUser: "arthur",
    onboardUser: "bonny"
  }

  _buildUrl(pathName, credentials) {
    const credSep = pathName.includes("?") ? "&" : "?"
    return `${browser.options.baseUrl}${pathName}${credSep}user=${credentials}&pass=${credentials}`
  }

  _open(pathName, credentials) {
    browser.url(this._buildUrl(pathName, credentials))
  }

  open(pathName = "/", credentials = Page.DEFAULT_CREDENTIALS.user) {
    this._open(pathName, credentials)
  }

  openAsSuperUser(pathName = "/") {
    this._open(pathName, Page.DEFAULT_CREDENTIALS.superUser)
  }

  openAsAdminUser(pathName = "/") {
    this._open(pathName, Page.DEFAULT_CREDENTIALS.adminUser)
  }

  openAsOnboardUser(pathName = "/") {
    this._open(pathName, Page.DEFAULT_CREDENTIALS.onboardUser)
  }

  getRandomOption(select) {
    const options = select.$$("option")
    // Ignore the first option, it is always the empty one
    const index = 1 + Math.floor(Math.random() * (options.length - 1))
    return options[index].getValue()
  }
}

export default Page
<commit_msg>When opening new page, wait for loading indicator to disappear<commit_after>class Page {
  static DEFAULT_CREDENTIALS = {
    user: "erin",
    superUser: "rebecca",
    adminUser: "arthur",
    onboardUser: "bonny"
  }

  _buildUrl(pathName, credentials) {
    const credSep = pathName.includes("?") ? "&" : "?"
    return `${browser.options.baseUrl}${pathName}${credSep}user=${credentials}&pass=${credentials}`
  }

  _open(pathName, credentials) {
    browser.url(this._buildUrl(pathName, credentials))
    browser
      .$("span.loading")
      .waitForExist(30000, true, "Expected everything to be loaded by now")
  }

  open(pathName = "/", credentials = Page.DEFAULT_CREDENTIALS.user) {
    this._open(pathName, credentials)
  }

  openAsSuperUser(pathName = "/") {
    this._open(pathName, Page.DEFAULT_CREDENTIALS.superUser)
  }

  openAsAdminUser(pathName = "/") {
    this._open(pathName, Page.DEFAULT_CREDENTIALS.adminUser)
  }

  openAsOnboardUser(pathName = "/") {
    this._open(pathName, Page.DEFAULT_CREDENTIALS.onboardUser)
  }

  getRandomOption(select) {
    const options = select.$$("option")
    // Ignore the first option, it is always the empty one
    const index = 1 + Math.floor(Math.random() * (options.length - 1))
    return options[index].getValue()
  }
}

export default Page
<|endoftext|>


<commit_before>
openExternalURL = function(externalUrl) {
    if (externalUrl) {
        var target = '_top';
        if (externalUrl.length > 4 && externalUrl.substr(0, 4) == "http")
            target = '_blank';
        window.open(externalUrl, target);
    }
};

redirectTo = function(newAddress) {
    window.open("/buildings/" + newAddress, "_top");
};

bldgRenderFunc = {
    'twitter-social-post': function(d) {
        return d.payload.text;
    },
    'daily-feed': function(d) {
        return d.key;
    },
    'user': function(d) {
        return d.payload.screenName;
    }
};

Template.buildingsGrid.helpers({
    bldgKey: function() {
        var bldgKey = getBldgKey(Session.get("currentBldg"));
        if (bldgKey) {
            return bldgKey;
        }
        else {
            // if there's no bldg, just show the address
            return Session.get("currentAddress");
        }
    }
});

Template.buildingsGrid.events({
    "mousedown .bldg": function(event) {
        var externalUrl = $(event.currentTarget).attr("href");
        openExternalURL(externalUrl);
    },
    "click .navigate-up": function() {
        var newAddress = getContainingBldgAddress();
        redirectTo(newAddress);
    }
});

Template.buildingsGrid.rendered = function () {
    var WIDTH = 1200,
        HEIGHT = 600,
        BOUNDING_WIDTH = 1220,
        BOUNDING_HEIGHT = 620,
        SQUARE_WIDTH = 10,
        SQUARE_HEIGHT = 10,
        MAX_ZOOM_OUT = 0.8,
        MAX_ZOOM_IN = 60;

    var self = this;
    var dom = {};

    var _zoom = function(_translate, _scale) {
        dom.svg.attr("transform", "translate(" + _translate + ")scale(" + _scale + ")");
    };

    var zoom = function() {
        _zoom(d3.event.translate, d3.event.scale);
    };

    var zoomBehavior = d3.behavior.zoom().scaleExtent([MAX_ZOOM_OUT, MAX_ZOOM_IN]).on("zoom", zoom);

    dom.svg = d3.select("#display").append("svg")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .append("g")
        .call(zoomBehavior)
        .append("g");

    dom.svg.append("rect")
        .attr("class", "overlay")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .attr("fill", "lightblue");

    var xScale = d3.scale.linear().domain([0, FLOOR_W * SQUARE_WIDTH]).range([0, WIDTH]);
    var yScale = d3.scale.linear().domain([0, FLOOR_H * SQUARE_HEIGHT]).range([0, HEIGHT]);

    if (!self.handle) {
        self.handle = Meteor.autorun(function () {
            var query = {};
            if (Session.get("currentBldg") != Session.get("currentAddress")) {
                // if we're in a flr, don't render the containing bldg
                query = {flr: Session.get("currentAddress")};
            }
            // add g elements for all bldgs
            dom.bldgs = dom.svg.selectAll('.bldg')
                .data(Buildings.find(query).fetch())
                .enter()
                .append("g")
                .attr("class", "bldg")
                .attr("xlink:href", getBldgLink);

            // draw the bldg frame
            dom.bldgs
                .append('rect')
                .attr({
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_HEIGHT)
                    },
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_HEIGHT),
                    stroke: 'grey',
                    "stroke-width": 0.01,
                    fill: function (d) {
                        if (d.contentType)
                            return "white";
                    }
                });

            // add the bldg content
            dom.bldgs
                .append("foreignObject")
                .attr({
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_WIDTH),
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_HEIGHT)
                    },
                    fill: 'none'
                })
                .append("xhtml:body").append("xhtml:p")
                .style({
                    "color": function (d) {
                        // different color for posts with links
                        // TODO this ain't generic
                        if (d.payload.urls && d.payload.urls.length)
                            return "blue";
                        else
                            return "navy";
                    },
                    "font-size": "0.6px"
                })
                .html(function (d) {
                    return bldgRenderFunc[d.contentType](d);
                });

            // if given a bldg address, zoom on it
            if (Session.get("currentAddress") && Session.get("currentAddress") == Session.get("currentBldg")) {
                var coords = extractBldgCoordinates(Session.get("currentBldg"));
                var x = xScale(coords[0] * SQUARE_WIDTH),
                    y = yScale(coords[1] * SQUARE_WIDTH);
                // if possible, show some offset
                var X_OFFSET = xScale(10),
                    Y_OFFSET = yScale(5);
                if (x > X_OFFSET) x -= X_OFFSET;
                if (y > Y_OFFSET) y -=  Y_OFFSET;
                // apply the zoom
                var translateVector = [-(x * MAX_ZOOM_IN), -(y * MAX_ZOOM_IN)];
                zoomBehavior.scale(MAX_ZOOM_IN);
                zoomBehavior.translate(translateVector);
                _zoom(translateVector, MAX_ZOOM_IN);
            }
        });
    }

};<commit_msg>refactoring<commit_after>
openExternalURL = function(externalUrl) {
    if (externalUrl) {
        var target = '_top';
        if (externalUrl.length > 4 && externalUrl.substr(0, 4) == "http")
            target = '_blank';
        window.open(externalUrl, target);
    }
};

redirectTo = function(newAddress) {
    window.open("/buildings/" + newAddress, "_top");
};

bldgRenderFunc = {
    'twitter-social-post': function(d) {
        return d.payload.text;
    },
    'daily-feed': function(d) {
        return d.key;
    },
    'user': function(d) {
        return d.key;
    }
};

Template.buildingsGrid.helpers({
    bldgKey: function() {
        var bldgKey = getBldgKey(Session.get("currentBldg"));
        if (bldgKey) {
            return bldgKey;
        }
        else {
            // if there's no bldg, just show the address
            return Session.get("currentAddress");
        }
    }
});

Template.buildingsGrid.events({
    "mousedown .bldg": function(event) {
        var externalUrl = $(event.currentTarget).attr("href");
        openExternalURL(externalUrl);
    },
    "click .navigate-up": function() {
        var newAddress = getContainingBldgAddress();
        redirectTo(newAddress);
    }
});

Template.buildingsGrid.rendered = function () {
    var WIDTH = 1200,
        HEIGHT = 600,
        BOUNDING_WIDTH = 1220,
        BOUNDING_HEIGHT = 620,
        SQUARE_WIDTH = 10,
        SQUARE_HEIGHT = 10,
        MAX_ZOOM_OUT = 0.8,
        MAX_ZOOM_IN = 60;

    var self = this;
    var dom = {};

    var _zoom = function(_translate, _scale) {
        dom.svg.attr("transform", "translate(" + _translate + ")scale(" + _scale + ")");
    };

    var zoom = function() {
        _zoom(d3.event.translate, d3.event.scale);
    };

    var zoomBehavior = d3.behavior.zoom().scaleExtent([MAX_ZOOM_OUT, MAX_ZOOM_IN]).on("zoom", zoom);

    dom.svg = d3.select("#display").append("svg")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .append("g")
        .call(zoomBehavior)
        .append("g");

    dom.svg.append("rect")
        .attr("class", "overlay")
        .attr("width", BOUNDING_WIDTH)
        .attr("height", BOUNDING_HEIGHT)
        .attr("fill", "lightblue");

    var xScale = d3.scale.linear().domain([0, FLOOR_W * SQUARE_WIDTH]).range([0, WIDTH]);
    var yScale = d3.scale.linear().domain([0, FLOOR_H * SQUARE_HEIGHT]).range([0, HEIGHT]);

    if (!self.handle) {
        self.handle = Meteor.autorun(function () {
            var query = {};
            if (Session.get("currentBldg") != Session.get("currentAddress")) {
                // if we're in a flr, don't render the containing bldg
                query = {flr: Session.get("currentAddress")};
            }
            // add g elements for all bldgs
            dom.bldgs = dom.svg.selectAll('.bldg')
                .data(Buildings.find(query).fetch())
                .enter()
                .append("g")
                .attr("class", "bldg")
                .attr("xlink:href", getBldgLink);

            // draw the bldg frame
            dom.bldgs
                .append('rect')
                .attr({
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_HEIGHT)
                    },
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_HEIGHT),
                    stroke: 'grey',
                    "stroke-width": 0.01,
                    fill: function (d) {
                        if (d.contentType)
                            return "white";
                    }
                });

            // add the bldg content
            dom.bldgs
                .append("foreignObject")
                .attr({
                    width: xScale(SQUARE_WIDTH),
                    height: yScale(SQUARE_WIDTH),
                    x: function (d) {
                        return xScale(d.x * SQUARE_WIDTH)
                    },
                    y: function (d) {
                        return yScale(d.y * SQUARE_HEIGHT)
                    },
                    fill: 'none'
                })
                .append("xhtml:body").append("xhtml:p")
                .style({
                    "color": function (d) {
                        // different color for posts with links
                        // TODO this ain't generic
                        if (d.payload.urls && d.payload.urls.length)
                            return "blue";
                        else
                            return "navy";
                    },
                    "font-size": "0.6px"
                })
                .html(function (d) {
                    return bldgRenderFunc[d.contentType](d);
                });

            // if given a bldg address, zoom on it
            if (Session.get("currentAddress") && Session.get("currentAddress") == Session.get("currentBldg")) {
                var coords = extractBldgCoordinates(Session.get("currentBldg"));
                var x = xScale(coords[0] * SQUARE_WIDTH),
                    y = yScale(coords[1] * SQUARE_WIDTH);
                // if possible, show some offset
                var X_OFFSET = xScale(10),
                    Y_OFFSET = yScale(5);
                if (x > X_OFFSET) x -= X_OFFSET;
                if (y > Y_OFFSET) y -=  Y_OFFSET;
                // apply the zoom
                var translateVector = [-(x * MAX_ZOOM_IN), -(y * MAX_ZOOM_IN)];
                zoomBehavior.scale(MAX_ZOOM_IN);
                zoomBehavior.translate(translateVector);
                _zoom(translateVector, MAX_ZOOM_IN);
            }
        });
    }

};<|endoftext|>


<commit_before>import React, { Component } from 'react';
import { Link } from 'react-router-dom';

import Button from '../Shared/Button';
import legitCatImage from '../../images/legit-cat.png';

class Start extends Component {
  render() {
    const bodyStyles = { marginBottom: "50px" }

    return (

You'll evaluate 3 different articles and figure out which ones are legit.

We'll ask you questins to help you determine the answer.

        <Link to="/article/1">
          <Button text="Let's Get Started" />
        </Link>

    );
  }

}

export default Start;
<commit_msg>convert text to smart quotes<commit_after>import React, { Component } from 'react';
import { Link } from 'react-router-dom';

import Button from '../Shared/Button';
import legitCatImage from '../../images/legit-cat.png';

class Start extends Component {
  render() {
    const bodyStyles = { marginBottom: "50px" }

    return (

You’ll evaluate 3 different articles and figure out which ones are legit.

We’ll ask you questins to help you determine the answer.  Testing this Crazy shit out dog

        <Link to="/article/1">
          <Button text="Let's Get Started" />
        </Link>

    );
  }

}

export default Start;
<|endoftext|>


<commit_before>/**
 * Created by i.n. on 15.06.2015.
 */

var conf = require('../../config'),
    elasticConf = conf.get('elastic'),
    elastic = require('./elastic')(elasticConf),
    log = require('../../libs/log')(module),
    async = require('async');

//var moment = require('moment');

function exportCollection(desc, mongoDb, callback) {

    var collection = mongoDb.collection(desc.name);
    var query = {};

    var indexName = desc.index + '-' + (new Date().toLocaleDateString()).replace(/-/g,'.');

    if (!collection) {
        return callback('collection ' + desc.name + ' does not exist.');
    };

    log.trace(('====> exporting collection [' + desc.name + ']'));

    async.waterfall([
        function (next) {
            log.trace('----> checking connection to elastic');
            elastic.ping({requestTimeout: 10000}, function (err) {
                next(err);
            });
        },
        function (next) {
            log.trace('----> search existing index [' + indexName + ']');
            elastic.indices.stats({index: indexName}, function (err, result) {
                next(null, !err)
            });
        },

        function (existsIndex, next) {
            if (!existsIndex) {
                log.trace('----> creating new index [' + indexName + ']');
                elastic.indices.create({index: indexName}, function (err, result) {
                    next(err);
                });
            } else {
                log.trace('----> skip creating new index [' + indexName + ']');
                next();
            }
        },

        function (next) {
            log.trace('----> find max start_stamp in index [' + indexName + ']');
            elastic.search({
                index: desc.index + '-*',
                size: 1,
                body: {
                    "aggs": {
                        "maxDate": {
                            "max": {
                                "field": "variables.start_stamp"
                            }
                        }
                    }
                }
            }, function (err, result) {
                if (err) return next(err);
                if (!result || !result['aggregations']) {
                    return next(new Error('Bad aggregatins.'))
                }
                query = {
                    "callflow.times.created_time": {
                        "$gt": (result['aggregations']['maxDate']['value'] + 1000) * 1000
                    }
                };
                next();
            });
        },

        function (next) {
            log.trace('----> initialize index mapping');

            if (!desc.mappings) {
                return next();
            }

            elastic.indices.putMapping({index: indexName, type: desc.type, body: desc.mappings}, function (err) {
                next(err);
            });
        },

        function (next) {
            log.trace('----> analizing collection [' + desc.name + ']');
            collection.count(query, function (err, total) {
                if (err) {
                    return next(err);
                }

                log.trace('----> find ' + total + ' documentents to export');
                next(null, total);
            });
        },

        function (total, next) {
            log.trace('----> streaming collection to elastic');

            var stream = collection
                .find(query)
                .stream();

            stream.on('data', function (doc) {
                stream.pause();
                elastic.create({
                    index: indexName,
                    type: desc.type,
                    id: doc._id.toString(),
                    body: {
                        "_id": doc._id.toString(),
                        "variables": doc.variables
                    }
                }, function (err) {
                    if (err) {
                        if (err['message'] && err['message'].indexOf('DocumentAlreadyExistsException') > -1) {
                            log.warn(err['message']);
                        } else {
                            log.error('failed to create document %s in elastic.', err['message']);
                            return next(err);
                        }
                    } else {
                        log.trace('Save document id %s', doc._id.toString());
                    };
                    stream.resume();
                });
            });

            stream.on('end', function (err) {
                stream.destroy();
                next(err, total);
            });
        },

    ], function (err) {
        if (err) {
            log.error(('====> collection [' + desc.name + '] - failed to export.'));
            //log.error(err);
            return callback(err);
        }
        log.trace(('====> collection [' + desc.name + '] - end to export.'));
        callback(null);
    });
};

var started = false;

module.exports = function (mongoDb) {
    if (started) return;
    // TODO ..
    started = true;
    var timeMSec = elasticConf.intervalMin * 60 * 1000;
    var timerId = setTimeout(function tick() {
        exportCollection(elasticConf.collections[0], mongoDb, function (err) {
            log.debug('Next sync with %s min', elasticConf.intervalMin);
            timerId = setTimeout(tick, timeMSec);
        });
        if (typeof gc === 'function')
            gc();

    }, 2000);
};<commit_msg>fix index elastic<commit_after>/**
 * Created by i.n. on 15.06.2015.
 */

var conf = require('../../config'),
    elasticConf = conf.get('elastic'),
    elastic = require('./elastic')(elasticConf),
    log = require('../../libs/log')(module),
    async = require('async');

//var moment = require('moment');

function exportCollection(desc, mongoDb, callback) {

    var collection = mongoDb.collection(desc.name);
    var query = {};

    var indexName = desc.index + '-' + (new Date().toLocaleDateString()).replace(/-|\//g,'.');

    if (!collection) {
        return callback('collection ' + desc.name + ' does not exist.');
    };

    log.trace(('====> exporting collection [' + desc.name + ']'));

    async.waterfall([
        function (next) {
            log.trace('----> checking connection to elastic');
            elastic.ping({requestTimeout: 10000}, function (err) {
                next(err);
            });
        },
        function (next) {
            log.trace('----> search existing index [' + indexName + ']');
            elastic.indices.stats({index: indexName}, function (err, result) {
                next(null, !err)
            });
        },

        function (existsIndex, next) {
            if (!existsIndex) {
                log.trace('----> creating new index [' + indexName + ']');
                elastic.indices.create({index: indexName}, function (err, result) {
                    next(err);
                });
            } else {
                log.trace('----> skip creating new index [' + indexName + ']');
                next();
            }
        },

        function (next) {
            log.trace('----> find max start_stamp in index [' + indexName + ']');
            elastic.search({
                index: desc.index + '-*',
                size: 1,
                body: {
                    "aggs": {
                        "maxDate": {
                            "max": {
                                "field": "variables.start_stamp"
                            }
                        }
                    }
                }
            }, function (err, result) {
                if (err) return next(err);
                if (!result || !result['aggregations']) {
                    return next(new Error('Bad aggregatins.'))
                }
                query = {
                    "callflow.times.created_time": {
                        "$gt": (result['aggregations']['maxDate']['value'] + 1000) * 1000
                    }
                };
                next();
            });
        },

        function (next) {
            log.trace('----> initialize index mapping');

            if (!desc.mappings) {
                return next();
            }

            elastic.indices.putMapping({index: indexName, type: desc.type, body: desc.mappings}, function (err) {
                next(err);
            });
        },

        function (next) {
            log.trace('----> analizing collection [' + desc.name + ']');
            collection.count(query, function (err, total) {
                if (err) {
                    return next(err);
                }

                log.trace('----> find ' + total + ' documentents to export');
                next(null, total);
            });
        },

        function (total, next) {
            log.trace('----> streaming collection to elastic');

            var stream = collection
                .find(query)
                .stream();

            stream.on('data', function (doc) {
                stream.pause();
                elastic.create({
                    index: indexName,
                    type: desc.type,
                    id: doc._id.toString(),
                    body: {
                        "_id": doc._id.toString(),
                        "variables": doc.variables
                    }
                }, function (err) {
                    if (err) {
                        if (err['message'] && err['message'].indexOf('DocumentAlreadyExistsException') > -1) {
                            log.warn(err['message']);
                        } else {
                            log.error('failed to create document %s in elastic.', err['message']);
                            return next(err);
                        }
                    } else {
                        log.trace('Save document id %s', doc._id.toString());
                    };
                    stream.resume();
                });
            });

            stream.on('end', function (err) {
                stream.destroy();
                next(err, total);
            });
        },

    ], function (err) {
        if (err) {
            log.error(('====> collection [' + desc.name + '] - failed to export.'));
            //log.error(err);
            return callback(err);
        }
        log.trace(('====> collection [' + desc.name + '] - end to export.'));
        callback(null);
    });
};

var started = false;

module.exports = function (mongoDb) {
    if (started) return;
    // TODO ..
    started = true;
    var timeMSec = elasticConf.intervalMin * 60 * 1000;
    var timerId = setTimeout(function tick() {
        exportCollection(elasticConf.collections[0], mongoDb, function (err) {
            log.debug('Next sync with %s min', elasticConf.intervalMin);
            timerId = setTimeout(tick, timeMSec);
        });
        if (typeof gc === 'function')
            gc();

    }, 2000);
};<|endoftext|>


<commit_before>'use strict';

module.exports = function (req, res, next) {
  res.set({
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': '*',
    'Access-Control-Allow-Headers': '*'
  });

  next();
};
<commit_msg>allow cors headers<commit_after>'use strict';

module.exports = function (req, res, next) {
  res.set({
    'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Methods': '*',
    'Access-Control-Allow-Headers': '*',
    'Access-Control-Allow-Credentials': 'true'
  });

  next();
};
<|endoftext|>


<commit_before>angular
	.module('ngSharepointMocks', ['ngSharepoint'])
	.config(['$spProvider', function($spProvider) {
		$spProvider.setSiteUrl('localhost');
	}]);<commit_msg>Updated namespace<commit_after>angular
	.module('ngSharepoint.Mocks', ['ngSharepoint'])
	.config(['$spProvider', function($spProvider) {
		$spProvider.setSiteUrl('localhost');
	}]);<|endoftext|>


<commit_before>module.exports = function (sequelize, DataTypes) {
  var Espacio = sequelize.define(
    'Espacio',
    {
      id: {
        type: DataTypes.BIGINT(11),
        primaryKey: true,
        autoIncrement: true,
        comment: 'ID espacio',
        validate: {
          isNumeric:true,
          notNull: true
        }
      },
      espacio: {
        type: DataTypes.STRING(20),
        allowNull: true,
        defaultValue: null,
        comment: 'Espacio'
      },
      codigoEspacio: {
        type: DataTypes.STRING(2),
        allowNull: true,
        defaultValue: null,
        comment: 'Codigo de Espacio'
      },
      inmuebles: {
        type: DataTypes.STRING(25),
        allowNull: true,
        defaultValue: null,
        comment: 'Inmuebles'
      },
      codigoInmueble: {
        type: DataTypes.STRING(2),
        allowNull: true,
        defaultValue: null,
        comment: 'Codigo de Inmueble'
      },
      ubicacionInmueble: {
        type: DataTypes.STRING(30),
        allowNull: true,
        defaultValue: null,
        comment: 'Ubicacion del Inmueble'
      }
    },
    {
      instanceMethods: {
        retrieveAll: function (onSuccess, onError) {
          Espacio.findAll( { } )
          .then(onSuccess).catch(onError);
        },
        retrieveById: function (espacioId, onSuccess, onError) {
          Espacio.find( { where: { id: espacioId } }, { raw: true })
          .then(onSuccess).catch(onError);
        },
        add: function (onSuccess, onError) {
          var espacio = this.espacio;
          var codigoEspacio = this.codigoEspacio;
          var inmuebles = this.inmuebles;
          var codigoInmueble = this.codigoInmueble;
          var ubicacionInmueble = this.ubicacionInmueble;

          Espacio.build({
            espacio: espacio, codigoEspacio: codigoEspacio, inmuebles: inmuebles,
            codigoInmueble: codigoInmueble, ubicacionInmueble: ubicacionInmueble
          })
          .save().then(onSuccess).catch(onError);
        },
        updateById: function (id, espacio, codigoEspacio, inmuebles, codigoInmueble, ubicacionInmueble, onSuccess, onError) {
          console.log(this.id, this.espacio, this.codigoEspacio, this.inmuebles, this.codigoInmueble, this.ubicacionInmueble);
          Espacio.update(
            { espacio: this.id, this.espacio, this.codigoEspacio, this.inmuebles, this.codigoInmueble, this.ubicacionInmueble },
            { where: { id: this.id } }
          )
          .then(onSuccess).catch(onError);
        },
        removeById: function (espacioId, onSuccess, onError) {
          Espacio.destroy({ where: { id: espacioId }})
          .then(onSuccess).catch(onError);
        }
      },
      timestamps: true,
      paranoid: true,
      createdAt: 'creacion',
      updatedAt: 'modifica',
      deletedAt: 'borrado',
      underscore: false,
      freezeTableName:true,
      tableName: 'Espacios',
      comment: 'Espacios registradas'
      /*
      indexes: [
        {
          name: 'idxEspacio',
          method: 'BTREE',
          unique: false,
          fields: ['Espacio']
        },
        {
          name: 'idxInmuebles',
          method: 'BTREE',
          unique: false,
          fields: ['inmuebles']
        },
        {
          name: 'idxUbicacionInmueble',
          method: 'BTREE',
          unique: true,
          fields: ['ubicacionInmueble']
        }
      ]
      */
    }
  );
  return Espacio;
};
<commit_msg>corrigiendo sintaxis de parametros de update de orm<commit_after>module.exports = function (sequelize, DataTypes) {
  var Espacio = sequelize.define(
    'Espacio',
    {
      id: {
        type: DataTypes.BIGINT(11),
        primaryKey: true,
        autoIncrement: true,
        comment: 'ID espacio',
        validate: {
          isNumeric:true,
          notNull: true
        }
      },
      espacio: {
        type: DataTypes.STRING(20),
        allowNull: true,
        defaultValue: null,
        comment: 'Espacio'
      },
      codigoEspacio: {
        type: DataTypes.STRING(2),
        allowNull: true,
        defaultValue: null,
        comment: 'Codigo de Espacio'
      },
      inmuebles: {
        type: DataTypes.STRING(25),
        allowNull: true,
        defaultValue: null,
        comment: 'Inmuebles'
      },
      codigoInmueble: {
        type: DataTypes.STRING(2),
        allowNull: true,
        defaultValue: null,
        comment: 'Codigo de Inmueble'
      },
      ubicacionInmueble: {
        type: DataTypes.STRING(30),
        allowNull: true,
        defaultValue: null,
        comment: 'Ubicacion del Inmueble'
      }
    },
    {
      instanceMethods: {
        retrieveAll: function (onSuccess, onError) {
          Espacio.findAll( { } )
          .then(onSuccess).catch(onError);
        },
        retrieveById: function (espacioId, onSuccess, onError) {
          Espacio.find( { where: { id: espacioId } }, { raw: true })
          .then(onSuccess).catch(onError);
        },
        add: function (onSuccess, onError) {
          var espacio = this.espacio;
          var codigoEspacio = this.codigoEspacio;
          var inmuebles = this.inmuebles;
          var codigoInmueble = this.codigoInmueble;
          var ubicacionInmueble = this.ubicacionInmueble;

          Espacio.build({
            espacio: espacio, codigoEspacio: codigoEspacio, inmuebles: inmuebles,
            codigoInmueble: codigoInmueble, ubicacionInmueble: ubicacionInmueble
          })
          .save().then(onSuccess).catch(onError);
        },
        updateById: function (id, espacio, codigoEspacio, inmuebles, codigoInmueble, ubicacionInmueble, onSuccess, onError) {
          console.log(this.id, this.espacio, this.codigoEspacio, this.inmuebles, this.codigoInmueble, this.ubicacionInmueble);
          Espacio.update(
            { espacio: this.espacio, codigoEspacio: this.codigoEspacio, inmuebles: this.inmuebles, codigoInmueble: this.codigoInmueble, ubicacionInmueble: this.ubicacionInmueble },
            { where: { id: this.id } }
          )
          .then(onSuccess).catch(onError);
        },
        removeById: function (espacioId, onSuccess, onError) {
          Espacio.destroy({ where: { id: espacioId }})
          .then(onSuccess).catch(onError);
        }
      },
      timestamps: true,
      paranoid: true,
      createdAt: 'creacion',
      updatedAt: 'modifica',
      deletedAt: 'borrado',
      underscore: false,
      freezeTableName:true,
      tableName: 'Espacios',
      comment: 'Espacios registradas'
      /*
      indexes: [
        {
          name: 'idxEspacio',
          method: 'BTREE',
          unique: false,
          fields: ['Espacio']
        },
        {
          name: 'idxInmuebles',
          method: 'BTREE',
          unique: false,
          fields: ['inmuebles']
        },
        {
          name: 'idxUbicacionInmueble',
          method: 'BTREE',
          unique: true,
          fields: ['ubicacionInmueble']
        }
      ]
      */
    }
  );
  return Espacio;
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2017 Thomas Otterson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// options.js
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tracks and allows the setting of a few runtime-configurable options.

import { setDispatcher } from './dispatcher';

export const options = {
  // The maximum number of operations (puts or takes) that can be queued in a channel buffer before running a cleanup
  // operation to make sure no inactive operations are in the queue.
  maxDirtyOps:    64,
  // The maximum number of puts or takes that can be queued on a channel at the same time.
  maxQueuedOps:   1024,
  // The maximum number of tasks that the dispatcher will run in a single batch. If the number of pending tasks exceeds
  // this, the remaining are not discarded. They're simply run as part of another batch after the current batch
  // completes. Setting this to a reasonable number makes sure that control can pass back to the event loop every now
  // and then, even if there are thousands of tasks in the queue.
  taskBatchSize:  1024,
  // The default process error handler. If this is set and an uncaught `yield raise` happens in the process, this error
  // handler is used to manage the error. It's a function that takes one parameter, which is an object containing an
  // `error` property which is the actual error. (This is to allow future expansion of the library's error-handling
  // capabilities.)
  defaultHandler: null,
  // The method used for dispatch. Possible values are 'setImmediate', 'MessageChannel', and 'setTimeout'. This option
  // specifies the internal method used for dispatch of asynchronous tasks. If the chosen method isn't available, then
  // the first one further down the chain (setImmediate -> MessageChannel -> setTimeout) that is available is used.
  //
  // There should be little reason to change this option. The only possibility is in an environment where one of the
  // methods is available but doesn't work quite right; then another one further down the chain can be chosen instead.
  dispatchMethod: 'setImmediate'
};

// Sets the values of one or more configurable options. This function takes an object for a parameter, and if any of
// that object's property's names match one of those of the options object, its value becomes the new value of that
// option. Properties that don't exist as options are ignored, and options that are not present in the parameter are
// left unchanged.
export function config(opts) {
  for (const key in options) {
    if (opts.hasOwnProperty(key)) {
      options[key] = opts[key];

      if (key === 'dispatchMethod') {
        setDispatcher();
      }
    }
  }
}
<commit_msg>Removed defaultHandler from options, as it's no longer necessary with goSafe<commit_after>/*
 * Copyright (c) 2017 Thomas Otterson
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of
 * this software and associated documentation files (the "Software"), to deal in
 * the Software without restriction, including without limitation the rights to
 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
 * the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// options.js
// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tracks and allows the setting of a few runtime-configurable options.

import { setDispatcher } from './dispatcher';

export const options = {
  // The maximum number of operations (puts or takes) that can be queued in a channel buffer before running a cleanup
  // operation to make sure no inactive operations are in the queue.
  maxDirtyOps:    64,
  // The maximum number of puts or takes that can be queued on a channel at the same time.
  maxQueuedOps:   1024,
  // The maximum number of tasks that the dispatcher will run in a single batch. If the number of pending tasks exceeds
  // this, the remaining are not discarded. They're simply run as part of another batch after the current batch
  // completes. Setting this to a reasonable number makes sure that control can pass back to the event loop every now
  // and then, even if there are thousands of tasks in the queue.
  taskBatchSize:  1024,
  // The default process error handler. If this is set and an uncaught `yield raise` happens in the process, this error
  // handler is used to manage the error. It's a function that takes one parameter, which is an object containing an
  // `error` property which is the actual error. (This is to allow future expansion of the library's error-handling
  // capabilities.)
  dispatchMethod: 'setImmediate'
};

// Sets the values of one or more configurable options. This function takes an object for a parameter, and if any of
// that object's property's names match one of those of the options object, its value becomes the new value of that
// option. Properties that don't exist as options are ignored, and options that are not present in the parameter are
// left unchanged.
export function config(opts) {
  for (const key in options) {
    if (opts.hasOwnProperty(key)) {
      options[key] = opts[key];

      if (key === 'dispatchMethod') {
        setDispatcher();
      }
    }
  }
}
<|endoftext|>


<commit_before>var React = require('react');
var Bootstrap = require('react-bootstrap');
var _ = require('lodash');
var debug = require('debug')("craftodex:ui:group:views:page")

var router = require('router');
var registry = require('registry');
var Group = require('group/model');

module.exports = React.createClass({

  componentDidMount: function () {
    this.props.model.on("change", function () {
      this.forceUpdate();
    }, this);
  },

  render: function () {

    var model = this.props.model;

    debug("render", model);

    console.log("model.relationshipsByType", model.hasRelsByType);

    var relsByType = _.map(model.hasRelsByType, function (rels, relTypeId) {

      var relType = registry.get(relTypeId);

      console.log(relType, rels);

      return (

            { relType.name }

          <Bootstrap.ListGroup>
            {
              rels.map(function (rel) {
                return (
                  <Bootstrap.ListGroupItem>
                    { rel.has.name }
                  </Bootstrap.ListGroupItem>
                );
              })
            }
          </Bootstrap.ListGroup>

      );
    });

    return (

            {model.name}

        { relsByType }

    );
  },
});
<commit_msg>remove old console.logs<commit_after>var React = require('react');
var Bootstrap = require('react-bootstrap');
var _ = require('lodash');
var debug = require('debug')("craftodex:ui:group:views:page")

var router = require('router');
var registry = require('registry');
var Group = require('group/model');

module.exports = React.createClass({

  componentDidMount: function () {
    this.props.model.on("change", function () {
      this.forceUpdate();
    }, this);
  },

  render: function () {

    var model = this.props.model;

    debug("render", model);

    var relsByType = _.map(model.hasRelsByType, function (rels, relTypeId) {

      var relType = registry.get(relTypeId);

      return (

            { relType.name }

          <Bootstrap.ListGroup>
            {
              rels.map(function (rel) {
                return (
                  <Bootstrap.ListGroupItem>
                    { rel.has.name }
                  </Bootstrap.ListGroupItem>
                );
              })
            }
          </Bootstrap.ListGroup>

      );
    });

    return (

            {model.name}

        { relsByType }

    );
  },
});
<|endoftext|>