<commit_before>angular.module('RailsModel', ['rails'])
.factory('Model', ['railsResourceFactory', '$q', function (railsResourceFactory, $q) {
  var requestTransformers =  'protectedAttributeRemovalTransformer updateParentNestedValue railsRootWrappingTransformer railsFieldRenamingTransformer'.split(' ');
  return function (options) {

    var idMap = {};
    function objectForData(klass, data) {
      var result;
      if (typeof data.id !== 'undefined') {
        if (typeof idMap[data.id] != 'undefined') {
          result = idMap[data.id];
        } else {
          result = new klass();
          idMap[data.id] = result;
        }
      } else {
        result = new klass();
      }
      return angular.extend(result, data);
    }

    options.requestTransformers = requestTransformers;
    options.responseInterceptors = ['railsFieldRenamingInterceptor', 'railsRootWrappingInterceptor', [function () {
      return function (promise) {
        var RailsResource = promise.resource;
        promise.resource.processResponse = function (promise) {
          promise = RailsResource.callInterceptors(promise);
          return promise.then(function (response) {
            var result;
            if (angular.isArray(response.data)) {
              result = [];
              angular.forEach(response.data, function (value) {
                result.push(objectForData(RailsResource, value));
              });
            } else if (angular.isObject(response.data)) {
              result = objectForData(RailsResource, response.data);
            } else {
              result = response.data;
            }
            return result;
          });
        };
        return promise;
      }
    }]];

    var factory = railsResourceFactory(options);
    var originalUpdate = factory.prototype.update;
    var originalCreate = factory.prototype.create;
    var originalRemove = factory.prototype.remove;

    factory.prototype.update = function () {
      this.isSaving = true;
      return originalUpdate.apply(this, arguments).then(function(data) { data.isSaving = false });
    }

    factory.prototype.create = function () {
      this.isSaving = true;
      return originalCreate.apply(this, arguments).then(function(data) { data.isSaving = false });
    }

    factory.prototype.remove = function () {
      this.isSaving = true;
      return originalRemove.apply(this, arguments).then(function(data) { data.isSaving = false });
    }

    factory.get = function (context, queryParams) {
      var result;
      if (angular.isNumber(context)) {
        if (typeof idMap[context] !== 'undefined') {
          result = idMap[context];
        }
      } else if (angular.isNumber(context.id)) {
        if (typeof idMap[context.id] !== 'undefined') {
          result = idMap[context.id];
        }
      }
      if (typeof result !== 'undefined') {
        var deferred = $q.defer();
        deferred.resolve(result);
        factory.$get(factory.resourceUrl(context), queryParams).then(function (data) {
          angular.extend(result, data);
        });
        return deferred.promise;
      } else {
        return factory.$get(factory.resourceUrl(context), queryParams);
      }
    };

    return factory;
  }
}])
.factory('updateParentNestedValue', [function () {
  return function (data, resource) {
    if (resource.attrNested && resource.attrNested.length && resource.attrNested.length > 0) {
      for (index in resource.attrNested) {
        var key = resource.attrNested[index];
        var attrVals = key.split('_');
        if (attrVals.length == 2) {
          var nestedAttr = data[attrVals[0]][attrVals[1]];
          data[key] = nestedAttr;
        }
      }
    }
    return data;
  }
}])
.factory('protectedAttributeRemovalTransformer', [function () {
  return function (data, resource) {
    var obj = data;
    if (resource.attrAccessible && resource.attrAccessible.length && resource.attrAccessible.length > 0) {
      obj = {};
      for (index in resource.attrAccessible) {
        var key = resource.attrAccessible[index];
        var val = data[key.replace(/Attributes$/, '')];
        if (typeof val !== 'undefined' && val != null && !(angular.isArray(val) && !val.length)) {
          obj[key] = val;
        }
      }
    }
    return obj;
  }
}]);
<commit_msg>query cache<commit_after>angular.module('RailsModel', ['rails'])
.factory('Model', ['railsResourceFactory', '$q', function (railsResourceFactory, $q) {
  var requestTransformers =  'protectedAttributeRemovalTransformer updateParentNestedValue railsRootWrappingTransformer railsFieldRenamingTransformer'.split(' ');
  return function (options) {

    var idMap = {};
    var queryCache = {};

    function objectForData(klass, data) {
      var result;
      if (typeof data.id !== 'undefined') {
        if (typeof idMap[data.id] != 'undefined') {
          result = idMap[data.id];
        } else {
          result = new klass();
          idMap[data.id] = result;
        }
      } else {
        result = new klass();
      }
      return angular.extend(result, data);
    }

    options.requestTransformers = requestTransformers;
    options.responseInterceptors = ['railsFieldRenamingInterceptor', 'railsRootWrappingInterceptor', [function () {
      return function (promise) {
        var RailsResource = promise.resource;
        promise.resource.processResponse = function (promise) {
          promise = RailsResource.callInterceptors(promise);
          return promise.then(function (response) {
            var result;
            if (angular.isArray(response.data)) {
              result = [];
              angular.forEach(response.data, function (value) {
                result.push(objectForData(RailsResource, value));
              });
            } else if (angular.isObject(response.data)) {
              result = objectForData(RailsResource, response.data);
            } else {
              result = response.data;
            }
            return result;
          });
        };
        return promise;
      }
    }]];

    var factory = railsResourceFactory(options);
    var originalUpdate = factory.prototype.update;
    var originalCreate = factory.prototype.create;
    var originalRemove = factory.prototype.remove;

    factory.prototype.update = function () {
      this.isSaving = true;
      return originalUpdate.apply(this, arguments).then(function(data) { data.isSaving = false });
    }

    factory.prototype.create = function () {
      this.isSaving = true;
      return originalCreate.apply(this, arguments).then(function(data) { data.isSaving = false });
    }

    factory.prototype.remove = function () {
      this.isSaving = true;
      return originalRemove.apply(this, arguments).then(function(data) { data.isSaving = false });
    }

    factory.get = function (context, queryParams) {
      var result;
      if (angular.isNumber(context)) {
        if (typeof idMap[context] !== 'undefined') {
          result = idMap[context];
        }
      } else if (angular.isNumber(context.id)) {
        if (typeof idMap[context.id] !== 'undefined') {
          result = idMap[context.id];
        }
      }
      if (typeof result !== 'undefined') {
        var deferred = $q.defer();
        deferred.resolve(result);
        factory.$get(factory.resourceUrl(context), queryParams).then(function (data) {
          angular.extend(result, data);
        });
        return deferred.promise;
      } else {
        return factory.$get(factory.resourceUrl(context), queryParams);
      }
    };

    factory.query = function (queryParams, context) {
      queryParams = queryParams || {};
      context = context || {};
      var hash = JSON.stringify([queryParams, context]);

      var result = factory.$get(factory.resourceUrl(context), queryParams).then(function (data) {
        if (typeof queryCache[hash] == 'undefined') {
          queryCache[hash] = data;
        } else {
          if (angular.isObject(data)) {
            angular.forEach(data, function (value, key) {
              queryCache[hash][key] = value;
            });
          } else {
            var array = queryCache[hash];
            var loc = -1;
            angular.forEach(data, function (obj, index) {
              loc = array.indexOf(obj);
              if (loc !== -1 && loc !== index) {
                array.splice(loc, 1);
                loc = -1;
              }
              if (loc == -1) {
                array.splice(index, 0, obj);
              }
            });
            array.length = data.length;
          }
        }
        return queryCache[hash];
      });

      if (typeof queryCache[hash] !== 'undefined') {
        console.log("Getting it from the query cache");
        console.log(queryCache[hash]);
        var deferred = $q.defer();
        deferred.resolve(queryCache[hash]);
        result = deferred.promise;
      }

      console.log(queryCache);
      console.log(result);

      return result;
    }

    return factory;
  }
}])
.factory('updateParentNestedValue', [function () {
  return function (data, resource) {
    if (resource.attrNested && resource.attrNested.length && resource.attrNested.length > 0) {
      for (index in resource.attrNested) {
        var key = resource.attrNested[index];
        var attrVals = key.split('_');
        if (attrVals.length == 2) {
          var nestedAttr = data[attrVals[0]][attrVals[1]];
          data[key] = nestedAttr;
        }
      }
    }
    return data;
  }
}])
.factory('protectedAttributeRemovalTransformer', [function () {
  return function (data, resource) {
    var obj = data;
    if (resource.attrAccessible && resource.attrAccessible.length && resource.attrAccessible.length > 0) {
      obj = {};
      for (index in resource.attrAccessible) {
        var key = resource.attrAccessible[index];
        var val = data[key.replace(/Attributes$/, '')];
        if (typeof val !== 'undefined' && val != null && !(angular.isArray(val) && !val.length)) {
          obj[key] = val;
        }
      }
    }
    return obj;
  }
}]);
<|endoftext|>


<commit_before>suiteHasFailed = function (suite)  {
  return !! VelocityTestReports.findOne({
    framework: suite.framework,
    ancestors: suite.ancestors,
    result: "failed"
  });
};

frameworkStatus = function (name) {
  var hasTests = VelocityTestReports.find({framework: name}).count() > 0;
  if (!hasTests) return "empty"

  var frameworkExecStatus = VelocityAggregateReports.findOne({name: name});
  var isComplete = (frameworkExecStatus && frameworkExecStatus.result === "completed");
  var hasFailed = !! VelocityTestReports.findOne({framework: name, result: "failed"});

  if (hasFailed)
    return "failed";
  else if (isComplete)
    return "passed";
  else
    return "pending";
}

function mochaPresent() {
  //XXX hard-coding mocha iframe support for now
  return !! VelocityAggregateReports.findOne({'name': 'mocha'});
}
function nightwatchPresent() {
  return !! VelocityAggregateReports.findOne({'name': 'nightwatch'});
}

Template.velocity.created = function () {
  // Only show widget when we know we are NOT running in a Velocity Mirror
  Session.setDefault('velocity.isMirror', true);

  // Determine if session is running in a Velocity mirror or not
  Meteor.call('velocity/isMirror', function (err, res) {
    if (err) {
      // Log error. HTML Reporter will not be shown
      console.log(err);
    } else {
      Session.set('velocity.isMirror', res);
    }
  })
};

Template.velocity.helpers({
  statusWidgetClass: function () {
    var aggregateResult = VelocityAggregateReports.findOne({name: 'aggregateResult'});
    if (aggregateResult && aggregateResult.result === 'failed') {
      return  'failed';
    }

    var aggregateComplete = VelocityAggregateReports.findOne({name: 'aggregateComplete'});
    if (aggregateComplete && aggregateResult
      && aggregateResult.result === 'passed' && aggregateComplete.result === 'completed') {
      return 'passed';
    }
    return 'pending';
  },
  resetting: function () {
    return Session.get('resettingVelocity')
  },
  testReports: function () {
    return VelocityTestReports.find();
  },
  frameworks: function () {
    return VelocityAggregateReports.find({name: {$nin: ["aggregateResult", "aggregateComplete"]}});
  },
  active: function (id) {
    return reamplify.store(id);
  },
  overlayIsVisible: function () {
    return amplify.store('velocityOverlayIsVisible')
  },
  notInMirror: function () {
    // This causes the html reporter to remain hidden if running in a Velocity mirror
    return Session.equals('velocity.isMirror', false);
  },
  mochaPresent: mochaPresent,
  nightwatchPresent: nightwatchPresent
});

Template.velocityReports.helpers({
  frameworkStatus: function () {
    return frameworkStatus(this.name)
  },
  isPassed: function (status) {
    return status === 'passed'
  },
  frameworkTotalTestCount: function () {
    return VelocityTestReports.find({framework: this.name}).count();
  },
  frameworkPassedTestCount: function () {
    return VelocityTestReports.find({framework: this.name, result: 'passed'}).count();
  },
  noFrameworkFiles: function () {
    // XXX presence of VelocityAggregateReports is a stand-in for
    // Velocity being loaded. This is a bit brittle. It breaks
    // if you call the Velocity "reset" method.
    var velocityIsLoaded = !! VelocityAggregateReports;
    return  ! velocityIsLoaded ?  false : ! VelocityTestFiles.findOne({targetFramework: this.name});
  },
  suites: function () {
    var result =  [];
    var reports = VelocityTestReports.find({framework: this.name}).fetch();
    // XXX for now, ancestors get reduced to a single-tier suite
    // Should we do fancier indenting, etc. for nested suites?
    // If not, forcing packages to concatenate their own "suite" string
    // instead of ancestors array would clean this up.
    if (reports.length > 0) {

      var reports = _.map(reports, function (report) {
        //must clone report.ancestors to not mutate report.ancestors with .reverse()
        var ancestors = report.ancestors ? _.clone(report.ancestors) : [];
        report.suite = ancestors.reverse().join(".");
        return report;
      });

      _.each(reports, function (report) {
        if (! _.findWhere(result, {suite: report.suite}))
          result.push({
            framework: report.framework,
            ancestors: report.ancestors, //needed for future queries
            suite: report.suite
          })
      });

      return result;
    }
  },
  suiteStatus: function () {
    return suiteHasFailed(this) ? 'failed' : 'passed';
  },
  suiteNotHidden: function () {
    if (!reamplify.store('showSuccessful'))
      return suiteHasFailed(this);
    return true;
  },
  reports: function () {
    return VelocityTestReports.find({
      framework: this.framework,
      ancestors: this.ancestors
    });
  }
});

Template.velocitySummary.helpers({
  anyFailed: function () {
    var aggregateResult = VelocityAggregateReports.findOne({name: 'aggregateResult'})
    if (aggregateResult && aggregateResult.result === 'failed') {
      return  true;
    }
    return false;
  },
  totalTime: function () {
    var ms = VelocityTestReports
               .find({result: 'passed'})
               .fetch()
               .reduce(function (tot, i) { return tot + (i.duration || 0) }, 0);

    if (ms >= 1000) return Math.round(ms / 1000) + ' s';

    return ms + ' ms';
  },
  regularPlural: function (count, word, suffix) {
    if(count === 1) return word;
    return word + suffix;
  },
  totalFailedTestCount: function () {
    return VelocityTestReports.find({result: 'failed'}).count();
  },
  totalTestCount: function () {
    return VelocityTestReports.find().count();
  },
  totalPassedTestCount: function () {
    return VelocityTestReports.find({result: 'passed'}).count();
  },
});

Template.velocityControlPanel.helpers({
  mochaPresent: mochaPresent,
  nightwatchPresent: nightwatchPresent,
  showActive: function (id) {
    // XXX refactor this to name consistently
    return !reamplify.store(id) ? '' : 'active';
  },
  showActive: function (self) {
    // $self = $("#"+ self);
    return reamplify.store(self) ? 'active' : ''
  }
});

Template.velocityControlPanel.events({
  'click #runNightwatchTests': function () {
    console.log('#runNightwatchTests clicked.');
    Meteor.call('nightwatch/run');
  }
})

Template.velocityTestReport.helpers({
  reportNotHidden: function () {
    if (this.result === "failed")
      return true;
    else{
      return (reamplify.store('showSuccessful'));
    }
  },
  failed: function () {
    return (this.result === "failed");
  }
});

Template.velocityTestFiles.helpers({
  testFiles: function () {
    return VelocityTestFiles.find();
  },
  isVisible: function () {
    return amplify.store('velocityTestFilesIsVisible') ? 'block' : 'none';
  }
});

Template.velocityLogs.helpers({
  logs: function () {
    return VelocityLogs.find();
  },
  isVisible: function () {
    return amplify.store('velocityLogsIsVisible') ? 'block' : 'none';
  }
});

Template.velocity.events({
  'click .display-toggle': function (e) {
    var targetId = $(e.currentTarget).data('target'),
        $target = $('#' + targetId);
    $target.toggleClass('visible');
    amplify.store(targetId + 'IsVisible', $target.hasClass('visible') );
  },
  'change input:checkbox': function (e) {
    var targetId = e.target.id
    reamplify.store(e.target.id, e.target.checked);
  },
  'click button.control-toggle': function (e) {
    var $target = $('#' + e.target.id);
    $target.toggleClass('active');
    reamplify.store(e.target.id, $target.hasClass('active'));
  },
  'click .velocity-options-toggle': function (e, tpl) {
    tpl.$('.velocity-options').toggleClass('visible')
  }
});

Template.velocityReports.events({
  'click .copy-sample-tests': function (e) {
    Meteor.call('velocity/copySampleTests', {framework: this.name}, function (err, res) {
      // XXX This method for getting the new files to register is slow, but it
      // works. The reset method gets Velocity to see the new files.
      // We then disconnect altogether to prevent flapping of reactive
      // template elements (& overlay a notification to show the user
      // what's happening). Then we simply reload. Is there a way to do this
      // with a lighter touch?

      // make sure the user can see the demo tests, which generally pass.
      reamplify.store('showSuccessful', true);
      Session.set('resettingVelocity', true)
      Meteor.call('velocity/reset');
      Meteor.disconnect();
      location.reload();
    });
  }
});
<commit_msg>Changed console.log to console.error<commit_after>suiteHasFailed = function (suite)  {
  return !! VelocityTestReports.findOne({
    framework: suite.framework,
    ancestors: suite.ancestors,
    result: "failed"
  });
};

frameworkStatus = function (name) {
  var hasTests = VelocityTestReports.find({framework: name}).count() > 0;
  if (!hasTests) return "empty"

  var frameworkExecStatus = VelocityAggregateReports.findOne({name: name});
  var isComplete = (frameworkExecStatus && frameworkExecStatus.result === "completed");
  var hasFailed = !! VelocityTestReports.findOne({framework: name, result: "failed"});

  if (hasFailed)
    return "failed";
  else if (isComplete)
    return "passed";
  else
    return "pending";
}

function mochaPresent() {
  //XXX hard-coding mocha iframe support for now
  return !! VelocityAggregateReports.findOne({'name': 'mocha'});
}
function nightwatchPresent() {
  return !! VelocityAggregateReports.findOne({'name': 'nightwatch'});
}

Template.velocity.created = function () {
  // Only show widget when we know we are NOT running in a Velocity Mirror
  Session.setDefault('velocity.isMirror', true);

  // Determine if session is running in a Velocity mirror or not
  Meteor.call('velocity/isMirror', function (err, res) {
    if (err) {
      // Log error. HTML Reporter will not be shown
      console.error(err);
    } else {
      Session.set('velocity.isMirror', res);
    }
  })
};

Template.velocity.helpers({
  statusWidgetClass: function () {
    var aggregateResult = VelocityAggregateReports.findOne({name: 'aggregateResult'});
    if (aggregateResult && aggregateResult.result === 'failed') {
      return  'failed';
    }

    var aggregateComplete = VelocityAggregateReports.findOne({name: 'aggregateComplete'});
    if (aggregateComplete && aggregateResult
      && aggregateResult.result === 'passed' && aggregateComplete.result === 'completed') {
      return 'passed';
    }
    return 'pending';
  },
  resetting: function () {
    return Session.get('resettingVelocity')
  },
  testReports: function () {
    return VelocityTestReports.find();
  },
  frameworks: function () {
    return VelocityAggregateReports.find({name: {$nin: ["aggregateResult", "aggregateComplete"]}});
  },
  active: function (id) {
    return reamplify.store(id);
  },
  overlayIsVisible: function () {
    return amplify.store('velocityOverlayIsVisible')
  },
  notInMirror: function () {
    // This causes the html reporter to remain hidden if running in a Velocity mirror
    return Session.equals('velocity.isMirror', false);
  },
  mochaPresent: mochaPresent,
  nightwatchPresent: nightwatchPresent
});

Template.velocityReports.helpers({
  frameworkStatus: function () {
    return frameworkStatus(this.name)
  },
  isPassed: function (status) {
    return status === 'passed'
  },
  frameworkTotalTestCount: function () {
    return VelocityTestReports.find({framework: this.name}).count();
  },
  frameworkPassedTestCount: function () {
    return VelocityTestReports.find({framework: this.name, result: 'passed'}).count();
  },
  noFrameworkFiles: function () {
    // XXX presence of VelocityAggregateReports is a stand-in for
    // Velocity being loaded. This is a bit brittle. It breaks
    // if you call the Velocity "reset" method.
    var velocityIsLoaded = !! VelocityAggregateReports;
    return  ! velocityIsLoaded ?  false : ! VelocityTestFiles.findOne({targetFramework: this.name});
  },
  suites: function () {
    var result =  [];
    var reports = VelocityTestReports.find({framework: this.name}).fetch();
    // XXX for now, ancestors get reduced to a single-tier suite
    // Should we do fancier indenting, etc. for nested suites?
    // If not, forcing packages to concatenate their own "suite" string
    // instead of ancestors array would clean this up.
    if (reports.length > 0) {

      var reports = _.map(reports, function (report) {
        //must clone report.ancestors to not mutate report.ancestors with .reverse()
        var ancestors = report.ancestors ? _.clone(report.ancestors) : [];
        report.suite = ancestors.reverse().join(".");
        return report;
      });

      _.each(reports, function (report) {
        if (! _.findWhere(result, {suite: report.suite}))
          result.push({
            framework: report.framework,
            ancestors: report.ancestors, //needed for future queries
            suite: report.suite
          })
      });

      return result;
    }
  },
  suiteStatus: function () {
    return suiteHasFailed(this) ? 'failed' : 'passed';
  },
  suiteNotHidden: function () {
    if (!reamplify.store('showSuccessful'))
      return suiteHasFailed(this);
    return true;
  },
  reports: function () {
    return VelocityTestReports.find({
      framework: this.framework,
      ancestors: this.ancestors
    });
  }
});

Template.velocitySummary.helpers({
  anyFailed: function () {
    var aggregateResult = VelocityAggregateReports.findOne({name: 'aggregateResult'})
    if (aggregateResult && aggregateResult.result === 'failed') {
      return  true;
    }
    return false;
  },
  totalTime: function () {
    var ms = VelocityTestReports
               .find({result: 'passed'})
               .fetch()
               .reduce(function (tot, i) { return tot + (i.duration || 0) }, 0);

    if (ms >= 1000) return Math.round(ms / 1000) + ' s';

    return ms + ' ms';
  },
  regularPlural: function (count, word, suffix) {
    if(count === 1) return word;
    return word + suffix;
  },
  totalFailedTestCount: function () {
    return VelocityTestReports.find({result: 'failed'}).count();
  },
  totalTestCount: function () {
    return VelocityTestReports.find().count();
  },
  totalPassedTestCount: function () {
    return VelocityTestReports.find({result: 'passed'}).count();
  },
});

Template.velocityControlPanel.helpers({
  mochaPresent: mochaPresent,
  nightwatchPresent: nightwatchPresent,
  showActive: function (id) {
    // XXX refactor this to name consistently
    return !reamplify.store(id) ? '' : 'active';
  },
  showActive: function (self) {
    // $self = $("#"+ self);
    return reamplify.store(self) ? 'active' : ''
  }
});

Template.velocityControlPanel.events({
  'click #runNightwatchTests': function () {
    console.log('#runNightwatchTests clicked.');
    Meteor.call('nightwatch/run');
  }
})

Template.velocityTestReport.helpers({
  reportNotHidden: function () {
    if (this.result === "failed")
      return true;
    else{
      return (reamplify.store('showSuccessful'));
    }
  },
  failed: function () {
    return (this.result === "failed");
  }
});

Template.velocityTestFiles.helpers({
  testFiles: function () {
    return VelocityTestFiles.find();
  },
  isVisible: function () {
    return amplify.store('velocityTestFilesIsVisible') ? 'block' : 'none';
  }
});

Template.velocityLogs.helpers({
  logs: function () {
    return VelocityLogs.find();
  },
  isVisible: function () {
    return amplify.store('velocityLogsIsVisible') ? 'block' : 'none';
  }
});

Template.velocity.events({
  'click .display-toggle': function (e) {
    var targetId = $(e.currentTarget).data('target'),
        $target = $('#' + targetId);
    $target.toggleClass('visible');
    amplify.store(targetId + 'IsVisible', $target.hasClass('visible') );
  },
  'change input:checkbox': function (e) {
    var targetId = e.target.id
    reamplify.store(e.target.id, e.target.checked);
  },
  'click button.control-toggle': function (e) {
    var $target = $('#' + e.target.id);
    $target.toggleClass('active');
    reamplify.store(e.target.id, $target.hasClass('active'));
  },
  'click .velocity-options-toggle': function (e, tpl) {
    tpl.$('.velocity-options').toggleClass('visible')
  }
});

Template.velocityReports.events({
  'click .copy-sample-tests': function (e) {
    Meteor.call('velocity/copySampleTests', {framework: this.name}, function (err, res) {
      // XXX This method for getting the new files to register is slow, but it
      // works. The reset method gets Velocity to see the new files.
      // We then disconnect altogether to prevent flapping of reactive
      // template elements (& overlay a notification to show the user
      // what's happening). Then we simply reload. Is there a way to do this
      // with a lighter touch?

      // make sure the user can see the demo tests, which generally pass.
      reamplify.store('showSuccessful', true);
      Session.set('resettingVelocity', true)
      Meteor.call('velocity/reset');
      Meteor.disconnect();
      location.reload();
    });
  }
});
<|endoftext|>


<commit_before>var processParse = require('./processParse');
var r = require('./redis');
var redis = r.client;
var jobs = r.jobs;
var cluster = require('cluster');
start();

function start() {
    if (cluster.isMaster) {
        console.log("[PARSEMANAGER] starting master");
            redis.get("parsers", function(err, result) {
                if (err || !result) {
                    console.log("no parsers in redis!");
                    return setTimeout(function() {
                        return start();
                    }, 10000);
                }
                var parsers = JSON.parse(result);
                //length of this array is capacity
                var capacity = parsers.length;
                //run one job.process for requests
                jobs.process('request_parse', function(job, cb) {
                    job.parser_url = parsers[0];
                    processParse(job, cb);
                });
                //run one jobs.process with parallelism=capacity
                jobs.process('parse', capacity, function(job, cb) {
                    //RR or randomly select a parser for each job
                    getParserRandom(job, function() {
                        processParse(job, cb);
                    });
                });
                /*
                var urls = {};
                // code to spawn a thread for each parsing core
                for (var i = 0; i < capacity; i++) {
                    cluster.fork({
                        PARSER_URL: parsers[i]
                    });
                }
                // handle unwanted worker exits
                cluster.on("exit", function(worker, code) {
                    if (code != 0) {
                        console.log("Worker crashed! Spawning a replacement.");
                        //fork a new worker with the same url as the one that crashed
                        //lookup by worker id
                        cluster.fork({
                            PARSER_URL: urls[worker.id]
                        });
                    }
                });
                Object.keys(cluster.workers).forEach(function(id) {
                    cluster.workers[id].on('message', function(msg) {
                        console.log(msg);
                        //a new worker is running, keep track of what url it's using
                        urls[msg.id] = msg.url;
                    });
                });
                */
            });
    }
    else {
        /*
        console.log("[PARSEMANAGER] starting worker");
        process.send({
            id: cluster.worker.id,
            url: process.env.PARSER_URL
        });
        //insert into job the parser this worker should use
        jobs.process('parse', function(job, cb) {
            getParserEnv(job, function() {
                processParse(job, cb);
            });
        });
function getParserEnv(job, cb) {
    job.parser_url = process.env.PARSER_URL;
    cb();
}
*/
    }
}

function getParserRandom(job, cb) {
    redis.get("parsers", function(err, result) {
        if (err || !result) {
            console.log("no parsers in redis!");
            return getParserRandom(job, cb);
        }
        var parsers = JSON.parse(result);
        job.parser_url = parsers[Math.floor(Math.random() * parsers.length)];
        cb();
    });
}
<commit_msg>moved a function<commit_after>var processParse = require('./processParse');
var r = require('./redis');
var redis = r.client;
var jobs = r.jobs;
var cluster = require('cluster');
start();

function start() {
    if (cluster.isMaster) {
        console.log("[PARSEMANAGER] starting master");
        redis.get("parsers", function(err, result) {
            if (err || !result) {
                console.log("no parsers in redis!");
                return setTimeout(function() {
                    return start();
                }, 10000);
            }
            var parsers = JSON.parse(result);
            //length of this array is capacity
            var capacity = parsers.length;
            //run one job.process for requests
            jobs.process('request_parse', function(job, cb) {
                job.parser_url = parsers[0];
                processParse(job, cb);
            });
            //run one jobs.process with parallelism=capacity
            jobs.process('parse', capacity, function(job, cb) {
                //RR or randomly select a parser for each job
                getParserRandom(job, function() {
                    processParse(job, cb);
                });
            });
            /*
            var urls = {};
            // code to spawn a thread for each parsing core
            // this makes it harder to adjust parallelism on the fly
            for (var i = 0; i < capacity; i++) {
                cluster.fork({
                    PARSER_URL: parsers[i]
                });
            }
            // handle unwanted worker exits
            cluster.on("exit", function(worker, code) {
                if (code !== 0) {
                    console.log("Worker crashed! Spawning a replacement.");
                    //fork a new worker with the same url as the one that crashed
                    //lookup by worker id
                    cluster.fork({
                        PARSER_URL: urls[worker.id]
                    });
                }
            });
            Object.keys(cluster.workers).forEach(function(id) {
                cluster.workers[id].on('message', function(msg) {
                    console.log(msg);
                    //a new worker is running, keep track of what url it's using
                    urls[msg.id] = msg.url;
                });
            });
            */
        });
    }
    else {
        /*
        console.log("[PARSEMANAGER] starting worker");
        process.send({
            id: cluster.worker.id,
            url: process.env.PARSER_URL
        });
        //insert into job the parser this worker should use
        jobs.process('parse', function(job, cb) {
            getParserEnv(job, function() {
                processParse(job, cb);
            });
        });

*/
    }
}

function getParserEnv(job, cb) {
    job.parser_url = process.env.PARSER_URL;
    cb();
}

function getParserRandom(job, cb) {
    redis.get("parsers", function(err, result) {
        if (err || !result) {
            console.log("no parsers in redis!");
            return getParserRandom(job, cb);
        }
        var parsers = JSON.parse(result);
        job.parser_url = parsers[Math.floor(Math.random() * parsers.length)];
        cb();
    });
}
<|endoftext|>


<commit_before>var postcss = require('postcss');
var expect  = require('chai').expect;

var plugin = require('../');

var test = function (input, output, opts, done) {
    postcss([ plugin(opts) ]).process(input).then(function (result) {
        expect(result.css).to.eql(output);
        expect(result.warnings()).to.be.empty;
        done();
    }).catch(function (error) {
        done(error);
    });
};

describe('postcss-position-alt', function () {

    it('test position absolute', function (done) {
      test('a{ absolute: top 10px left 20px right 30px bottom 40px; }',
           'a{ position: absolute; top: 10px; left: 20px; right: 30px; bottom: 40px; }', { }, done);
    });
    it('test position absolute no value', function (done) {
      test('a{ absolute: top left; }',
           'a{ position: absolute; top: 0; left: 0; }', { }, done);
    });

    it('test position fixed', function (done) {
      test('a{ fixed: bottom 10% right 4em; }',
           'a{ position: fixed; bottom: 10%; right: 4em; }', { }, done);
    });

    it('test auto and inherit value', function (done) {
      test('a{ fixed: bottom auto right inherit left; }',
           'a{ position: fixed; bottom: auto; right: inherit; left: 0; }', { }, done);
    });

    it('test relative', function (done) {
      test('a{ relative: top -1px; }',
           'a{ position: relative; top: -1px; }', { }, done);
    });

});
<commit_msg>fixed test<commit_after>var postcss = require('postcss');
var expect  = require('chai').expect;

var plugin = require('../');

var test = function (input, output, opts, done) {
    postcss([ plugin(opts) ]).process(input).then(function (result) {
        expect(result.css).to.eql(output);
        expect(result.warnings()).to.be.empty;
        done();
    }).catch(function (error) {
        done(error);
    });
};

describe('postcss-position-alt', function () {

    it('test position absolute', function (done) {
      test('a{ absolute: top 10px left 20px right 30px bottom 40px; }',
           'a{ position: absolute; bottom: 40px; right: 30px; left: 20px; top: 10px; }', { }, done);
    });

    it('test position absolute no value', function (done) {
      test('a{ absolute: top left; }',
           'a{ position: absolute; left: 0; top: 0; }', { }, done);
    });

    it('test position fixed', function (done) {
      test('a{ fixed: bottom 10% right 4em; }',
           'a{ position: fixed; right: 4em; bottom: 10%; }', { }, done);
    });

    it('test auto and inherit value', function (done) {
      test('a{ fixed: bottom auto right inherit left; }',
           'a{ position: fixed; left: 0; right: inherit; bottom: auto; }', { }, done);
    });

    it('test relative', function (done) {
      test('a{ relative: top -1px; }',
           'a{ position: relative; top: -1px; }', { }, done);
    });

});
<|endoftext|>


<commit_before>// This shouldn't be hard coded, but there are limitations to the google spreadsheet api
var readableString = {
    "mycurrentskintemperature": "My Current Skin Temperature",
    "howmanyhoursofsleepdidyouhavelastnight": "How many hours of sleep did you have last night?",
    "didyoueatbreakfastthismorning": "Did you eat breakfast this morning?",
    "iam": "Birth Sex"
}

function addSelectBox(parentId, opts, elemId, selectedVal, label) {
    var parent = document.getElementById(parentId);
    var selectElement = document.createElement("select");
    selectElement.setAttribute("id", elemId);
    for (var i = 0; i < opts.length; i++) {
        var option = new Option(readableString[opts[i]], opts[i])
        selectElement.options[selectElement.options.length] = option;
    }
    var labelElem = document.createElement("label");
    labelElem.setAttribute("for", elemId);
    labelElem.innerHTML = label
    selectElement.value = selectedVal
    parent.appendChild(labelElem);
    parent.appendChild(selectElement);
    if (parseInt(d3.select('#wrapper').style('width'),10) < 800) {
      parent.appendChild(document.createElement("br"));
    }
}

var removeKeys = ["rowNumber", "iunderstandthattheinformationisubmitwillbeavailabletothegeneralpublic.", "timestamp"]
   var margin = {
        top: 40,
        right: 20,
        bottom: 40,
        left: 40
    }

// so long, so messy
function showInfo(gData, tableTop, xKey, yKey) {
    //width = 400 - margin.left - margin.right,
    width = parseInt(d3.select('#hdScatter').style('width'),10) - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom,
    padding = 1,
    radius = 6;

    xKey = xKey || "didyoueatbreakfastthismorning";
    yKey = yKey || "mycurrentskintemperature";
    // make the table
    tableOptions = {
        "data": gData,
        "tableDiv": "#healthDataTable"
    }
    Sheetsee.makeTable(tableOptions)
    Sheetsee.initiateTableFilter(tableOptions)

    // create the scatterplot categories
    var categories = {}
    var counts = {}
    var keys = Object.keys(gData[0])
    removeKeys.forEach(function(rm) {
        var rmIdx = keys.indexOf(rm)
        keys.splice(rmIdx, 1)
    });
    keys.forEach(function(key) {
        categories[key] = []
        counts[key] = []
    });

    // setup x - did you eat breakfast this morning
    var xValue = function(d) {
            return d[xKey];
        }, // data -> value
        xScale = d3.scale.ordinal().rangePoints([0, width - 5], 1), // value -> display
        xMap = function(d) {
            return xScale(xValue(d));
        }, // data -> display
        xAxis = d3.svg.axis().scale(xScale).orient("bottom");

    // setup y - my current skin temperature
    //var yKey = "howmanyhoursofsleepdidyouhavelastnight";
    var yValue = function(d) {
            return d[yKey]
        }, // data -> value
        yScale = d3.scale.ordinal().rangePoints([0, height - 5], 1), // value -> display
        yMap = function(d) {
            return yScale(yValue(d));
        }, // data -> display
        yAxis = d3.svg.axis().scale(yScale).orient("left");
    // setup fill color - Sex
    var cValue = function(d) {
            return d.iam;
        },
        color = d3.scale.category10();
    var force = d3.layout.force()
        .nodes(gData)
        .size([width, height])
        .on("tick", tick)
        .charge(-1)
        .gravity(0)
        .chargeDistance(20);
    // add a selectbox for the xAxis key
    addSelectBox("hdControls", keys, "xAxisSelect", xKey, "X Axis:");
    addSelectBox("hdControls", keys, "yAxisSelect", yKey, "Y Axis:");
    document.getElementById("xAxisSelect").addEventListener("change", changeAxis);
    document.getElementById("yAxisSelect").addEventListener("change", changeAxis);

    function changeAxis(t) {
        var xSelect = document.getElementById("xAxisSelect");
        var xNKey = xSelect[xSelect.selectedIndex].value;
        var ySelect = document.getElementById("yAxisSelect");
        var yNKey = ySelect[ySelect.selectedIndex].value;
        updateInfo(gData, tableTop, categories[xNKey], categories[yNKey], xNKey, yNKey)
    }

    // add the graph canvas to the body of the webpage
    var svg = d3.select("#hdScatter").append("svg")
	.attr("preserveAspectRatio", "xMinYMin meet")
        .attr("class", "scatter")
        .attr("id", "scatter")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    // add the tooltip area to the webpage
    var tooltip = d3.select("#hdScatter").append("div")
        .attr("class", "tooltip")
        .style("opacity", 0);

    gData.forEach(function(d) {
        keys.forEach(function(key) {
            if (d.hasOwnProperty(key)) {
                if (!categories[key].includes(d[key])) {
                    categories[key].push(d[key])
                }
                if (!counts[key].hasOwnProperty(d[key])) {
                    counts[key][d[key]] = 1
                } else {
                    counts[key][d[key]] += 1
                }
            }
			if (key == "howmanyhoursofsleepdidyouhavelastnight") {
				catSort = categories[key].sort()
				categories[key] = catSort;
			}
        });
    });
    yScale.domain(categories[yKey])
    xScale.domain(categories[xKey])

    // x-axis
    svg.append("g")
        .attr("class", "xAxis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
        .append("text")
        .attr("class", "xAxisLabel")
        .attr("x", width)
        .attr("y", -6)
        .style("text-anchor", "end")
        .text("Did you eat breakfast this morning?");

    // y-axis
    svg.append("g")
        .attr("class", "yAxis")
        .call(yAxis)
        .selectAll("text")
        .attr("transform", "rotate(90)")
        .attr("dx", 10)
        .attr("y", 20)
        .style("text-anchor", "middle")

    svg.select(".yAxis")
        .append("text")
        .attr("transform", "rotate(90)")
        .attr("class", "yAxisLabel")
        .attr("y", -10)
        .style("text-anchor", "start")
        .text(readableString[yKey])

    // draw dots
    var node = svg.selectAll(".dot")
        .data(gData)
        .enter().append("circle")
        .attr("class", "dot")
        .attr("r", radius)
        .attr("cx", xMap)
        .attr("cy", yMap)
        .style("fill", function(d) {
            return color(cValue(d));
        })
        .on("mouseover", function(d) {
            tooltip.transition()
                .duration(200)
                .style("opacity", .9);
            tooltip.html(d.iam + "
 (" + d[xKey] +
                    " - " + counts[xKey][d[xKey]] + ")
" +
                    "(" + d[yKey] + " - " + counts[yKey][d[yKey]] + ")")
                .style("left", (d3.event.pageX + 5) + "px")
                .style("top", (d3.event.pageY - 28) + "px");
        })
        .on("mouseout", function(d) {
            tooltip.transition()
                .duration(500)
                .style("opacity", 0);
        });

    // draw legend
    var legend = svg.selectAll(".legend")
        .data(color.domain())
        .enter().append("g")
        .attr("class", "legend")
        .attr("transform", function(d, i) {
            return "translate(0," + i * 20 + ")";
        });

    // draw legend colored rectangles
    legend.append("rect")
        .attr("x", width - 18)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill", color);

    // draw legend text
    legend.append("text")
        .attr("x", width - 24)
        .attr("y", 9)
        .attr("dy", ".35em")
        .style("text-anchor", "end")
        .text(function(d) {
            return d;
        })

    force.start()
    gData.forEach(function(d) {
        d.x = xScale(d[xKey]);
        d.y = yScale(d[yKey]);
        d.color = color(d.iam);
        d.radius = radius;
    });

    function tick(e) {
        node.each(moveTowardDataPosition(e.alpha));

        node.each(collide(e.alpha));

        node.attr("cx", function(d) {
                return d.x;
            })
            .attr("cy", function(d) {
                return d.y;
            });
    }

    function moveTowardDataPosition(alpha) {
        return function(d) {
            d.x += (xScale(d[xKey]) - d.x) * 0.1 * alpha;
            d.y += (yScale(d[yKey]) - d.y) * 0.1 * alpha;
        };
    }

    // Resolve collisions between nodes.
    function collide(alpha) {
        var quadtree = d3.geom.quadtree(gData);
        return function(d) {
            var r = d.radius + radius + padding,
                nx1 = d.x - r,
                nx2 = d.x + r,
                ny1 = d.y - r,
                ny2 = d.y + r;
            quadtree.visit(function(quad, x1, y1, x2, y2) {
                if (quad.point && (quad.point !== d)) {
                    var x = d.x - quad.point.x,
                        y = d.y - quad.point.y,
                        l = Math.sqrt(x * x + y * y),
                        r = d.radius + quad.point.radius + (d.color !== quad.point.color) * padding;
                    if (l < r) {
                        l = (l - r) / l * alpha;
                        d.x -= x *= l;
                        d.y -= y *= l;
                        quad.point.x += x;
                        quad.point.y += y;
                    }
                }
                return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
            });
        };
    }
} // end showInfo

function updateInfo(gData, tableTop, xDomain, yDomain, xKey, yKey) {

    var width = parseInt(d3.select('#hdScatter').style('width'),10) - margin.left - margin.right,
    	height = parseInt(d3.select('#hdScatter').style('height'),10) - margin.left - margin.right;
    var xValue = function(d) {
            return d[xKey];
        },
        xScale = d3.scale.ordinal().rangePoints([0, width - 5], 1),
        xMap = function(d) {
            return xScale(xValue(d));
        },
        xAxis = d3.svg.axis().scale(xScale).orient("bottom");

    var yValue = function(d) {
            return d[yKey]
        },
        yScale = d3.scale.ordinal().rangePoints([0, height - 5], 1),
        yMap = function(d) {
            return yScale(yValue(d));
        },
        yAxis = d3.svg.axis().scale(yScale).orient("left");

    var force = d3.layout.force()
        .nodes(gData)
        .size([width, height])
        .on("tick", tick)
        .charge(-1)
        .gravity(0)
        .chargeDistance(20);

    // setup fill color - Sex
    var cValue = function(d) {
            return d.iam;
        },
        color = d3.scale.category10();

    xScale.domain(xDomain)
    yScale.domain(yDomain)

    var svg = d3.select("#hdScatter").transition();

    svg.select(".yAxis")
        .duration(750)
        .call(yAxis)
        .selectAll("text")
        .attr("transform", "rotate(90)")
        .attr("dx", 10)
        .attr("y", 20)
        .style("text-anchor", "middle")

    svg.select(".yAxisLabel")
        .attr("transform", "rotate(90)")
        .attr("y", -10)
        .style("text-anchor", "start")
        .text(readableString[yKey])

    svg.select(".xAxis")
        .duration(750)
        .call(xAxis)

    svg.select(".xAxisLabel")
        .attr("x", width)
        .attr("y", -6)
        .style("text-anchor", "end")
        .text(readableString[xKey]);

    var node = d3.selectAll(".dot")
        .data(gData);

    force.start();

    function tick(e) {
        node.each(moveTowardDataPosition(e.alpha));

        node.each(collide(e.alpha));

        node.attr("cx", function(d) {
                return d.x;
            })
            .attr("cy", function(d) {
                return d.y;
            });
    }

    function moveTowardDataPosition(alpha) {
        return function(d) {
            d.x += (xScale(d[xKey]) - d.x) * 0.1 * alpha;
            d.y += (yScale(d[yKey]) - d.y) * 0.1 * alpha;
        };
    }

    // Resolve collisions between nodes.
    function collide(alpha) {
        var quadtree = d3.geom.quadtree(gData);
        return function(d) {
            var r = d.radius + radius + padding,
                nx1 = d.x - r,
                nx2 = d.x + r,
                ny1 = d.y - r,
                ny2 = d.y + r;
            quadtree.visit(function(quad, x1, y1, x2, y2) {
                if (quad.point && (quad.point !== d)) {
                    var x = d.x - quad.point.x,
                        y = d.y - quad.point.y,
                        l = Math.sqrt(x * x + y * y),
                        r = d.radius + quad.point.radius + (d.color !== quad.point.color) * padding;
                    if (l < r) {
                        l = (l - r) / l * alpha;
                        d.x -= x *= l;
                        d.y -= y *= l;
                        quad.point.x += x;
                        quad.point.y += y;
                    }
                }
                return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
            });
        };
    }

}
<commit_msg>hard coding category order.<commit_after>// This shouldn't be hard coded, but there are limitations to the google spreadsheet api
var readableString = {
    "mycurrentskintemperature": "My Current Skin Temperature",
    "howmanyhoursofsleepdidyouhavelastnight": "How many hours of sleep did you have last night?",
    "didyoueatbreakfastthismorning": "Did you eat breakfast this morning?",
    "iam": "Birth Sex"
}

function addSelectBox(parentId, opts, elemId, selectedVal, label) {
    var parent = document.getElementById(parentId);
    var selectElement = document.createElement("select");
    selectElement.setAttribute("id", elemId);
    for (var i = 0; i < opts.length; i++) {
        var option = new Option(readableString[opts[i]], opts[i])
        selectElement.options[selectElement.options.length] = option;
    }
    var labelElem = document.createElement("label");
    labelElem.setAttribute("for", elemId);
    labelElem.innerHTML = label
    selectElement.value = selectedVal
    parent.appendChild(labelElem);
    parent.appendChild(selectElement);
    if (parseInt(d3.select('#wrapper').style('width'),10) < 800) {
      parent.appendChild(document.createElement("br"));
    }
}

var removeKeys = ["rowNumber", "iunderstandthattheinformationisubmitwillbeavailabletothegeneralpublic.", "timestamp"]
   var margin = {
        top: 40,
        right: 20,
        bottom: 40,
        left: 40
    }

// so long, so messy
function showInfo(gData, tableTop, xKey, yKey) {
    //width = 400 - margin.left - margin.right,
    width = parseInt(d3.select('#hdScatter').style('width'),10) - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom,
    padding = 1,
    radius = 6;

    xKey = xKey || "didyoueatbreakfastthismorning";
    yKey = yKey || "mycurrentskintemperature";
    // make the table
    tableOptions = {
        "data": gData,
        "tableDiv": "#healthDataTable"
    }
    Sheetsee.makeTable(tableOptions)
    Sheetsee.initiateTableFilter(tableOptions)

    // create the scatterplot categories
    var categories = {}
    var counts = {}
    var keys = Object.keys(gData[0])
    removeKeys.forEach(function(rm) {
        var rmIdx = keys.indexOf(rm)
        keys.splice(rmIdx, 1)
    });
    keys.forEach(function(key) {
        categories[key] = []
        counts[key] = []
    });

    // setup x - did you eat breakfast this morning
    var xValue = function(d) {
            return d[xKey];
        }, // data -> value
        xScale = d3.scale.ordinal().rangePoints([0, width - 5], 1), // value -> display
        xMap = function(d) {
            return xScale(xValue(d));
        }, // data -> display
        xAxis = d3.svg.axis().scale(xScale).orient("bottom");

    // setup y - my current skin temperature
    //var yKey = "howmanyhoursofsleepdidyouhavelastnight";
    var yValue = function(d) {
            return d[yKey]
        }, // data -> value
        yScale = d3.scale.ordinal().rangePoints([0, height - 5], 1), // value -> display
        yMap = function(d) {
            return yScale(yValue(d));
        }, // data -> display
        yAxis = d3.svg.axis().scale(yScale).orient("left");
    // setup fill color - Sex
    var cValue = function(d) {
            return d.iam;
        },
        color = d3.scale.category10();
    var force = d3.layout.force()
        .nodes(gData)
        .size([width, height])
        .on("tick", tick)
        .charge(-1)
        .gravity(0)
        .chargeDistance(20);
    // add a selectbox for the xAxis key
    addSelectBox("hdControls", keys, "xAxisSelect", xKey, "X Axis:");
    addSelectBox("hdControls", keys, "yAxisSelect", yKey, "Y Axis:");
    document.getElementById("xAxisSelect").addEventListener("change", changeAxis);
    document.getElementById("yAxisSelect").addEventListener("change", changeAxis);

    function changeAxis(t) {
        var xSelect = document.getElementById("xAxisSelect");
        var xNKey = xSelect[xSelect.selectedIndex].value;
        var ySelect = document.getElementById("yAxisSelect");
        var yNKey = ySelect[ySelect.selectedIndex].value;
        updateInfo(gData, tableTop, categories[xNKey], categories[yNKey], xNKey, yNKey)
    }

    // add the graph canvas to the body of the webpage
    var svg = d3.select("#hdScatter").append("svg")
	.attr("preserveAspectRatio", "xMinYMin meet")
        .attr("class", "scatter")
        .attr("id", "scatter")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    // add the tooltip area to the webpage
    var tooltip = d3.select("#hdScatter").append("div")
        .attr("class", "tooltip")
        .style("opacity", 0);

    gData.forEach(function(d) {
        keys.forEach(function(key) {
            if (d.hasOwnProperty(key)) {
                if (!categories[key].includes(d[key])) {
                    categories[key].push(d[key])
                }
                if (!counts[key].hasOwnProperty(d[key])) {
                    counts[key][d[key]] = 1
                } else {
                    counts[key][d[key]] += 1
                }
            }
			if (key == "howmanyhoursofsleepdidyouhavelastnight") {
				catSort = categories[key].sort()
				categories[key] = catSort;
			}
			if (key == "didyoueatbreakfastthismorning") {
				categories[key] = ["Yes", "No"]
        });
    });
    yScale.domain(categories[yKey])
    xScale.domain(categories[xKey])

    // x-axis
    svg.append("g")
        .attr("class", "xAxis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
        .append("text")
        .attr("class", "xAxisLabel")
        .attr("x", width)
        .attr("y", -6)
        .style("text-anchor", "end")
        .text("Did you eat breakfast this morning?");

    // y-axis
    svg.append("g")
        .attr("class", "yAxis")
        .call(yAxis)
        .selectAll("text")
        .attr("transform", "rotate(90)")
        .attr("dx", 10)
        .attr("y", 20)
        .style("text-anchor", "middle")

    svg.select(".yAxis")
        .append("text")
        .attr("transform", "rotate(90)")
        .attr("class", "yAxisLabel")
        .attr("y", -10)
        .style("text-anchor", "start")
        .text(readableString[yKey])

    // draw dots
    var node = svg.selectAll(".dot")
        .data(gData)
        .enter().append("circle")
        .attr("class", "dot")
        .attr("r", radius)
        .attr("cx", xMap)
        .attr("cy", yMap)
        .style("fill", function(d) {
            return color(cValue(d));
        })
        .on("mouseover", function(d) {
            tooltip.transition()
                .duration(200)
                .style("opacity", .9);
            tooltip.html(d.iam + "
 (" + d[xKey] +
                    " - " + counts[xKey][d[xKey]] + ")
" +
                    "(" + d[yKey] + " - " + counts[yKey][d[yKey]] + ")")
                .style("left", (d3.event.pageX + 5) + "px")
                .style("top", (d3.event.pageY - 28) + "px");
        })
        .on("mouseout", function(d) {
            tooltip.transition()
                .duration(500)
                .style("opacity", 0);
        });

    // draw legend
    var legend = svg.selectAll(".legend")
        .data(color.domain())
        .enter().append("g")
        .attr("class", "legend")
        .attr("transform", function(d, i) {
            return "translate(0," + i * 20 + ")";
        });

    // draw legend colored rectangles
    legend.append("rect")
        .attr("x", width - 18)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill", color);

    // draw legend text
    legend.append("text")
        .attr("x", width - 24)
        .attr("y", 9)
        .attr("dy", ".35em")
        .style("text-anchor", "end")
        .text(function(d) {
            return d;
        })

    force.start()
    gData.forEach(function(d) {
        d.x = xScale(d[xKey]);
        d.y = yScale(d[yKey]);
        d.color = color(d.iam);
        d.radius = radius;
    });

    function tick(e) {
        node.each(moveTowardDataPosition(e.alpha));

        node.each(collide(e.alpha));

        node.attr("cx", function(d) {
                return d.x;
            })
            .attr("cy", function(d) {
                return d.y;
            });
    }

    function moveTowardDataPosition(alpha) {
        return function(d) {
            d.x += (xScale(d[xKey]) - d.x) * 0.1 * alpha;
            d.y += (yScale(d[yKey]) - d.y) * 0.1 * alpha;
        };
    }

    // Resolve collisions between nodes.
    function collide(alpha) {
        var quadtree = d3.geom.quadtree(gData);
        return function(d) {
            var r = d.radius + radius + padding,
                nx1 = d.x - r,
                nx2 = d.x + r,
                ny1 = d.y - r,
                ny2 = d.y + r;
            quadtree.visit(function(quad, x1, y1, x2, y2) {
                if (quad.point && (quad.point !== d)) {
                    var x = d.x - quad.point.x,
                        y = d.y - quad.point.y,
                        l = Math.sqrt(x * x + y * y),
                        r = d.radius + quad.point.radius + (d.color !== quad.point.color) * padding;
                    if (l < r) {
                        l = (l - r) / l * alpha;
                        d.x -= x *= l;
                        d.y -= y *= l;
                        quad.point.x += x;
                        quad.point.y += y;
                    }
                }
                return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
            });
        };
    }
} // end showInfo

function updateInfo(gData, tableTop, xDomain, yDomain, xKey, yKey) {

    var width = parseInt(d3.select('#hdScatter').style('width'),10) - margin.left - margin.right,
    	height = parseInt(d3.select('#hdScatter').style('height'),10) - margin.left - margin.right;
    var xValue = function(d) {
            return d[xKey];
        },
        xScale = d3.scale.ordinal().rangePoints([0, width - 5], 1),
        xMap = function(d) {
            return xScale(xValue(d));
        },
        xAxis = d3.svg.axis().scale(xScale).orient("bottom");

    var yValue = function(d) {
            return d[yKey]
        },
        yScale = d3.scale.ordinal().rangePoints([0, height - 5], 1),
        yMap = function(d) {
            return yScale(yValue(d));
        },
        yAxis = d3.svg.axis().scale(yScale).orient("left");

    var force = d3.layout.force()
        .nodes(gData)
        .size([width, height])
        .on("tick", tick)
        .charge(-1)
        .gravity(0)
        .chargeDistance(20);

    // setup fill color - Sex
    var cValue = function(d) {
            return d.iam;
        },
        color = d3.scale.category10();

    xScale.domain(xDomain)
    yScale.domain(yDomain)

    var svg = d3.select("#hdScatter").transition();

    svg.select(".yAxis")
        .duration(750)
        .call(yAxis)
        .selectAll("text")
        .attr("transform", "rotate(90)")
        .attr("dx", 10)
        .attr("y", 20)
        .style("text-anchor", "middle")

    svg.select(".yAxisLabel")
        .attr("transform", "rotate(90)")
        .attr("y", -10)
        .style("text-anchor", "start")
        .text(readableString[yKey])

    svg.select(".xAxis")
        .duration(750)
        .call(xAxis)

    svg.select(".xAxisLabel")
        .attr("x", width)
        .attr("y", -6)
        .style("text-anchor", "end")
        .text(readableString[xKey]);

    var node = d3.selectAll(".dot")
        .data(gData);

    force.start();

    function tick(e) {
        node.each(moveTowardDataPosition(e.alpha));

        node.each(collide(e.alpha));

        node.attr("cx", function(d) {
                return d.x;
            })
            .attr("cy", function(d) {
                return d.y;
            });
    }

    function moveTowardDataPosition(alpha) {
        return function(d) {
            d.x += (xScale(d[xKey]) - d.x) * 0.1 * alpha;
            d.y += (yScale(d[yKey]) - d.y) * 0.1 * alpha;
        };
    }

    // Resolve collisions between nodes.
    function collide(alpha) {
        var quadtree = d3.geom.quadtree(gData);
        return function(d) {
            var r = d.radius + radius + padding,
                nx1 = d.x - r,
                nx2 = d.x + r,
                ny1 = d.y - r,
                ny2 = d.y + r;
            quadtree.visit(function(quad, x1, y1, x2, y2) {
                if (quad.point && (quad.point !== d)) {
                    var x = d.x - quad.point.x,
                        y = d.y - quad.point.y,
                        l = Math.sqrt(x * x + y * y),
                        r = d.radius + quad.point.radius + (d.color !== quad.point.color) * padding;
                    if (l < r) {
                        l = (l - r) / l * alpha;
                        d.x -= x *= l;
                        d.y -= y *= l;
                        quad.point.x += x;
                        quad.point.y += y;
                    }
                }
                return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
            });
        };
    }

}
<|endoftext|>


<commit_before>var Manager = require('../');
var expect = require('expect.js');

describe('inter-tab', function(){

  it('should run simple test', function(){
    // var test = new Manager();
    expect(1).to.be(1);
  });

});
<commit_msg>Add simple test case for tabId<commit_after>var Manager = require('../');
var expect = require('expect.js');

describe('inter-tab', function(){
    it('should create tab id', function(){
        var tab = new Manager();
        expect(tab.id).to.be.a('number');
        tab.destroy();
    });
});
<|endoftext|>


<commit_before>'use strict';

moj.Modules.checkEmail = {
  container: 'verify-password-form',
  input_id: 'user_email',
  confirmation_panel_class: 'email-confirmation',

  init: function() {
    var self = this,
        $emailField = $('.' + self.container).find('#' + self.input_id);

    if($emailField.length) {
      self.$emailField = $emailField;
      self.bindEvents();
    }
  },

  bindEvents: function() {
    var self = this;

    self.$emailField.on('keyup', function() {
      self.checkValue();
    });
  },

  checkValue: function() {
    var self = this,
        val = self.$emailField.val(),
        length = val.length;

    if(length) {
      self.showConfirmation(val);
    } else {
      self.hideConfirmation();
    }
  },

  showConfirmation: function(val) {
    var self = this;

    if(!$('.' + self.confirmation_panel_class).length) {
      self.createConfirmationPanel();
    }
    $('.' + self.confirmation_panel_class).removeClass('js-hidden');
    $('.' + self.confirmation_panel_class).find('strong').text(val);
    self.$emailField.closest('.form-group').addClass('tight');
  },

  createConfirmationPanel: function() {
    var self = this;

    self.$emailField.closest('.form-group').after('

' + moj.Modules.emailConfirmationText + '

');
  },

  hideConfirmation: function() {
    var self = this;

    self.$emailField.closest('.form-group').removeClass('tight');
    $('.' + self.confirmation_panel_class).addClass('js-hidden');
  }
};
<commit_msg>update visual email confirmation on more events (#473)<commit_after>'use strict';

moj.Modules.checkEmail = {
  container: 'verify-password-form',
  input_id: 'user_email',
  confirmation_panel_class: 'email-confirmation',

  init: function() {
    var self = this,
        $emailField = $('.' + self.container).find('#' + self.input_id);

    if($emailField.length) {
      self.$emailField = $emailField;
      self.bindEvents();
    }
  },

  bindEvents: function() {
    var self = this;

    self.$emailField.on('keyup change focus blur', function() {
      self.checkValue();
    });
  },

  checkValue: function() {
    var self = this,
        val = self.$emailField.val(),
        length = val.length;

    if(length) {
      self.showConfirmation(val);
    } else {
      self.hideConfirmation();
    }
  },

  showConfirmation: function(val) {
    var self = this;

    if(!$('.' + self.confirmation_panel_class).length) {
      self.createConfirmationPanel();
    }
    $('.' + self.confirmation_panel_class).removeClass('js-hidden');
    $('.' + self.confirmation_panel_class).find('strong').text(val);
    self.$emailField.closest('.form-group').addClass('tight');
  },

  createConfirmationPanel: function() {
    var self = this;

    self.$emailField.closest('.form-group').after('

' + moj.Modules.emailConfirmationText + '

');
  },

  hideConfirmation: function() {
    var self = this;

    self.$emailField.closest('.form-group').removeClass('tight');
    $('.' + self.confirmation_panel_class).addClass('js-hidden');
  }
};
<|endoftext|>


<commit_before>var CloudCommander, CloudFunc, $;
/* object contains viewer FancyBox
 * https://github.com/fancyapps/fancyBox
 */
CloudCommander.Viewer = {getByClass  : function(pClass){
        return document.getElementsByClassName(pClass);
    }};
CloudCommander.Viewer.FancyBox = {
    /* function return configureation
     * for FancyBox open and
     * onclick (it shoud be
     * different objects)
     */
    getConfig: (function(){
        return{
            beforeShow : (function(){
            CloudCommander.keyBinded = false;
            }),
            beforeClose: (function(){
                CloudCommander.keyBinded = true;
            }),

            openEffect    : 'none',
            closeEffect	: 'none',

            helpers : {
                overlay : {
                    opacity: 0.1,
                    css : {
                        'background-color' : '#fff'
                    }
                }
            },
            padding : 0
        };
    }),
    load: function(){
        var ljsLoad_f = function(){
                CloudCommander.jsload(
                    'http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js');
        };

        CloudCommander.cssLoad({
            src  : 'http://fancyapps.com/fancybox/source/jquery.fancybox.css',
            func : ljsLoad_f
        });
    },
    set: function(){
        if(this.getByClass('fancybox').length)
            return;
        try{
            /* get current panel (left or right) */
            var lPanel = this.getByClass('current-file');

            lPanel.length &&
                (lPanel = lPanel[0].parentElement);

            /* get all file links */
            var lA = lPanel.getElementsByTagName('a');

            var lName;
            /* first two is not files nor folders*/
            for (var i=2; i < lA.length; i++) {
                lName = lA[i].title || lA[i].textContent;

                CloudFunc.checkExtension(lName,['png','jpg']) &&
                    (lA[i].className    = 'fancybox') &&
                    (lA[i].rel          = 'gallery');
            }

            $('.fancybox').fancybox(this.getConfig());
        }catch(pError){
            console.log(pError);
        }
    },
    getById     : function(pId){return document.getElementById(pId);},
    getByClass  : function(pClass){
        return document.getElementsByClassName(pClass);
    }
};
CloudCommander.Viewer.Keys = (function(){
    "use strict";

    CloudCommander.Viewer.FancyBox.load();

    var key_event = function(pParent){
        return function(event){
            /* если клавиши можно обрабатывать */
            if(CloudCommander.keyBinded){
                /* if f3 pressed */
                if(event.keyCode===114){
                    CloudCommander.Viewer.FancyBox.set();
                    var lCurrent = pParent.getByClass('current-file');
                          lCurrent.length &&
                            (lCurrent = lCurrent[0]);

                    var lA = lCurrent.getElementsByClassName('fancybox');

                    var lConfig = pParent.FancyBox.getConfig();

                    lA.length &&
                        $.fancybox.open({ href : lA[0].href },
                            lConfig);

                event.preventDefault();
                }
            }
        };
    };

    /* добавляем обработчик клавишь */
    if (document.addEventListener)
        document.addEventListener('keydown', key_event(this),false);

    else
        document.onkeypress=key_event;
});<commit_msg>added copy of fancybox for offline mode<commit_after>var CloudCommander, CloudFunc, $;
/* object contains viewer FancyBox
 * https://github.com/fancyapps/fancyBox
 */
CloudCommander.Viewer = {
    dir : CloudCommander.LIBDIRCLIENT + 'viewer/',

    getByClass  : function(pClass){
        return document.getElementsByClassName(pClass);
    }
};
CloudCommander.Viewer.FancyBox = {
    dir     : CloudCommander.Viewer.dir + 'fancybox/',
    /* function return configureation
     * for FancyBox open and
     * onclick (it shoud be
     * different objects)
     */
    getConfig: (function(){
        return{
            beforeShow : (function(){
            CloudCommander.keyBinded = false;
            }),
            beforeClose: (function(){
                CloudCommander.keyBinded = true;
            }),

            openEffect    : 'none',
            closeEffect	: 'none',

            helpers : {
                overlay : {
                    opacity: 0.1,
                    css : {
                        'background-color' : '#fff'
                    }
                }
            },
            padding : 0
        };
    }),
    load: function(){
        var ljsLoad_f = function(){
            CloudCommander.jsload(
                'http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js',{
                    onerror: (function(){
                        CloudCommander.jsload(this.dir +
                            'jquery.fancybox.pack.js');
                    })
            });
        };

        CloudCommander.cssLoad({
            src  : 'http://fancyapps.com/fancybox/source/jquery.fancybox.css',
            func : {
                onload: ljsLoad_f,
                onerror: (function(){
                        CloudCommander.cssLoad({
                            src  : this.dir +'jquery.fancybox.css',
                            func : ljsLoad_f
                        });
                })
            }
        });
    },

    set: function(){
        if(this.getByClass('fancybox').length)
            return;
        try{
            /* get current panel (left or right) */
            var lPanel = this.getByClass('current-file');

            lPanel.length &&
                (lPanel = lPanel[0].parentElement);

            /* get all file links */
            var lA = lPanel.getElementsByTagName('a');

            var lName;
            /* first two is not files nor folders*/
            for (var i=2; i < lA.length; i++) {
                lName = lA[i].title || lA[i].textContent;

                CloudFunc.checkExtension(lName,['png','jpg']) &&
                    (lA[i].className    = 'fancybox') &&
                    (lA[i].rel          = 'gallery');
            }

            $('.fancybox').fancybox(this.getConfig());
        }catch(pError){
            console.log(pError);
        }
    },
    getById     : function(pId){return document.getElementById(pId);},
    getByClass  : function(pClass){
        return document.getElementsByClassName(pClass);
    }
};
CloudCommander.Viewer.Keys = (function(){
    "use strict";

    CloudCommander.Viewer.FancyBox.load();

    var key_event = function(pParent){
        return function(event){
            /* если клавиши можно обрабатывать */
            if(CloudCommander.keyBinded){
                /* if f3 pressed */
                if(event.keyCode===114){
                    CloudCommander.Viewer.FancyBox.set();
                    var lCurrent = pParent.getByClass('current-file');
                          lCurrent.length &&
                            (lCurrent = lCurrent[0]);

                    var lA = lCurrent.getElementsByClassName('fancybox');

                    var lConfig = pParent.FancyBox.getConfig();

                    lA.length &&
                        $.fancybox.open({ href : lA[0].href },
                            lConfig);

                event.preventDefault();
                }
            }
        };
    };

    /* добавляем обработчик клавишь */
    if (document.addEventListener)
        document.addEventListener('keydown', key_event(this),false);

    else
        document.onkeypress=key_event;
});<|endoftext|>


<commit_before>var nombre;

nombre = prompt ("ingresa tu nombre");

if (nombre == "bikoda") {
	alert("Buenos dias Bikoda");
} else if (nombre == "benja"){
	alert("Hola Gordon!");
} else if (nombre == "ciro"){
	alert("sup nebu"); {
} else {
	document.write ("bienvenidos a Bikoda")
}
<commit_msg>Update javascript.js<commit_after>var nombre;

nombre = prompt ("ingresa tu nombre");

if (nombre == "bikoda") {
	alert("Buenos dias Bikoda");
} else if (nombre == "benja"){
	alert("Hola Gordon!");
} else if (nombre == "ciro"){
	alert("sup nebu"); {
} else {
	alert("bienvenidos a Bikoda");
}
<|endoftext|>


<commit_before>function SpreeDeliveryOptions() {

  var that = this;

  this.initializeDatePicker = function() {
     $('#order_delivery_date').datepicker({dateFormat: "dd/mm/yy"});
  };

  this.initializeDeliveryTimeSelect = function() {
    this.update_delivery_time_options();

    $('#order_delivery_date').change(function(event){
      that.update_delivery_time_options();
    });
  };

  this.update_delivery_time_options = function() {
    delivery_time_options = $.parseJSON($('.delivery-time-options').attr("data"));

    if (delivery_time_options){
      weekdays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
      var dateParts = $('#order_delivery_date').val().split('/')
      day_index = new Date(dateParts[2], dateParts[1]-1, dateParts[0]).getDay();
      weekday = weekdays[day_index];

      day_options = delivery_time_options[weekday];
      this.populate_delivery_time(day_options);
    }
  };

  this.populate_delivery_time = function(options) {
    if (options) {
      var arLen = options.length;
      var newList = "";
      for ( var i=0, len=arLen; i<len; ++i ){
        newList = newList + '<option>' + options[i]+'</option>';
      }
      $('#order_delivery_time').html(newList);
    } else {
      $('#order_delivery_time').html("<option>No deliveries available on this date</option>");
    }
  };

}

$(document).ready(function() {
  var deliveryOptions = new SpreeDeliveryOptions();
  deliveryOptions.initializeDatePicker();
  deliveryOptions.initializeDeliveryTimeSelect();
});
<commit_msg>fixing js in store<commit_after>function SpreeDeliveryOptions() {

  var that = this;

  this.initializeDatePicker = function() {
     $('#order_delivery_date').datepicker({dateFormat: "dd/mm/yy"});
  };

  this.initializeDeliveryTimeSelect = function() {
    this.update_delivery_time_options();

    $('#order_delivery_date').change(function(event){
      that.update_delivery_time_options();
    });
  };

  this.update_delivery_time_options = function() {
    deliveryTimeOptions = $.parseJSON($('.delivery-time-options').attr("data"));

    if (deliveryTimeOptions){
      weekdays = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];

      var dayOptions = [];
      var deliveryDate = $('#order_delivery_date').val();

      if (deliveryTimeOptions[deliveryDate]) {
        dayOptions = deliveryTimeOptions[deliveryDate];
      } else {
        var dateParts = deliveryDate.split('/')
        var dayIndex = new Date(dateParts[2], dateParts[1]-1, dateParts[0]).getDay();
        weekday = weekdays[dayIndex];

        dayOptions = deliveryTimeOptions[weekday];
      }
      this.populate_delivery_time(dayOptions);
    }
  };

  this.populate_delivery_time = function(options) {
    if (options) {
      var arLen = options.length;
      var newList = "";
      for ( var i=0, len=arLen; i<len; ++i ){
        newList = newList + '<option>' + options[i]+'</option>';
      }
      $('#order_delivery_time').html(newList);
    } else {
      $('#order_delivery_time').html("<option>No deliveries available on this date</option>");
    }
  };

}

$(document).ready(function() {
  var deliveryOptions = new SpreeDeliveryOptions();
  deliveryOptions.initializeDatePicker();
  deliveryOptions.initializeDeliveryTimeSelect();
});
<|endoftext|>


<commit_before>var URL = "http://iostream.dk:8888/";

function mkEditor(editorId, buttonId, outputId) {
    var editor = ace.edit(editorId);
    editor.setShowPrintMargin(false);
    editor.renderer.setShowGutter(false);
    editor.renderer.setPadding(20);
    editor.renderer.setScrollMargin(10, 10);
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/scala");

    $("#" + buttonId).click(function () {
        var input = editor.getValue();

        $("#" + outputId).html("Loading...");

        $.ajax({
            url: URL,
            method: "post",
            data: input,
            success: function (output) {
                var json = JSON.parse(output);
                console.log(json);

                if (json.status == "success") {
                    var buffer = "Result: " + json.result + "\n";

                    if (json.relations.length != 0) {
                        buffer += "\nRelations:\n";
                        json.relations.forEach(function (rel) {
                            rel.rows.forEach(function (row) {
                                buffer += "  " + rel.name + "(";
                                buffer += row.join(", ");
                                buffer += ").\n";
                            });
                        });
                    }

                    if (json.lattices.length != 0) {
                        buffer += "\nLattices:\n";
                        json.lattices.forEach(function (lat) {
                            lat.rows.forEach(function (row) {
                                buffer += "  " + lat.name + "(";
                                buffer += row.join(", ");
                                buffer += ").\n";
                            });
                        });
                    }

                    $("#" + outputId).html(buffer);
                } else {
                    $("#" + outputId).html(json.message);
                }
            },
            error: function () {
                $("#" + outputId).html("The server did not respond.");
            }
        });
    });

    return editor;
}
<commit_msg>Added https check.<commit_after>var URL = "http://iostream.dk:8888/";

function mkEditor(editorId, buttonId, outputId) {
    var editor = ace.edit(editorId);
    editor.setShowPrintMargin(false);
    editor.renderer.setShowGutter(false);
    editor.renderer.setPadding(20);
    editor.renderer.setScrollMargin(10, 10);
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/scala");

    $("#" + buttonId).click(function () {
        if (location.protocol == "https:") {
            alert('Unfortunately the code editor does not work over HTTPs.\n\nPlease access the site using HTTP (if you want to try the code editor).');
            return false;
        }

        var input = editor.getValue();

        $("#" + outputId).html("Loading...");

        $.ajax({
            url: URL,
            method: "post",
            data: input,
            success: function (output) {
                var json = JSON.parse(output);
                console.log(json);

                if (json.status == "success") {
                    var buffer = "Result: " + json.result + "\n";

                    if (json.relations.length != 0) {
                        buffer += "\nRelations:\n";
                        json.relations.forEach(function (rel) {
                            rel.rows.forEach(function (row) {
                                buffer += "  " + rel.name + "(";
                                buffer += row.join(", ");
                                buffer += ").\n";
                            });
                        });
                    }

                    if (json.lattices.length != 0) {
                        buffer += "\nLattices:\n";
                        json.lattices.forEach(function (lat) {
                            lat.rows.forEach(function (row) {
                                buffer += "  " + lat.name + "(";
                                buffer += row.join(", ");
                                buffer += ").\n";
                            });
                        });
                    }

                    $("#" + outputId).html(buffer);
                } else {
                    $("#" + outputId).html(json.message);
                }
            },
            error: function () {
                $("#" + outputId).html("The server did not respond.");
            }
        });
    });

    return editor;
}
<|endoftext|>


<commit_before>/**
 * Created with JetBrains PhpStorm.
 * User: Janine Derix
 * Date: 23.04.14
 * Time: 15:22
 * To change this template use File | Settings | File Templates.
 */
function buttonClick(id) {
    var div = document.getElementById(id);

    if(div.className === "desc"){
        for(var i = 1; i <= 9; i++){
            var current = document.getElementById("desc"+i);
            current.className = "desc"
        }
        div.className = "desc active"
    }
    else {
        div.className = "desc"
    }
}
<commit_msg>Update javascript.js<commit_after>function buttonClick(id) {
    var div = document.getElementById(id);

    if(div.className === "desc"){
        for(var i = 1; i <= 9; i++){
            var current = document.getElementById("desc"+i);
            current.className = "desc"
        }
        div.className = "desc active"
    }
    else {
        div.className = "desc"
    }
}
<|endoftext|>


<commit_before>var assert    = require('assert');
var fs        = require('fs');
var postcss   = require('postcss');
var classPrfx = require('..');

function fixture(name) {
  return fs.readFileSync('test/fixtures/' + name, 'utf8').trim();
}

describe('postcss-class-prefix', function() {
  it('prefixes all classes', function() {
    var output = postcss()
                .use(classPrfx('prfx-'))
                .process(fixture('source.css')).css;
    var expected = fixture('source.expected.css');

    assert.equal(output, expected);
  });

  it('ignores a classes given in `ignore`', function() {
    var output = postcss()
              .use(classPrfx('prfx-', { ignore: /^is-/ }))
              .process(fixture('filter.css')).css;
    var expected = fixture('filter.expected.css');

    assert.equal(output, expected);
  });

  it('allows an array of ignores as regex or string', function() {
    var output = postcss()
              .use(classPrfx('prfx-', {
                ignore: [
                  /^s-[a-z-]+/,
                  'no-flexbox',
                  'no-fontface',
                  /^Box[a-zA-Z]/
                  ]
                }))
              .process(fixture('ignore.css')).css;
    var expected = fixture('ignore.expected.css');

    assert.equal(output, expected);
  });
});
<commit_msg>Fix test regex<commit_after>var assert    = require('assert');
var fs        = require('fs');
var postcss   = require('postcss');
var classPrfx = require('..');

function fixture(name) {
  return fs.readFileSync('test/fixtures/' + name, 'utf8').trim();
}

describe('postcss-class-prefix', function() {
  it('prefixes all classes', function() {
    var output = postcss()
                .use(classPrfx('prfx-'))
                .process(fixture('source.css')).css;
    var expected = fixture('source.expected.css');

    assert.equal(output, expected);
  });

  it('ignores a classes given in `ignore`', function() {
    var output = postcss()
              .use(classPrfx('prfx-', { ignore: /^is-/ }))
              .process(fixture('filter.css')).css;
    var expected = fixture('filter.expected.css');

    assert.equal(output, expected);
  });

  it('allows an array of ignores as regex or string', function() {
    var output = postcss()
              .use(classPrfx('prfx-', {
                ignore: [
                  /^s-[a-z-]+/,
                  'no-flexbox',
                  'no-fontface',
                  /^Box[a-zA-Z]+/
                  ]
                }))
              .process(fixture('ignore.css')).css;
    var expected = fixture('ignore.expected.css');

    assert.equal(output, expected);
  });
});
<|endoftext|>


<commit_before>var colors = require('colors');

var _help = function(){
  console.log("");
  console.log("Need some help? Here's a list of all available commands (preceded by `roots`):");
  console.log("");

  process.stdout.write("- ");
  process.stdout.write("new `name`: ".bold);
  process.stdout.write("create a new project structure in the current directory\n- ");

  process.stdout.write("compile: ".bold);
  process.stdout.write("compile, compress, and minify to /public\n- ");

  process.stdout.write("watch: ".bold);
  process.stdout.write("watch your project, compile and reload whenever you save\n- ");

  process.stdout.write("deploy `name`: ".bold);
  process.stdout.write("deploy your project to heroku\n- ");

  process.stdout.write("version: ".bold);
  process.stdout.write("print the version of your current install\n");

  process.stdout.write("\n");
  process.stdout.write("- " + "js list: ".bold + "list the components you have installed");
  process.stdout.write("\n");
  process.stdout.write("- " + "js search `name`: ".bold + "search for a component");
  process.stdout.write("\n");
  process.stdout.write("- " + "js install `name`: ".bold + "install a component");
  process.stdout.write("\n");
  process.stdout.write("- " + "js uninstall `name`: ".bold + "uninstall a component");
  process.stdout.write("\n");
  process.stdout.write("- " + "js update `name`: ".bold + "update a component to the latest version");
  process.stdout.write("\n");
  process.stdout.write("- " + "js info `name`: ".bold + "more info about a component");
  process.stdout.write("\n");

  process.stdout.write("\n");
  process.stdout.write("- " + "plugin generate: ".bold + "generates a roots plugin template");
  process.stdout.write("\n");
  process.stdout.write("- " + "plugin install `username/repo`: ".bold + "installs a plugin from a github repo");
  process.stdout.write("\n");

  console.log("");
  console.log("...and by all means check out " + "http://roots.cx".green + " for more help!");
  console.log("");

};

module.exports = { execute: _help };
<commit_msg>change "js" to "pkg"<commit_after>var colors = require('colors');

var _help = function(){
  console.log("");
  console.log("Need some help? Here's a list of all available commands (preceded by `roots`):");
  console.log("");

  process.stdout.write("- ");
  process.stdout.write("new `name`: ".bold);
  process.stdout.write("create a new project structure in the current directory\n- ");

  process.stdout.write("compile: ".bold);
  process.stdout.write("compile, compress, and minify to /public\n- ");

  process.stdout.write("watch: ".bold);
  process.stdout.write("watch your project, compile and reload whenever you save\n- ");

  process.stdout.write("deploy `name`: ".bold);
  process.stdout.write("deploy your project to heroku\n- ");

  process.stdout.write("version: ".bold);
  process.stdout.write("print the version of your current install\n");

  process.stdout.write("\n");
  process.stdout.write("- " + "pkg list: ".bold + "list the components you have installed");
  process.stdout.write("\n");
  process.stdout.write("- " + "pkg search `name`: ".bold + "search for a component");
  process.stdout.write("\n");
  process.stdout.write("- " + "pkg install `name`: ".bold + "install a component");
  process.stdout.write("\n");
  process.stdout.write("- " + "pkg uninstall `name`: ".bold + "uninstall a component");
  process.stdout.write("\n");
  process.stdout.write("- " + "pkg update `name`: ".bold + "update a component to the latest version");
  process.stdout.write("\n");
  process.stdout.write("- " + "pkg info `name`: ".bold + "more info about a component");
  process.stdout.write("\n");

  process.stdout.write("\n");
  process.stdout.write("- " + "plugin generate: ".bold + "generates a roots plugin template");
  process.stdout.write("\n");
  process.stdout.write("- " + "plugin install `username/repo`: ".bold + "installs a plugin from a github repo");
  process.stdout.write("\n");

  console.log("");
  console.log("...and by all means check out " + "http://roots.cx".green + " for more help!");
  console.log("");

};

module.exports = { execute: _help };
<|endoftext|>


<commit_before>/*!
 * Clean Blog v1.0.0 (http://startbootstrap.com)
 * Copyright 2015 Start Bootstrap
 * Licensed under Apache 2.0 (https://github.com/IronSummitMedia/startbootstrap/blob/gh-pages/LICENSE)
 */

// Tooltip Init
$(function() {
    $("[data-toggle='tooltip']").tooltip();
});

// make all images responsive
/*
 * Unuse by Hux
 * actually only Portfolio-Pages can't use it and only post-img need it.
 * so I modify the _layout/post and CSS to make post-img responsive!
 */
// $(function() {
// 	$("img").addClass("img-responsive");
// });

// responsive tables
// $(document).ready(function() {
// 	$("table").wrap("

");
// 	$("table").addClass("table");
// });

// responsive embed videos
// $(document).ready(function () {
//     $('iframe[src*="youtube.com"]').wrap('

');
// 	$('iframe[src*="youtube.com"]').addClass('embed-responsive-item');
//     $('iframe[src*="vimeo.com"]').wrap('

');
// 	$('iframe[src*="vimeo.com"]').addClass('embed-responsive-item');
// });

// Navigation Scripts to Show Header on Scroll-Up
jQuery(document).ready(function($) {
    var MQL = 1170;

    //primary navigation slide-in effect
    if ($(window).width() > MQL) {
        var headerHeight = $('.navbar-custom').height();
        $(window).on('scroll', {
                previousTop: 0
            },
            function() {
                var currentTop = $(window).scrollTop();
                //check if user is scrolling up
                if (currentTop < this.previousTop) {
                    //if scrolling up...
                    if (currentTop > 0 && $('.navbar-custom').hasClass('is-fixed')) {
                        $('.navbar-custom').addClass('is-visible');
                    } else {
                        $('.navbar-custom').removeClass('is-visible is-fixed');
                    }
                } else {
                    //if scrolling down...
                    $('.navbar-custom').removeClass('is-visible');
                    if (currentTop > headerHeight && !$('.navbar-custom').hasClass('is-fixed')) $('.navbar-custom').addClass('is-fixed');
                }
                this.previousTop = currentTop;
            });
    }
});
<commit_msg>delete js<commit_after>/*!
 * Clean Blog v1.0.0 (http://startbootstrap.com)
 * Copyright 2015 Start Bootstrap
 * Licensed under Apache 2.0 (https://github.com/IronSummitMedia/startbootstrap/blob/gh-pages/LICENSE)
 */

// Tooltip Init
$(function() {
    $("[data-toggle='tooltip']").tooltip();
});

// make all images responsive
/*
 * Unuse by Hux
 * actually only Portfolio-Pages can't use it and only post-img need it.
 * so I modify the _layout/post and CSS to make post-img responsive!
 */
// $(function() {
// 	$("img").addClass("img-responsive");
// });

// responsive tables
// $(document).ready(function() {
// 	$("table").wrap("

");
// 	$("table").addClass("table");
// });

// responsive embed videos
// $(document).ready(function () {
//     $('iframe[src*="youtube.com"]').wrap('

');
// 	$('iframe[src*="youtube.com"]').addClass('embed-responsive-item');
//     $('iframe[src*="vimeo.com"]').wrap('

');
// 	$('iframe[src*="vimeo.com"]').addClass('embed-responsive-item');
// });

// Navigation Scripts to Show Header on Scroll-Up
// jQuery(document).ready(function($) {
//     var MQL = 1170;

//     //primary navigation slide-in effect
//     if ($(window).width() > MQL) {
//         var headerHeight = $('.navbar-custom').height();
//         $(window).on('scroll', {
//                 previousTop: 0
//             },
//             function() {
//                 var currentTop = $(window).scrollTop();
//                 //check if user is scrolling up
//                 if (currentTop < this.previousTop) {
//                     //if scrolling up...
//                     if (currentTop > 0 && $('.navbar-custom').hasClass('is-fixed')) {
//                         $('.navbar-custom').addClass('is-visible');
//                     } else {
//                         $('.navbar-custom').removeClass('is-visible is-fixed');
//                     }
//                 } else {
//                     //if scrolling down...
//                     $('.navbar-custom').removeClass('is-visible');
//                     if (currentTop > headerHeight && !$('.navbar-custom').hasClass('is-fixed')) $('.navbar-custom').addClass('is-fixed');
//                 }
//                 this.previousTop = currentTop;
//             });
//     }
// });
<|endoftext|>


<commit_before>'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
console.log('Building info.js');

exports.name = 'info';

exports.exec = async (msg, {send, reply, channel, guild, client, bot, Discord, member, args}) =>{
  let user = msg.content.split(/\s+/g)

  let id
  if(user[2] != null){
    if(user[2].length == 18)
      id = user[2]
  } else {
  msg.mentions.users.first().id
  }

  let nick = msg.guild.members.get(id).nickname
  if(nick == null) {
  nick = msg.guild.members.get(id).username
  }

  let embed = new Discord.RichEmbed();
  if (msg.content.endsWith(" server"))
  embed.setColor(member&&member.displayColor?member.displayColor:1290103);
  embed.setTitle(`${msg.guild.name}`).setDescription(`Created on ${msg.guild.createdAt}`);
  embed.addField('Owner ',`${msg.guild.owner}`);
  embed.addField('Member Count ', `${msg.guild.memberCount}`);
  embed.addField('Location ',`${msg.guild.region}`);
  embed.addField('Verification Level ',`${msg.guild.verificationLevel}`);
  embed.setThumbnail(`${msg.guild.iconURL}`);
  embed.setFooter(`Guild ID:${msg.guild.id}`);
} else {
  return send("I do not recognize that command.")
}

  embed = new Discord.RichEmbed();
  if (msg.content.endsWith(" user"))
  embed.setColor(member&&member.displayColor?member.displayColor:1290103);
  embed.setTitle(`${msg.guild.members.get(id).username}`).setDescription(nick);
  embed.addField(`Account Creation`,`${msg.guild.members.get(id).createdAt}`);
  embed.addField(`Joined ${msg.guild.name}`,`${msg.guild.members.get(id).joinedAt}`);
  embed.addField(`Highest Role`,`${msg.guild.members.get(id).highestRole}`);
  embed.addField(`Status`, `${msg.guild.members.get(id).presence.status}`);
  embed.addField(`Currently Playing`,`${msg.guild.members.get(id).presence.game.name}`);
  embed.setThumbnail(`${msg.guild.members.get(id).user.avatarURL}`);
} else {
  return send("I do not recognize that command.")
}
  return await send({embed});
};
<commit_msg>No idea if this is going to work but yea<commit_after>'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
console.log('Building info.js');

const _ = require('lodash');

exports.name = 'info';

exports.exec = async (msg, {send, guild, Discord, member, args}) =>{
  let id = member.id;
  if(msg.mentions.users.first())
    id = msg.mentions.users.first().id;
  else if(args[1]){
    for(const [i,m] of guild.members)
      if(
        args[1] === i ||
        new RegExp(_.escapeRegExp(m.user.username),'i').test(args[1]) ||
        new RegExp(_.escapeRegExp(m.user.tag),'i').test(args[1]) ||
        new RegExp(_.escapeRegExp(m.user.displayName),'i').test(args[1])
      ){
        id = i;
        break;
      }
  }
  let targetMember = guild.members.get(id);

  if(!id||!targetMember) return await send('Please ensure you have specified a valid member');

  let targetUser = targetMember.user;
  let nick = targetMember.displayName;

  let embed = new Discord.RichEmbed;

  if (args[0] === "server") {
    embed.setColor(targetMember.displayColor||1290103);
    embed.setTitle(`${guild.name}`).setDescription(`Created on ${guild.createdAt}`);
    embed.addField('Owner ',`${guild.owner}`);
    embed.addField('Member Count ', `${guild.memberCount}`);
    embed.addField('Location ',`${guild.region}`);
    embed.addField('Verification Level ',`${guild.verificationLevel}`);
    embed.setThumbnail(`${guild.iconURL}`);
    embed.setFooter(`Guild ID:${guild.id}`);
  } else if (args[0]==="user") {
    embed.setColor(member&&member.displayColor?member.displayColor:1290103);
    embed.setTitle(`${targetUser.username}`).setDescription(nick);
    embed.addField(`Account Creation`,`${targetUser.createdAt}`);
    embed.addField(`Joined ${guild.name}`,`${targetMember.joinedAt}`);
    embed.addField(`Highest Role`,`${targetMember.highestRole}`);
    embed.addField(`Status`, `${targetUser.presence.status}`);
    embed.addField(`Currently Playing`,`${targetUser.presence.game.name}`);
    embed.setThumbnail(`${targetUser.displayAvatarURL}`);
  } else
    return send("I do not recognize that sub-command.");

  return await send({embed});
};
<|endoftext|>