<commit_before>/* global before, describe, it */
var assert = require('assert')
var rdf = require('../rdf-ext')
var testData = require('rdf-test-data')

module.exports = function (ctx) {
  describe('utils', function () {
    var tbbtGraph

    before(function (done) {
      testData.tbbtGraph().then(function (graph) {
        tbbtGraph = graph

        done()
      }).catch(function (error) {
        done(error)
      })
    })

    describe('filter', function () {
      it('namedNode should filter NamedNode nodes', function () {
        assert.equal(rdf.utils.filter.namedNode(rdf.createNamedNode('http://example.org')), true)
        assert.equal(rdf.utils.filter.namedNode(rdf.createBlankNode()), false)
        assert.equal(rdf.utils.filter.namedNode(rdf.createLiteral('test')), false)
      })

      it('blankNode should filter BlankNode nodes', function () {
        assert.equal(rdf.utils.filter.blankNode(rdf.createNamedNode('http://example.org')), false)
        assert.equal(rdf.utils.filter.blankNode(rdf.createBlankNode()), true)
        assert.equal(rdf.utils.filter.blankNode(rdf.createLiteral('test')), false)
      })

      it('literal should filter Literal nodes', function () {
        assert.equal(rdf.utils.filter.literal(rdf.createNamedNode('http://example.org')), false)
        assert.equal(rdf.utils.filter.literal(rdf.createBlankNode()), false)
        assert.equal(rdf.utils.filter.literal(rdf.createLiteral('test')), true)
      })

      it('namedNodeSubject should exclude NamedNodes with different subject', function () {
        var blankNodeTriple = rdf.createTriple(
          rdf.createBlankNode(),
          rdf.createNamedNode('http://example.org'),
          rdf.createLiteral('test'))

        var subject = rdf.createNamedNode('http://example.org/subject')

        var sameSubjectTriple = rdf.createTriple(
          subject,
          rdf.createNamedNode('http://example.org'),
          rdf.createLiteral('test'))

        var otherSubjectTriple = rdf.createTriple(
          rdf.createNamedNode('http://example.org/otherSubject'),
          rdf.createNamedNode('http://example.org'),
          rdf.createLiteral('test'))

        assert.equal(rdf.utils.filter.namedNodeSubject(subject)(blankNodeTriple), true)
        assert.equal(rdf.utils.filter.namedNodeSubject(subject)(sameSubjectTriple), true)
        assert.equal(rdf.utils.filter.namedNodeSubject(subject)(otherSubjectTriple), false)
      })
    })

    describe('list', function () {
      it('should list subjects', function () {
        var subject = rdf.createNamedNode('http://localhost:8080/data/person/amy-farrah-fowler')
        var subjects = rdf.utils.list.subjects(tbbtGraph.match(subject))

        assert.equal(subjects.length, 1)
        assert.equal(subjects[0].toString(), subject.toString())
      })

      it('should list subjects with filter', function () {
        var subject = rdf.createNamedNode('http://localhost:8080/data/person/amy-farrah-fowler')
        var subjects = rdf.utils.list.subjects(tbbtGraph, function (node) { return node.equals(subject) })

        assert.equal(subjects.length, 1)
        assert.equal(subjects[0].toString(), subject.toString())
      })

      it('should list predicates', function () {
        var predicate = rdf.createNamedNode('http://schema.org/knows')
        var predicates = rdf.utils.list.predicates(tbbtGraph.match(null, predicate))

        assert.equal(predicates.length, 1)
        assert.equal(predicates[0].toString(), predicate.toString())
      })

      it('should list predicates with filter', function () {
        var predicate = rdf.createNamedNode('http://schema.org/knows')
        var predicates = rdf.utils.list.predicates(tbbtGraph, function (node) { return node.equals(predicate) })

        assert.equal(predicates.length, 1)
        assert.equal(predicates[0].toString(), predicate.toString())
      })

      it('should list objects', function () {
        var object = rdf.createLiteral('microbiologist')
        var objects = rdf.utils.list.objects(tbbtGraph.match(null, null, object))

        assert.equal(objects.length, 1)
        assert.equal(objects[0].toString(), object.toString())
      })

      it('should list objects with filter', function () {
        var object = rdf.createLiteral('microbiologist')
        var objects = rdf.utils.list.objects(tbbtGraph, function (node) { return node.equals(object) })

        assert.equal(objects.length, 1)
        assert.equal(objects[0].toString(), object.toString())
      })
    })

    describe('subgraph', function () {
      it('should create a subgraph', function () {
        var tbbtGraphNg = rdf.createGraph()

        // create a copy of tbbt + a not linked triple
        tbbtGraphNg.addAll(tbbtGraph)
        tbbtGraphNg.add(rdf.createTriple(
          rdf.createNamedNode('http://example.org/subject'),
          rdf.createNamedNode('http://example.org/predicate'),
          rdf.createLiteral('object')))

        var subgraph = rdf.utils.createSubGraph(
          tbbtGraphNg,
          rdf.createNamedNode('http://localhost:8080/data/person/amy-farrah-fowler'))

        assert.equal(subgraph.length, tbbtGraph.length)
      })

      it('should create a subgraph with filter', function () {
        var subject = rdf.createNamedNode('http://localhost:8080/data/person/amy-farrah-fowler')

        var subgraph = rdf.utils.createSubGraph(tbbtGraph, subject, function (triple) {
          return triple.predicate.equals(rdf.createNamedNode('http://schema.org/knows'))
        })

        assert.equal(subgraph.length, 61)
        assert.equal(rdf.utils.list.predicates(subgraph).length, 1)
      })

      it('should create a subgraph by NamedNode subject', function () {
        var subgraph = rdf.utils.createSubGraphByNamedNodeSubject(
          tbbtGraph,
          rdf.createNamedNode('http://localhost:8080/data/person/amy-farrah-fowler'))

        assert.equal(subgraph.length, 12)
      })

      it('should split a graph by NamedNode subject into a store', function (done) {
        rdf.utils.splitGraphByNamedNodeSubject(tbbtGraph)
          .then(function (store) {
            var graphCount = 0

            store.forEach(function () {
              graphCount++
            })

            assert.equal(graphCount, 9)
          })
          .then(function () {
            done()
          })
          .catch(function (error) {
            done(error)
          })
      })
    })

    /* describe('mimeType', function () {
      it('should find a parser by mime type and use it to parse data', function (done) {
        rdf.utils.parse('application/n-triples', tbbtGraph.toString())
          .then(function (graph) {
            assert.equal(graph.length, 126);
          })
          .then(function () {
            done();
          })
          .catch(function (error) {
            done(error);
          });
      });

      it('should throw an error if the mime type is not in the parser map', function (done) {
        rdf.utils.parse('image/jpeg', '')
          .then(function (graph) {
            done('no error thrown');
          })
          .catch(function (error) {
            done();
          });
      });

      it('should find a serializer by mime type and use it to serialize data', function (done) {
        rdf.utils.serialize('application/n-triples', tbbtGraph)
            .then(function (output) {
              assert.equal(output, tbbtGraph.toString());
            })
            .then(function () {
              done();
            })
            .catch(function (error) {
              done(error);
            });
      });

      it('should throw an error if the mime type is not in the serializer map', function (done) {
        rdf.utils.serialize('image/jpeg', rdf.createGraph())
            .then(function (output) {
              done('no error thrown');
            })
            .catch(function (error) {
              done();
            });
      });
    }); */
  })
}
<commit_msg>fixed test to use new interface<commit_after>/* global before, describe, it */
var assert = require('assert')
var rdf = require('../rdf-ext')
var testData = require('rdf-test-data')

module.exports = function (ctx) {
  describe('utils', function () {
    var tbbtGraph

    before(function (done) {
      testData.tbbtGraph().then(function (graph) {
        tbbtGraph = graph

        done()
      }).catch(function (error) {
        done(error)
      })
    })

    describe('filter', function () {
      it('namedNode should filter NamedNode nodes', function () {
        assert.equal(rdf.utils.filter.namedNode(rdf.createNamedNode('http://example.org')), true)
        assert.equal(rdf.utils.filter.namedNode(rdf.createBlankNode()), false)
        assert.equal(rdf.utils.filter.namedNode(rdf.createLiteral('test')), false)
      })

      it('blankNode should filter BlankNode nodes', function () {
        assert.equal(rdf.utils.filter.blankNode(rdf.createNamedNode('http://example.org')), false)
        assert.equal(rdf.utils.filter.blankNode(rdf.createBlankNode()), true)
        assert.equal(rdf.utils.filter.blankNode(rdf.createLiteral('test')), false)
      })

      it('literal should filter Literal nodes', function () {
        assert.equal(rdf.utils.filter.literal(rdf.createNamedNode('http://example.org')), false)
        assert.equal(rdf.utils.filter.literal(rdf.createBlankNode()), false)
        assert.equal(rdf.utils.filter.literal(rdf.createLiteral('test')), true)
      })

      it('namedNodeSubject should exclude NamedNodes with different subject', function () {
        var blankNodeTriple = rdf.createTriple(
          rdf.createBlankNode(),
          rdf.createNamedNode('http://example.org'),
          rdf.createLiteral('test'))

        var subject = rdf.createNamedNode('http://example.org/subject')

        var sameSubjectTriple = rdf.createTriple(
          subject,
          rdf.createNamedNode('http://example.org'),
          rdf.createLiteral('test'))

        var otherSubjectTriple = rdf.createTriple(
          rdf.createNamedNode('http://example.org/otherSubject'),
          rdf.createNamedNode('http://example.org'),
          rdf.createLiteral('test'))

        assert.equal(rdf.utils.filter.namedNodeSubject(subject)(blankNodeTriple), true)
        assert.equal(rdf.utils.filter.namedNodeSubject(subject)(sameSubjectTriple), true)
        assert.equal(rdf.utils.filter.namedNodeSubject(subject)(otherSubjectTriple), false)
      })
    })

    describe('list', function () {
      it('should list subjects', function () {
        var subject = rdf.createNamedNode('http://localhost:8080/data/person/amy-farrah-fowler')
        var subjects = rdf.utils.list.subjects(tbbtGraph.match(subject))

        assert.equal(subjects.length, 1)
        assert.equal(subjects[0].toString(), subject.toString())
      })

      it('should list subjects with filter', function () {
        var subject = rdf.createNamedNode('http://localhost:8080/data/person/amy-farrah-fowler')
        var subjects = rdf.utils.list.subjects(tbbtGraph, function (node) { return node.equals(subject) })

        assert.equal(subjects.length, 1)
        assert.equal(subjects[0].toString(), subject.toString())
      })

      it('should list predicates', function () {
        var predicate = rdf.createNamedNode('http://schema.org/knows')
        var predicates = rdf.utils.list.predicates(tbbtGraph.match(null, predicate))

        assert.equal(predicates.length, 1)
        assert.equal(predicates[0].toString(), predicate.toString())
      })

      it('should list predicates with filter', function () {
        var predicate = rdf.createNamedNode('http://schema.org/knows')
        var predicates = rdf.utils.list.predicates(tbbtGraph, function (node) { return node.equals(predicate) })

        assert.equal(predicates.length, 1)
        assert.equal(predicates[0].toString(), predicate.toString())
      })

      it('should list objects', function () {
        var object = rdf.createLiteral('microbiologist')
        var objects = rdf.utils.list.objects(tbbtGraph.match(null, null, object))

        assert.equal(objects.length, 1)
        assert.equal(objects[0].toString(), object.toString())
      })

      it('should list objects with filter', function () {
        var object = rdf.createLiteral('microbiologist')
        var objects = rdf.utils.list.objects(tbbtGraph, function (node) { return node.equals(object) })

        assert.equal(objects.length, 1)
        assert.equal(objects[0].toString(), object.toString())
      })
    })

    describe('subgraph', function () {
      it('should create a subgraph', function () {
        var tbbtGraphNg = rdf.createGraph()

        // create a copy of tbbt + a not linked triple
        tbbtGraphNg.addAll(tbbtGraph)
        tbbtGraphNg.add(rdf.createTriple(
          rdf.createNamedNode('http://example.org/subject'),
          rdf.createNamedNode('http://example.org/predicate'),
          rdf.createLiteral('object')))

        var subgraph = rdf.utils.createSubGraph(
          tbbtGraphNg,
          rdf.createNamedNode('http://localhost:8080/data/person/amy-farrah-fowler'))

        assert.equal(subgraph.length, tbbtGraph.length)
      })

      it('should create a subgraph with filter', function () {
        var subject = rdf.createNamedNode('http://localhost:8080/data/person/amy-farrah-fowler')

        var subgraph = rdf.utils.createSubGraph(tbbtGraph, subject, function (triple) {
          return triple.predicate.equals(rdf.createNamedNode('http://schema.org/knows'))
        })

        assert.equal(subgraph.length, 61)
        assert.equal(rdf.utils.list.predicates(subgraph).length, 1)
      })

      it('should create a subgraph by NamedNode subject', function () {
        var subgraph = rdf.utils.createSubGraphByNamedNodeSubject(
          tbbtGraph,
          rdf.createNamedNode('http://localhost:8080/data/person/amy-farrah-fowler'))

        assert.equal(subgraph.length, 12)
      })

      it('should split a graph by NamedNode subject into a store', function (done) {
        rdf.utils.splitGraphByNamedNodeSubject(tbbtGraph)
          .then(function (store) {
            assert.equal(Object.keys(store.graphs).length, 9)
          })
          .then(function () {
            done()
          })
          .catch(function (error) {
            done(error)
          })
      })
    })
  })
}
<|endoftext|>


<commit_before>'use strict';

var commonUtils = require('deltadb-common-utils');

var Utils = function () {};

Utils.prototype.IE = global.window && navigator.appName == 'Microsoft Internet Explorer';

// Testing with IE in Saucelabs can be VERY slow therefore we need to increase the timeouts
if (global.deltaDBSaucelabs && Utils.prototype.IE) { // Saucelabs and IE?
  Utils.prototype.TIMEOUT = 120000;
} else {
  Utils.prototype.TIMEOUT = 20000; // ORIGINAL
}

Utils.prototype.sleep = function (sleepMs) {
  // Ensure a different timestamp will be generated after this function resolves.
  // Occasionally, using timeout(1) will not guarantee a different timestamp, e.g.:
  //   1. (new Date()).getTime()
  //   2. timeout(1)
  //   3. (new Date()).getTime()
  // It is not clear as to what causes this but the solution is to sleep longer. This function is
  // also used to delay between DB writes to create predictable patterns. In this case it may be
  // that the DB adapter processes queries out of sequence.
  return commonUtils.timeout(sleepMs ? sleepMs : 10);
};

Utils.prototype.allShouldEql = function (collection, expected) {
  // Index data as order is guaranteed

  var allDocs = {};

  var allExpDocs = {};
  expected.forEach(function (exp) {
    allExpDocs[exp.$id] = exp;
  });

  return collection.all(function (item) {
    allDocs[item.id()] = item.get();
  }).then(function () {
    allDocs.should.eql(allExpDocs);
  });
};

module.exports = new Utils();
<commit_msg>doc(utils): remove debug comment<commit_after>'use strict';

var commonUtils = require('deltadb-common-utils');

var Utils = function () {};

Utils.prototype.IE = global.window && navigator.appName == 'Microsoft Internet Explorer';

// Testing with IE in Saucelabs can be VERY slow therefore we need to increase the timeouts
if (global.deltaDBSaucelabs && Utils.prototype.IE) { // Saucelabs and IE?
  Utils.prototype.TIMEOUT = 120000;
} else {
  Utils.prototype.TIMEOUT = 20000;
}

Utils.prototype.sleep = function (sleepMs) {
  // Ensure a different timestamp will be generated after this function resolves.
  // Occasionally, using timeout(1) will not guarantee a different timestamp, e.g.:
  //   1. (new Date()).getTime()
  //   2. timeout(1)
  //   3. (new Date()).getTime()
  // It is not clear as to what causes this but the solution is to sleep longer. This function is
  // also used to delay between DB writes to create predictable patterns. In this case it may be
  // that the DB adapter processes queries out of sequence.
  return commonUtils.timeout(sleepMs ? sleepMs : 10);
};

Utils.prototype.allShouldEql = function (collection, expected) {
  // Index data as order is guaranteed

  var allDocs = {};

  var allExpDocs = {};
  expected.forEach(function (exp) {
    allExpDocs[exp.$id] = exp;
  });

  return collection.all(function (item) {
    allDocs[item.id()] = item.get();
  }).then(function () {
    allDocs.should.eql(allExpDocs);
  });
};

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


<commit_before>const logger = require('winston')
const listItems = require('../model/listitems')

const route = (request, response) => {
  logger.log('info', request)
  const data = {
    list: 'shopping',
    familyId: 2
  }
  listItems.findPromise(data)
    .then(result => {
      const listItemNames = result.listItems.map(listItem => {
        return {name: listItem.listItemName}
      })
      response.json(listItemNames)
    })
}

module.exports = {
  route
}
<commit_msg>test request object;<commit_after>const logger = require('winston')
const listItems = require('../model/listitems')

const route = (request, response) => {
  logger.log('info', request)
  const data = {
    list: 'shopping',
    familyId: 2
  }
  listItems.findPromise(data)
    .then(result => {
      const listItemNames = result.listItems.map(listItem => {
        return {name: listItem.listItemName}
      })
      response.json(request)
    })
}

module.exports = {
  route
}
<|endoftext|>


<commit_before>var gaAnalytics = require("ga-analytics");

var googleAnalytics = {};

googleAnalytics.load = function(args, next) {
  var outputs = [];

  gaAnalytics(args, function(err, res) {
    if(err) {
      next(error, "google analytics error.");
      return;
    }

    outputs.push(res.totalsForAllResults[args.metrics]);
    next(false, outputs);
  });
};

module.exports = googleAnalytics;
<commit_msg>Add moment require.<commit_after>var gaAnalytics = require("ga-analytics"),
    moment = require("moment");

var googleAnalytics = {};

googleAnalytics.load = function(args, next) {
  var outputs = [];

  gaAnalytics(args, function(err, res) {
    if(err) {
      next(error, "google analytics error.");
      return;
    }

    outputs.push(res.totalsForAllResults[args.metrics]);
    next(false, outputs);
  });
};

module.exports = googleAnalytics;
<|endoftext|>


<commit_before>'use strict';

var urlFn = require('url');
var moment = require('moment');
var util = require('hexo-util');
var htmlTag = util.htmlTag;
var stripHTML = util.stripHTML;
var cheerio;

function meta(name, content) {
  return htmlTag('meta', {
    name: name,
    content: content
  }) + '\n';
}

function og(name, content) {
  return htmlTag('meta', {
    property: name,
    content: content
  }) + '\n';
}

function openGraphHelper(options) {
  options = options || {};

  if (!cheerio) cheerio = require('cheerio');

  var page = this.page;
  var config = this.config;
  var content = page.content;
  var images = options.image || options.images || page.photos || [];
  var description = options.description || page.description || page.excerpt || content || config.description;
  var title = options.title || page.title || config.title;
  var type = options.type || (this.is_post() ? 'article' : 'website');
  var url = options.url || this.url;
  var siteName = options.site_name || config.title;
  var twitterCard = options.twitter_card || 'summary';
  var updated = options.updated || page.updated;
  var result = '';

  if (!Array.isArray(images)) images = [images];

  if (description) {
    description = stripHTML(description).substring(0, 200)
      .replace(/^\s+|\s+$/g, '') // Remove prefixing/trailing spaces
      .replace(/</g, '<')
      .replace(/>/g, '>')
      .replace(/&/g, '&')
      .replace(/"/g, '"')
      .replace(/'/g, ''');
  }

  if (!images.length && content) {
    images = images.slice();

    var $ = cheerio.load(content);

    $('img').each(function() {
      var src = $(this).attr('src');
      if (src) images.push(src);
    });
  }

  result += meta('description', description);
  result += og('og:type', type);
  result += og('og:title', title);
  result += og('og:url', url);
  result += og('og:site_name', siteName);
  result += og('og:description', description);

  images.map(function(path) {
    if (!urlFn.parse(path).host) {
      if (path[0] !== '/') path = '/' + path;
      return config.url + path;
    }

    return path;
  }).forEach(function(path) {
    result += og('og:image', path);
  });

  if (updated) {
    if ((moment.isMoment(updated) || moment.isDate(updated)) && !isNaN(updated.valueOf())) {
      result += og('og:updated_time', updated.toISOString());
    }
  }

  result += meta('twitter:card', twitterCard);
  result += meta('twitter:title', title);
  result += meta('twitter:description', description);

  if (options.twitter_id) {
    var twitterId = options.twitter_id;
    if (twitterId[0] !== '@') twitterId = '@' + twitterId;

    result += meta('twitter:creator', twitterId);
  }

  if (options.twitter_site) {
    result += meta('twitter:site', options.twitter_site);
  }

  if (options.google_plus) {
    result += htmlTag('link', {rel: 'publisher', href: options.google_plus}) + '\n';
  }

  if (options.fb_admins) {
    result += og('fb:admins', options.fb_admins);
  }

  if (options.fb_app_id) {
    result += og('fb:app_id', options.fb_app_id);
  }

  return result.trim();
}

module.exports = openGraphHelper;
<commit_msg>trim() instead of regular expression<commit_after>'use strict';

var urlFn = require('url');
var moment = require('moment');
var util = require('hexo-util');
var htmlTag = util.htmlTag;
var stripHTML = util.stripHTML;
var cheerio;

function meta(name, content) {
  return htmlTag('meta', {
    name: name,
    content: content
  }) + '\n';
}

function og(name, content) {
  return htmlTag('meta', {
    property: name,
    content: content
  }) + '\n';
}

function openGraphHelper(options) {
  options = options || {};

  if (!cheerio) cheerio = require('cheerio');

  var page = this.page;
  var config = this.config;
  var content = page.content;
  var images = options.image || options.images || page.photos || [];
  var description = options.description || page.description || page.excerpt || content || config.description;
  var title = options.title || page.title || config.title;
  var type = options.type || (this.is_post() ? 'article' : 'website');
  var url = options.url || this.url;
  var siteName = options.site_name || config.title;
  var twitterCard = options.twitter_card || 'summary';
  var updated = options.updated || page.updated;
  var result = '';

  if (!Array.isArray(images)) images = [images];

  if (description) {
    description = stripHTML(description).substring(0, 200)
      .trim() // Remove prefixing/trailing spaces
      .replace(/</g, '<')
      .replace(/>/g, '>')
      .replace(/&/g, '&')
      .replace(/"/g, '"')
      .replace(/'/g, ''');
  }

  if (!images.length && content) {
    images = images.slice();

    var $ = cheerio.load(content);

    $('img').each(function() {
      var src = $(this).attr('src');
      if (src) images.push(src);
    });
  }

  result += meta('description', description);
  result += og('og:type', type);
  result += og('og:title', title);
  result += og('og:url', url);
  result += og('og:site_name', siteName);
  result += og('og:description', description);

  images.map(function(path) {
    if (!urlFn.parse(path).host) {
      if (path[0] !== '/') path = '/' + path;
      return config.url + path;
    }

    return path;
  }).forEach(function(path) {
    result += og('og:image', path);
  });

  if (updated) {
    if ((moment.isMoment(updated) || moment.isDate(updated)) && !isNaN(updated.valueOf())) {
      result += og('og:updated_time', updated.toISOString());
    }
  }

  result += meta('twitter:card', twitterCard);
  result += meta('twitter:title', title);
  result += meta('twitter:description', description);

  if (options.twitter_id) {
    var twitterId = options.twitter_id;
    if (twitterId[0] !== '@') twitterId = '@' + twitterId;

    result += meta('twitter:creator', twitterId);
  }

  if (options.twitter_site) {
    result += meta('twitter:site', options.twitter_site);
  }

  if (options.google_plus) {
    result += htmlTag('link', {rel: 'publisher', href: options.google_plus}) + '\n';
  }

  if (options.fb_admins) {
    result += og('fb:admins', options.fb_admins);
  }

  if (options.fb_app_id) {
    result += og('fb:app_id', options.fb_app_id);
  }

  return result.trim();
}

module.exports = openGraphHelper;
<|endoftext|>


<commit_before>// rateLimiter.js

//
// Built-in Memory Store
//
//  This is used to keep track of rate-limits in-memory
//  You should not be using this Memory store for production usage,
//  as it's state will fresh everytime you reinitialization / load the rateLimiter plugin
//

//
// Storing rate limit data Redis
//
/*
  The rateLimiter plugin expects a 'provider' option is passed into it's configuraiton
  This provider will default to in-memory, but can easily be extended to Redis by passing in a Redis client

  The rateLimiter provider requires the follow methods:

    provider.incr
    provider.incrBy

  If you are using a redis client, you should already have `incr` and `incrby` available.

*/

// X-RateLimit-Limit
// X-RateLimit-Remaining
// TODO: X-RateLimit-Concurrency
// X-RateLimit-Running
// TODO: X-RateLimit-Reset
/*
| X-RateLimit-Limit           | Request limit per hour                      |
+-----------------------------+---------------------------------------------+
| X-RateLimit-Remaining       | The number of requests left for the time    |
|                             | window                                      |
+-----------------------------+---------
*/

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

module.exports = function rateLimitingMiddleware (config) {

  config = config || {};
  config.maxLimit = config.maxLimit || 1000;
  config.maxConcurrency = config.maxConcurrency || 2;

  config.maxConcurrencyMessage = "Rate limited: Max concurrency limit hit: " + config.maxConcurrency;
  config.maxLimitMessage = "Rate limited: Max services limit hit: " + config.maxLimit;

  // provider should be an instance of a node-redis client
  var provider = config.provider || new Store('memory');

  return function rateLimitingHandler (req, res, next) {
    var write = res.write;
    var end = res.end;

    // TODO: better default identity provider, perhaps get user name from system
    var owner = req.params.owner || "anonymous";

    res.on('close', function(){
      // console.log("res.close".magenta, res.statusCode);
      if (req.reduceCount === false) {
      } else {
        provider.zincrby(['running', -1, owner]);
      }
    });

    res.on('finish', function(){
      // console.log("res.finish".magenta, res.statusCode);
      if (req.reduceCount === false) {
      } else {
        provider.zincrby(['running', -1, owner]);
        provider.zincrby(['totalRunning', -1, 'tallies']);
      }
    });

    res.setHeader('X-RateLimit-Limit', config.maxLimit);

    provider.zscore("hits", owner, function (err, hits) {

      // console.log('metric.' + owner + '.hits'.green, err, hits);
      res.setHeader('X-RateLimit-Remaining', (config.maxLimit - hits).toString());

      // if total hits for user account is exceeded, rate-limit
      if (Number(hits) >= config.maxLimit) {
        // TODO: better error message
        res.writeHead(500);
        req.reduceCount = false;
        return res.end(config.maxLimitMessage);
      }

      // Get total amount of running hooks for current user
      provider.zscore("running", owner, function (err, total) {
        if (err) {
          return res.end(err.message);
        }
        if (total === null) {
          total = 0;
        }
        res.setHeader('X-RateLimit-Running', total.toString());
        // console.log('metric.' + owner + '.running'.green, total, config.maxConcurrency)
        // if total running is greater than account concurrency limit, rate-limit the request
        if (Number(total) >= config.maxConcurrency) {
          // TODO: better error message
          res.writeHead(500);
          req.reduceCount = false;
          return res.end(config.maxConcurrencyMessage);
        }
        provider.zincrby(['hits', 1, owner]);
        provider.zincrby(['running', 1, owner], next);
        provider.zincrby(['totalHits', 1, 'tallies']);
        provider.zincrby(['totalRunning', 1, 'tallies']);
      });
    });
  };
};<commit_msg>[api] [plugins] Add hits for individual services<commit_after>// rateLimiter.js

//
// Built-in Memory Store
//
//  This is used to keep track of rate-limits in-memory
//  You should not be using this Memory store for production usage,
//  as it's state will fresh everytime you reinitialization / load the rateLimiter plugin
//

//
// Storing rate limit data Redis
//
/*
  The rateLimiter plugin expects a 'provider' option is passed into it's configuraiton
  This provider will default to in-memory, but can easily be extended to Redis by passing in a Redis client

  The rateLimiter provider requires the follow methods:

    provider.incr
    provider.incrBy

  If you are using a redis client, you should already have `incr` and `incrby` available.

*/

// X-RateLimit-Limit
// X-RateLimit-Remaining
// TODO: X-RateLimit-Concurrency
// X-RateLimit-Running
// TODO: X-RateLimit-Reset
/*
| X-RateLimit-Limit           | Request limit per hour                      |
+-----------------------------+---------------------------------------------+
| X-RateLimit-Remaining       | The number of requests left for the time    |
|                             | window                                      |
+-----------------------------+---------
*/

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

module.exports = function rateLimitingMiddleware (config) {

  config = config || {};
  config.maxLimit = config.maxLimit || 1000;
  config.maxConcurrency = config.maxConcurrency || 2;

  config.maxConcurrencyMessage = "Rate limited: Max concurrency limit hit: " + config.maxConcurrency;
  config.maxLimitMessage = "Rate limited: Max services limit hit: " + config.maxLimit;

  // provider should be an instance of a node-redis client
  var provider = config.provider || new Store('memory');

  return function rateLimitingHandler (req, res, next) {
    var write = res.write;
    var end = res.end;

    // TODO: better default identity provider, perhaps get user name from system
    var owner = req.params.owner || "anonymous";

    res.on('close', function(){
      // console.log("res.close".magenta, res.statusCode);
      if (req.reduceCount === false) {
      } else {
        provider.zincrby(['running', -1, owner]);
      }
    });

    res.on('finish', function(){
      // console.log("res.finish".magenta, res.statusCode);
      if (req.reduceCount === false) {
      } else {
        provider.zincrby(['running', -1, owner]);
        provider.zincrby(['totalRunning', -1, 'tallies']);
      }
    });

    res.setHeader('X-RateLimit-Limit', config.maxLimit);

    provider.zscore("hits", owner, function (err, hits) {

      // console.log('metric.' + owner + '.hits'.green, err, hits);
      res.setHeader('X-RateLimit-Remaining', (config.maxLimit - hits).toString());

      // if total hits for user account is exceeded, rate-limit
      if (Number(hits) >= config.maxLimit) {
        // TODO: better error message
        res.writeHead(500);
        req.reduceCount = false;
        return res.end(config.maxLimitMessage);
      }

      // Get total amount of running hooks for current user
      provider.zscore("running", owner, function (err, total) {
        if (err) {
          return res.end(err.message);
        }
        if (total === null) {
          total = 0;
        }
        res.setHeader('X-RateLimit-Running', total.toString());
        // console.log('metric.' + owner + '.running'.green, total, config.maxConcurrency)
        // if total running is greater than account concurrency limit, rate-limit the request
        if (Number(total) >= config.maxConcurrency) {
          // TODO: better error message
          res.writeHead(500);
          req.reduceCount = false;
          return res.end(config.maxConcurrencyMessage);
        }
        provider.zincrby(['hits', 1, owner]);
        provider.zincrby(['hits', 1, owner + '/' + req.params.hook]);
        provider.zincrby(['running', 1, owner], next);
        provider.zincrby(['totalHits', 1, 'tallies']);
        provider.zincrby(['totalRunning', 1, 'tallies']);
      });
    });
  };
};<|endoftext|>


<commit_before>'use strict';

let throwIfMissing = require('../../support/util').throwIfMissing,
  path = require('path'),
  urlParser = require('url'),
  messageMaker = require('../../support/messageMaker'),
  filterRegistry = require('../../support/filterRegistry'),
  analyzer = require('./analyzer'),
  aggregator = require('./aggregator'),
  forEach = require('lodash.foreach'),
  WebPageTest = require('webpagetest');

const make = messageMaker('webpagetest').make;

const hostRegex = /^(https?:\/\/)?([^\/]*)/i;
const defaultWptHost = urlParser.parse(WebPageTest.defaultServer).host;

const DEFAULT_METRICS = [
  'data.median.*.SpeedIndex',
  'data.median.*.render',
  'data.median.*.TTFB',
  'data.median.*.fullyLoaded'];

module.exports = {
  name() {
    return path.basename(__dirname);
  },
  open(context, options) {
    throwIfMissing(options.webpagetest, ['host'], 'webpagetest');

    if (!options.webpagetest.key) {
      const host = hostRegex.exec(options.webpagetest.host);
      if (host && host[2] === defaultWptHost) {
        throw new Error('webpagetest.key needs to be specified when using the public WebPageTest server.');
      }
    }

    this.options = options;

    filterRegistry.registerFilterForType(DEFAULT_METRICS, 'webpagetest.pageSummary');
  },
  processMessage(message, queue) {
    switch (message.type) {
      case 'url':
      {
        const url = message.url;
        return analyzer.analyzeUrl(url, this.options)
          .tap((result) => {
            queue.postMessage(make('webpagetest.har', result.har, {url}));

            forEach(result.data.runs, (run, runKey) =>
              queue.postMessage(make('webpagetest.run', run, {
                url,
                runIndex: (parseInt(runKey) - 1)
              }))
            );

            queue.postMessage(make('webpagetest.pageSummary', result, {url}));
            aggregator.addToAggregate(result);
          })
          .catch((err) => {
            queue.postMessage(make('error', err, {url: message.url}));
          })
      }

      case 'summarize':
      {
        let summary = aggregator.summarize();
        if (summary && Object.keys(summary).length > 0) {
          queue.postMessage(make('webpagetest.summary', summary));
        }
      }
    }
  }
};
<commit_msg>Slight code simplification using ES6.<commit_after>'use strict';

let throwIfMissing = require('../../support/util').throwIfMissing,
  path = require('path'),
  urlParser = require('url'),
  messageMaker = require('../../support/messageMaker'),
  filterRegistry = require('../../support/filterRegistry'),
  analyzer = require('./analyzer'),
  aggregator = require('./aggregator'),
  forEach = require('lodash.foreach'),
  WebPageTest = require('webpagetest');

const make = messageMaker('webpagetest').make;

const hostRegex = /^(https?:\/\/)?([^\/]*)/i;
const defaultWptHost = urlParser.parse(WebPageTest.defaultServer).host;

const DEFAULT_METRICS = [
  'data.median.*.SpeedIndex',
  'data.median.*.render',
  'data.median.*.TTFB',
  'data.median.*.fullyLoaded'];

module.exports = {
  name() {
    return path.basename(__dirname);
  },
  open(context, options) {
    throwIfMissing(options.webpagetest, ['host'], 'webpagetest');

    if (!options.webpagetest.key) {
      const host = hostRegex.exec(options.webpagetest.host);
      if (host && host[2] === defaultWptHost) {
        throw new Error('webpagetest.key needs to be specified when using the public WebPageTest server.');
      }
    }

    this.options = options;

    filterRegistry.registerFilterForType(DEFAULT_METRICS, 'webpagetest.pageSummary');
  },
  processMessage(message, queue) {
    switch (message.type) {
      case 'url':
      {
        const url = message.url;
        return analyzer.analyzeUrl(url, this.options)
          .tap((result) => {
            queue.postMessage(make('webpagetest.har', result.har, {url}));

            forEach(result.data.runs, (run, runKey) =>
              queue.postMessage(make('webpagetest.run', run, {
                url,
                runIndex: (parseInt(runKey) - 1)
              }))
            );

            queue.postMessage(make('webpagetest.pageSummary', result, {url}));
            aggregator.addToAggregate(result);
          })
          .catch((err) => {
            queue.postMessage(make('error', err, {url}));
          })
      }

      case 'summarize':
      {
        let summary = aggregator.summarize();
        if (summary && Object.keys(summary).length > 0) {
          queue.postMessage(make('webpagetest.summary', summary));
        }
      }
    }
  }
};
<|endoftext|>


<commit_before>const array1 = [5, 12, 50, 130, 44];

const isLargeNumber = (element) => element > 45;

console.log(array1.findLastIndex(isLargeNumber));
// expected output: 3  (of element with value: 30)
<commit_msg>fix: typo in live example of array-findlastindex.js (#2255)<commit_after>const array1 = [5, 12, 50, 130, 44];

const isLargeNumber = (element) => element > 45;

console.log(array1.findLastIndex(isLargeNumber));
// expected output: 3  (of element with value: 130)
<|endoftext|>


<commit_before>import _ from 'lodash';
import {Router} from 'express';
import jsonapify, {Resource, Runtime, Template, Property} from 'jsonapify';

import * as common from './common';
import * as logger from '../logger';
import {Client} from '../models';

const clientResource = new Resource(Client, {
	'type': 'clients',
	'id': {
		value: new Property('_id'),
		writable: false,
	},
	'links': {
		'self': {
			value: new Template('/clients/${_id}'),
			writable: false,
		},
	},
	'attributes': {
		'name': new Property('name'),
		'secret': new Property('secret'),
		'trusted': new Property('trusted'),
		'redirect-uri': {
			value: new Property('redirectUri'),
			nullable: true,
		},
	},
});

Runtime.addResource('Client', clientResource);

const router = Router();

router.get('/',
	common.authenticate('token-bearer'),
	common.requirePrivilege('client:enum'),
	jsonapify.enumerate('Client'),
	logger.logErrors(), jsonapify.errorHandler());

router.post('/',
	common.authenticate('token-bearer'),
	common.requirePrivilege('client:add'),
	common.requirePrivilege(clientTrustPrivilege),
	jsonapify.create('Client'),
	logger.logErrors(), jsonapify.errorHandler());

router.get('/:id',
	common.authenticate('token-bearer'),
	common.requirePrivilege('client:read'),
	jsonapify.read(['Client', jsonapify.param('id')]),
	logger.logErrors(), jsonapify.errorHandler());

router.put('/:id',
	common.authenticate('token-bearer'),
	common.requirePrivilege('client:edit'),
	common.requirePrivilege(clientTrustPrivilege),
	jsonapify.update(['Client', jsonapify.param('id')]),
	logger.logErrors(), jsonapify.errorHandler());

router.delete('/:id',
	common.authenticate('token-bearer'),
	common.requirePrivilege('client:remove'),
	jsonapify.remove(['Client', jsonapify.param('id')]),
	logger.logErrors(), jsonapify.errorHandler());

function clientTrustPrivilege(req, cb) {
	let id = req.params.id;
	let newTrusted = false;
	if (req.method === 'post' || req.method === 'put')
		newTrusted = _.get(req.body, 'data.attributes.trusted');
	if (!newTrusted) return cb(null, false);
	Client.findById(id, function(err, client) {
		if (err) return cb(err);
		if (!client) return cb(null, false);
		cb(null, client.trusted ? false : 'client:trust');
	});
}

export default router;
<commit_msg>Generate client secret server side<commit_after>import _ from 'lodash';
import {Router} from 'express';
import jsonapify, {Resource, Runtime, Template, Property} from 'jsonapify';

import * as common from './common';
import * as logger from '../logger';
import {Client} from '../models';

const clientResource = new Resource(Client, {
	'type': 'clients',
	'id': {
		value: new Property('_id'),
		writable: false,
	},
	'links': {
		'self': {
			value: new Template('/clients/${_id}'),
			writable: false,
		},
	},
	'attributes': {
		'name': new Property('name'),
		'trusted': new Property('trusted'),
		'secret': {
			value: new Property('secret'),
			writable: false,
		},
		'redirect-uri': {
			value: new Property('redirectUri'),
			nullable: true,
		},
	},
});

Runtime.addResource('Client', clientResource);

const router = Router();

router.get('/',
	common.authenticate('token-bearer'),
	common.requirePrivilege('client:enum'),
	jsonapify.enumerate('Client'),
	logger.logErrors(), jsonapify.errorHandler());

router.post('/',
	common.authenticate('token-bearer'),
	common.requirePrivilege('client:add'),
	common.requirePrivilege(clientTrustPrivilege),
	jsonapify.create('Client'),
	logger.logErrors(), jsonapify.errorHandler());

router.get('/:id',
	common.authenticate('token-bearer'),
	common.requirePrivilege('client:read'),
	jsonapify.read(['Client', jsonapify.param('id')]),
	logger.logErrors(), jsonapify.errorHandler());

router.put('/:id',
	common.authenticate('token-bearer'),
	common.requirePrivilege('client:edit'),
	common.requirePrivilege(clientTrustPrivilege),
	jsonapify.update(['Client', jsonapify.param('id')]),
	logger.logErrors(), jsonapify.errorHandler());

router.delete('/:id',
	common.authenticate('token-bearer'),
	common.requirePrivilege('client:remove'),
	jsonapify.remove(['Client', jsonapify.param('id')]),
	logger.logErrors(), jsonapify.errorHandler());

function clientTrustPrivilege(req, cb) {
	let id = req.params.id;
	let newTrusted = false;
	if (req.method === 'post' || req.method === 'put')
		newTrusted = _.get(req.body, 'data.attributes.trusted');
	if (!newTrusted) return cb(null, false);
	Client.findById(id, function(err, client) {
		if (err) return cb(err);
		if (!client) return cb(null, false);
		cb(null, client.trusted ? false : 'client:trust');
	});
}

export default router;
<|endoftext|>


<commit_before>/*global setImmediate:true*/
// node 0.8 compat
if (typeof setImmediate === 'undefined') {
    setImmediate = process.nextTick;
}

var fs = require('fs'),
    urlTools = require('urltools'),
    seq = require('seq'),
    _ = require('underscore'),
    passError = require('passerror');

module.exports = function (fileUrl) {
    var matchJSBUrl = fileUrl.match(/^(.*\/)[^\/]*\.jsb([23])$/);

    if (!matchJSBUrl) {
        throw new Error("resolvers.SenchaJsBuilder: Url must end in .jsb2 or .jsb3: " + url);
    }
    var baseUrl = matchJSBUrl[1],
        jsbVersion = parseInt(matchJSBUrl[2], 10),
        jsbBody = JSON.parse(fs.readFileSync(urlTools.fileUrlToFsPath(fileUrl), 'utf-8')),
        pkgIndex = {};

    if (jsbVersion === 2) {
        jsbBody.packages = jsbBody.pkgs;
        delete jsbBody.pkgs;
    }

    jsbBody.builds = jsbBody.builds || [];

    ['packages', 'builds'].forEach(function (sectionName) {
        if (sectionName in jsbBody) {
            jsbBody[sectionName].forEach(function (pkg) {
                if (jsbVersion === 2) {
                    pkg.packages = pkg.pkgDeps;
                    delete pkg.pkgDeps;
                    pkg.target = pkg.file;
                    delete pkg.file;
                    pkg.files = pkg.fileIncludes.map(function (fileInclude) {
                        return {
                            path: fileInclude.path.replace(/^src\/ext-core/, "../ext-core"), // FIXME
                            name: fileInclude.text
                        };
                    });
                    delete pkg.fileIncludes;
                }
                pkgIndex[pkg.name] = pkgIndex[pkg.target] = pkg;
                if ('id' in pkg) {
                    pkgIndex[pkg.id] = pkg;
                }
            });
       }
    });

    function fixupAssetConfig(assetConfig, cb) {
        if (/\bresources\/.*\.css$/.test(assetConfig.url) && /^Ext JS Library [23].\d.\d/.test(jsbBody.licenseText)) {
            // Stupid ExtJS 3 has Css url()s relative to the target paths of their
            // bundles, NOT the source files!
            // Issue reported here: http://www.extjs.com/forum/showthread.php?p=330222
            // Work around it by around by substituting the url()s:

            fs.readFile(urlTools.fileUrlToFsPath(assetConfig.url), 'utf-8', passError(cb, function (src) {
                assetConfig.type = 'Css';
                assetConfig.text = src.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/url\s*\(\s*/g, function () {
                    assetConfig.isDirty = true;
                    assetConfig.fixedUpExtJS = true;
                    return "url(../";
                });
                assetConfig.isResolved = true;
                cb(null, assetConfig);
            }));
        } else {
            setImmediate(function () {
                cb(null, assetConfig);
            });
        }
    }

    function resolveExtBase(pkg, fileNames, cb) {
        seq(fileNames)
            .parMap(function (url) {
                fs.readFile(urlTools.fileUrlToFsPath(url), 'utf-8', this);
            })
            .unflatten()
            .seq(function (texts) {
                cb(null, {
                    type: 'JavaScript',
                    isResolved: true,
                    isDirty: true,
                    fixedUpExtJS: true,
                    text: texts.join("\n"),
                    outgoingRelations: [], // Save the trouble of parsing it to find zero relations
                    url: urlTools.resolveUrl(baseUrl, pkg.target)
                });
            })
            ['catch'](cb);
    }

    function resolvePkg(pkg, cb) {
        var assetConfigs = [],
            fileNames = (pkg.files || []).map(function (fileDef) {
                return urlTools.resolveUrl(baseUrl, fileDef.path + fileDef.name);
            });

        if (pkg.name === 'Ext Base') {
            // Special case for the ext-base.js package, which doesn't work when included as individual files
            return resolveExtBase(pkg, fileNames, cb);
        }

        seq(pkg.packages || [])
            .parMap(function (dependentPkgTargetFileName) {
                if (!pkgIndex[dependentPkgTargetFileName] && dependentPkgTargetFileName === 'ext-base.js') {
                    dependentPkgTargetFileName = 'adapter/ext/ext-base.js'; // pkgDeps bug in ExtJS 3.2
                }
                resolvePkg(pkgIndex[dependentPkgTargetFileName], this);
            })
            .seqEach(function (resolvedAssetConfigs) {
                if (_.isArray(resolvedAssetConfigs)) {
                    Array.prototype.push.apply(assetConfigs, resolvedAssetConfigs);
                } else {
                    assetConfigs.push(resolvedAssetConfigs);
                }
                this();
            })
            .set(fileNames)
            .parMap(function (url) {
                var assetConfig = {
                    url: url
                };
                if (/\.js$/.test(url)) {
                    assetConfig.outgoingRelations = [];
                }
                fixupAssetConfig(assetConfig, this);
            })
            .unflatten()
            .seq(function (fixedUpAssetConfigs) {
                cb(null, assetConfigs.concat(fixedUpAssetConfigs));
            })
            ['catch'](cb);
    }

    return function senchaJsBuilder(assetConfig, fromUrl, cb) {
        var labelRelativePath = assetConfig.url.replace(/^[^:]*:/, '');
        if (labelRelativePath in pkgIndex) {
            resolvePkg(pkgIndex[labelRelativePath], cb);
        } else {
            fixupAssetConfig({url: urlTools.resolveUrl(baseUrl, labelRelativePath)}, cb);
        }
    };
};
<commit_msg>lib/resolvers/senchaJsBuilder.js: fix jslint errors<commit_after>/*global setImmediate:true*/
// node 0.8 compat
if (typeof setImmediate === 'undefined') {
    setImmediate = process.nextTick;
}

var fs = require('fs'),
    urlTools = require('urltools'),
    seq = require('seq'),
    _ = require('underscore'),
    passError = require('passerror');

module.exports = function (fileUrl) {
    var matchJSBUrl = fileUrl.match(/^(.*\/)[^\/]*\.jsb([23])$/);

    if (!matchJSBUrl) {
        throw new Error('resolvers.SenchaJsBuilder: Url must end in .jsb2 or .jsb3: ' + fileUrl);
    }
    var baseUrl = matchJSBUrl[1],
        jsbVersion = parseInt(matchJSBUrl[2], 10),
        jsbBody = JSON.parse(fs.readFileSync(urlTools.fileUrlToFsPath(fileUrl), 'utf-8')),
        pkgIndex = {};

    if (jsbVersion === 2) {
        jsbBody.packages = jsbBody.pkgs;
        delete jsbBody.pkgs;
    }

    jsbBody.builds = jsbBody.builds || [];

    ['packages', 'builds'].forEach(function (sectionName) {
        if (sectionName in jsbBody) {
            jsbBody[sectionName].forEach(function (pkg) {
                if (jsbVersion === 2) {
                    pkg.packages = pkg.pkgDeps;
                    delete pkg.pkgDeps;
                    pkg.target = pkg.file;
                    delete pkg.file;
                    pkg.files = pkg.fileIncludes.map(function (fileInclude) {
                        return {
                            path: fileInclude.path.replace(/^src\/ext-core/, '../ext-core'), // FIXME
                            name: fileInclude.text
                        };
                    });
                    delete pkg.fileIncludes;
                }
                pkgIndex[pkg.name] = pkgIndex[pkg.target] = pkg;
                if ('id' in pkg) {
                    pkgIndex[pkg.id] = pkg;
                }
            });
        }
    });

    function fixupAssetConfig(assetConfig, cb) {
        if (/\bresources\/.*\.css$/.test(assetConfig.url) && /^Ext JS Library [23].\d.\d/.test(jsbBody.licenseText)) {
            // Stupid ExtJS 3 has Css url()s relative to the target paths of their
            // bundles, NOT the source files!
            // Issue reported here: http://www.extjs.com/forum/showthread.php?p=330222
            // Work around it by around by substituting the url()s:

            fs.readFile(urlTools.fileUrlToFsPath(assetConfig.url), 'utf-8', passError(cb, function (src) {
                assetConfig.type = 'Css';
                assetConfig.text = src.replace(/\/\*[\s\S]*?\*\//g, ' ').replace(/url\s*\(\s*/g, function () {
                    assetConfig.isDirty = true;
                    assetConfig.fixedUpExtJS = true;
                    return 'url(../';
                });
                assetConfig.isResolved = true;
                cb(null, assetConfig);
            }));
        } else {
            setImmediate(function () {
                cb(null, assetConfig);
            });
        }
    }

    function resolveExtBase(pkg, fileNames, cb) {
        seq(fileNames)
            .parMap(function (url) {
                fs.readFile(urlTools.fileUrlToFsPath(url), 'utf-8', this);
            })
            .unflatten()
            .seq(function (texts) {
                cb(null, {
                    type: 'JavaScript',
                    isResolved: true,
                    isDirty: true,
                    fixedUpExtJS: true,
                    text: texts.join('\n'),
                    outgoingRelations: [], // Save the trouble of parsing it to find zero relations
                    url: urlTools.resolveUrl(baseUrl, pkg.target)
                });
            })['catch'](cb);
    }

    function resolvePkg(pkg, cb) {
        var assetConfigs = [],
            fileNames = (pkg.files || []).map(function (fileDef) {
                return urlTools.resolveUrl(baseUrl, fileDef.path + fileDef.name);
            });

        if (pkg.name === 'Ext Base') {
            // Special case for the ext-base.js package, which doesn't work when included as individual files
            return resolveExtBase(pkg, fileNames, cb);
        }

        seq(pkg.packages || [])
            .parMap(function (dependentPkgTargetFileName) {
                if (!pkgIndex[dependentPkgTargetFileName] && dependentPkgTargetFileName === 'ext-base.js') {
                    dependentPkgTargetFileName = 'adapter/ext/ext-base.js'; // pkgDeps bug in ExtJS 3.2
                }
                resolvePkg(pkgIndex[dependentPkgTargetFileName], this);
            })
            .seqEach(function (resolvedAssetConfigs) {
                if (_.isArray(resolvedAssetConfigs)) {
                    Array.prototype.push.apply(assetConfigs, resolvedAssetConfigs);
                } else {
                    assetConfigs.push(resolvedAssetConfigs);
                }
                this();
            })
            .set(fileNames)
            .parMap(function (url) {
                var assetConfig = {
                    url: url
                };
                if (/\.js$/.test(url)) {
                    assetConfig.outgoingRelations = [];
                }
                fixupAssetConfig(assetConfig, this);
            })
            .unflatten()
            .seq(function (fixedUpAssetConfigs) {
                cb(null, assetConfigs.concat(fixedUpAssetConfigs));
            })['catch'](cb);
    }

    return function senchaJsBuilder(assetConfig, fromUrl, cb) {
        var labelRelativePath = assetConfig.url.replace(/^[^:]*:/, '');
        if (labelRelativePath in pkgIndex) {
            resolvePkg(pkgIndex[labelRelativePath], cb);
        } else {
            fixupAssetConfig({url: urlTools.resolveUrl(baseUrl, labelRelativePath)}, cb);
        }
    };
};
<|endoftext|>


<commit_before>/*global logger*/
/*
    DataviewLoader
    ========================

    @file      : DataviewLoader.js
    @version   : 1.3.1
    @author    : JvdGraaf
    @date      : Mon, 24 Apr 2017 15:02:42 GMT
    @copyright : Appronto
    @license   : Apache2

    Documentation
    ========================
    Describe your widget here.
*/

// Required module list. Remove unnecessary modules, you can always get them back from the boilerplate.
define([
  "dojo/_base/declare",
  "mxui/widget/_WidgetBase",
  "dijit/_TemplatedMixin",

  "mxui/dom",
  "dojo/dom",
  "dojo/dom-style",
  "dojo/dom-class",
  "dojo/_base/lang",
  "dojo/_base/event",

  "dojo/text!DataviewLoader/widget/template/DataviewLoader.html"
], function (declare, _WidgetBase, _TemplatedMixin, dom, dojoDom, dojoStyle, dojoClass, dojoLang, dojoEvent, widgetTemplate) {
    "use strict";

    // Declare widget's prototype.
    return declare("DataviewLoader.widget.DataviewLoader", [_WidgetBase, _TemplatedMixin], {
        // _TemplatedMixin will create our dom node using this HTML template.
        templateString: widgetTemplate,

        // DOM elements
        divContent: null,
        divLoader: null,

        // Internal variables. Non-primitives created in the prototype are shared between all widget instances.
        _handles: null,
        _contextObj: null,
        _loadingStarted: false,
        _pageInitiated: false,
        _form: null,
        active: true,
        prevForm : null,

        // dojo.declare.constructor is called to construct the widget instance. Implement to initialize non-primitive properties.
        constructor: function () {
            //logger.debug(this.id + ".constructor");
            this._handles = [];
        },

        // dijit._WidgetBase.postCreate is called after constructing the widget. Implement to do extra setup work.
        postCreate: function () {
            logger.debug(this.id + ".postCreate");

            this._updateRendering();
            this._setupEvents();
        },

        // mxui.widget._WidgetBase.update is called when context is changed or initialized. Implement to re-render and / or fetch data.
        update: function (obj, callback) {
            if(this._contextObj !== obj){
                console.log(this.id + ".update on new object");
                this._loadingStarted = false;
                this._pageInitiated = false;

                this._contextObj = obj;
                this._resetSubscriptions();
                this.   _updateRendering(callback); // We're passing the callback to updateRendering to be called after DOM-manipulation
            } else {
                // The callback, coming from update, needs to be executed, to let the page know it finished rendering
                this._executeCallback(callback, "update");
            }
        },

        // mxui.widget._WidgetBase.enable is called when the widget should enable editing. Implement to enable editing if widget is input widget.
        enable: function () {
            logger.debug(this.id + ".enable");
        },

        // mxui.widget._WidgetBase.enable is called when the widget should disable editing. Implement to disable editing if widget is input widget.
        disable: function () {
            logger.debug(this.id + ".disable");
        },

        // mxui.widget._WidgetBase.resize is called when the page's layout is recalculated. Implement to do sizing calculations. Prefer using CSS instead.
        resize: function (box) {
            console.log(this.id + ".resize");
            // TODO: How to handle tabs and conditional visibility
            if (this.domNode.offsetParent !== null && this.visibilityCheck) {
                this._loadAndShowcontent();
            }
        },

        // mxui.widget._WidgetBase.uninitialize is called when the widget is destroyed. Implement to do special tear-down work.
        uninitialize: function () {
            logger.debug(this.id + ".uninitialize");
            // Clean up listeners, helper objects, etc. There is no need to remove listeners added with this.connect / this.subscribe / this.own.
            this.active = false;
        },

        // We want to stop events on a mobile device
        _stopBubblingEventOnMobile: function (e) {
            logger.debug(this.id + "._stopBubblingEventOnMobile");
            if (typeof document.ontouchstart !== "undefined") {
                dojoEvent.stop(e);
            }
        },

        // Attach events to HTML dom elements
        _setupEvents: function () {
            //logger.debug(this.id + "._setupEvents");
        },

        // Rerender the interface.
        _updateRendering: function (callback) {
            logger.debug(this.id + "._updateRendering");

            if (this._contextObj) {
                dojoStyle.set(this.divContent, "display", "none");
                dojoStyle.set(this.divLoader, "display", "block");

                if(this.fadeContent){
                    dojoClass.add(this.divContent, "loaderfade");
                }

                if (this.domNode.offsetParent !== null || !this.visibilityCheck) {
                    this._loadAndShowcontent();
                }
            }

            // The callback, coming from update, needs to be executed, to let the page know it finished rendering
            this._executeCallback(callback, "_updateRendering");
        },

        _loadAndShowcontent: function () {
            logger.debug(this.id + "._loadAndShowcontent");
            if(this._loadingStarted == false){
                this._loadingStarted = true;
                if (this._contextObj && this.loadingMF) {
                    this._execMf(this.loadingMF, this._contextObj.getGuid(), this._processMicroflowCallback, this._processMicroflowFailure);
                } else if (this._contextObj) {
                    this._setPage(this._contextObj);
                }
            }
        },

        _processMicroflowCallback: function (objs) {
            logger.debug(this.id + '._processMicroflowCallback');
            if (this.active) {
                if(this.asyncCall)
                    this._setPage(this._contextObj);
                else
                    this._setPage(objs[0]);
            } else {
                 console.info(this.id + "._processMicroflowCallback Skip loading because widget is destroyed.");
            }
        },
        _processMicroflowFailure: function (){
            if(this.errorHandling){
                if(this._pageInitiated)
                    this._form.close();
                this._pageInitiated = false;
                this.divContent.innerHTML= "

"+this.errorText+"

";

                this._showPage();
            }
        },

        _setPage: function (pageObj) {
            logger.debug(this.id + '._setPage');

            if(this._pageInitiated) {
                if (this._loadingStarted) {
                    this._showPage();
                } else {
                    console.log(this.id + "_setPage skip because already set.");
                }
            } else {
                this._pageInitiated = true;
                this.divContent.innerHTML= "";
                console.log(this.id + "_setPage");
                if (pageObj) {
                    var pageContext = new mendix.lib.MxContext();
                    pageContext.setTrackObject(pageObj);
                    this._form = mx.ui.openForm(this.pageContent, {
                                    context: pageContext,
                                    location: "node",
                                    domNode: this.divContent,
                                    callback: dojoLang.hitch(this, this._showPage),
                                    error: function (error) {
                                        console.log(error.description);
                                    }
                                });
                } else {
                    this._form = mx.ui.openForm(this.pageContent, {
                                    location: "node",
                                    domNode: this.divContent,
                                    callback: dojoLang.hitch(this, this._showPage),
                                    error: function (error) {
                                        console.log(error.description);
                                    }
                                });
                }
            }
        },

        _showPage: function (mxform) {
            logger.debug(this.id + "._showPage on form");

            if(this.prevForm != null){
                this.prevForm.destroy();
            }
            this.prevForm = mxform;

            dojoStyle.set(this.divContent, "display", "block");
            dojoStyle.set(this.divLoader, "display", "none");

            this._loadingStarted = false;
        },

        // Reset subscriptions.
        _resetSubscriptions: function () {
            logger.debug(this.id + "._resetSubscriptions");
            // Release handles on previous object, if any.
            this.unsubscribeAll();

            // When a mendix object exists create subscribtions.
            if (this._contextObj && (this.refreshAction === "Object" || this.refreshAction === "Attribute")) {
                console.log(this.id + "._resetSubscriptions setup refresh handler: " + this.refreshAction);
                this.subscribe({
                    guid: this._contextObj.getGuid(),
                    callback: dojoLang.hitch(this, function (guid) {
                        if(this._loadingStarted == false){
                            if(this.refreshAction == "Attribute" && this.refreshtAttr && this._contextObj.get(this.refreshtAttr)){
                                console.log(this.id + ".Refresh triggered on attribute change.");
                                this._updateRendering();
                            } else if(this.refreshAction == "Object") {
                                console.log(this.id + ".Refresh triggered on object change.");
                                this._updateRendering();
                            }
                        } else {
                            console.log(this.id + ".Refresh skip because of loading started.");
                        }
                    })
                });
            }
        },

        _execMf: function (mf, guid, cb, cbfailure) {
            logger.debug(this.id + "._execMf" + (mf ? ": " + mf : ""));
            if (mf && guid) {
                mx.ui.action(mf, {
                    async : this.asyncCall,
                    params: {
                        applyto: "selection",
                        guids: [guid]
                    },
                    callback: (cb && typeof cb === "function" ? dojoLang.hitch(this, cb) : null),
                    error: (cbfailure && typeof cbfailure === "function" ? dojoLang.hitch(this, cbfailure) : null)
                }, this);
            }
        },

        _executeCallback: function (cb, from) {
            logger.debug(this.id + "._executeCallback" + (from ? " from " + from : ""));
            if (cb && typeof cb === "function") {
                cb();
            }
        }
    });
});

require(["DataviewLoader/widget/DataviewLoader"]);
<commit_msg>Update DataviewLoader.js<commit_after>/*global logger*/
/*
    DataviewLoader
    ========================

    @file      : DataviewLoader.js
    @version   : 1.3.1
    @author    : JvdGraaf
    @date      : Mon, 24 Apr 2017 15:02:42 GMT
    @copyright : Appronto
    @license   : Apache2

    Documentation
    ========================
    Describe your widget here.
*/

// Required module list. Remove unnecessary modules, you can always get them back from the boilerplate.
define([
  "dojo/_base/declare",
  "mxui/widget/_WidgetBase",
  "dijit/_TemplatedMixin",

  "mxui/dom",
  "dojo/dom",
  "dojo/dom-style",
  "dojo/dom-class",
  "dojo/_base/lang",
  "dojo/_base/event",

  "dojo/text!DataviewLoader/widget/template/DataviewLoader.html"
], function (declare, _WidgetBase, _TemplatedMixin, dom, dojoDom, dojoStyle, dojoClass, dojoLang, dojoEvent, widgetTemplate) {
    "use strict";

    // Declare widget's prototype.
    return declare("DataviewLoader.widget.DataviewLoader", [_WidgetBase, _TemplatedMixin], {
        // _TemplatedMixin will create our dom node using this HTML template.
        templateString: widgetTemplate,

        // DOM elements
        divContent: null,
        divLoader: null,

        // Internal variables. Non-primitives created in the prototype are shared between all widget instances.
        _handles: null,
        _contextObj: null,
        _loadingStarted: false,
        _pageInitiated: false,
        _form: null,
        active: true,
        prevForm : null,

        // dojo.declare.constructor is called to construct the widget instance. Implement to initialize non-primitive properties.
        constructor: function () {
            //logger.debug(this.id + ".constructor");
            this._handles = [];
        },

        // dijit._WidgetBase.postCreate is called after constructing the widget. Implement to do extra setup work.
        postCreate: function () {
            logger.debug(this.id + ".postCreate");

            this._updateRendering();
            this._setupEvents();
        },

        // mxui.widget._WidgetBase.update is called when context is changed or initialized. Implement to re-render and / or fetch data.
        update: function (obj, callback) {
            if(this._contextObj !== obj){
                console.log(this.id + ".update on new object");
                this._loadingStarted = false;
                this._pageInitiated = false;

                this._contextObj = obj;
                this._resetSubscriptions();
                this.   _updateRendering(callback); // We're passing the callback to updateRendering to be called after DOM-manipulation
            } else {
                // The callback, coming from update, needs to be executed, to let the page know it finished rendering
                this._executeCallback(callback, "update");
            }
        },

        // mxui.widget._WidgetBase.enable is called when the widget should enable editing. Implement to enable editing if widget is input widget.
        enable: function () {
            logger.debug(this.id + ".enable");
        },

        // mxui.widget._WidgetBase.enable is called when the widget should disable editing. Implement to disable editing if widget is input widget.
        disable: function () {
            logger.debug(this.id + ".disable");
        },

        // mxui.widget._WidgetBase.resize is called when the page's layout is recalculated. Implement to do sizing calculations. Prefer using CSS instead.
        resize: function (box) {
            console.log(this.id + ".resize");
            // TODO: How to handle tabs and conditional visibility
            if (this.domNode.offsetParent !== null && this.visibilityCheck) {
                this._loadAndShowcontent();
            }
        },

        // mxui.widget._WidgetBase.uninitialize is called when the widget is destroyed. Implement to do special tear-down work.
        uninitialize: function () {
            logger.debug(this.id + ".uninitialize");
            // Clean up listeners, helper objects, etc. There is no need to remove listeners added with this.connect / this.subscribe / this.own.
            this.active = false;
        },

        // We want to stop events on a mobile device
        _stopBubblingEventOnMobile: function (e) {
            logger.debug(this.id + "._stopBubblingEventOnMobile");
            if (typeof document.ontouchstart !== "undefined") {
                dojoEvent.stop(e);
            }
        },

        // Attach events to HTML dom elements
        _setupEvents: function () {
            //logger.debug(this.id + "._setupEvents");
        },

        // Rerender the interface.
        _updateRendering: function (callback) {
            logger.debug(this.id + "._updateRendering");

            if (this._contextObj) {
                dojoStyle.set(this.divContent, "display", "none");
                dojoStyle.set(this.divLoader, "display", "block");

                if(this.fadeContent){
                    dojoClass.add(this.divContent, "loaderfade");
                }

                if (this.domNode.offsetParent !== null || !this.visibilityCheck) {
                    this._loadAndShowcontent();
                }
            }

            // The callback, coming from update, needs to be executed, to let the page know it finished rendering
            this._executeCallback(callback, "_updateRendering");
        },

        _loadAndShowcontent: function () {
            logger.debug(this.id + "._loadAndShowcontent");
            if(this._loadingStarted == false){
                this._loadingStarted = true;
                if (this._contextObj && this.loadingMF) {
                    this._execMf(this.loadingMF, this._contextObj.getGuid(), this._processMicroflowCallback, this._processMicroflowFailure);
                } else if (this._contextObj) {
                    this._setPage(this._contextObj);
                }
            }
        },

        _processMicroflowCallback: function (objs) {
            logger.debug(this.id + '._processMicroflowCallback');
            if (this.active) {
                if(this.asyncCall)
                    this._setPage(this._contextObj);
                else
                    this._setPage(objs[0]);
            } else {
                 console.info(this.id + "._processMicroflowCallback Skip loading because widget is destroyed.");
            }
        },
        _processMicroflowFailure: function (){
            if(this.errorHandling){
                if(this._pageInitiated)
                    this._form.close();
                this._pageInitiated = false;
                this.divContent.innerHTML= "

"+this.errorText+"

";

                this._showPage();
            }
        },

        _setPage: function (pageObj) {
            logger.debug(this.id + '._setPage');

            if(this._pageInitiated) {
                if (this._loadingStarted) {
                    this._showPage();
                } else {
                    console.log(this.id + "_setPage skip because already set.");
                }
            } else {
                this._pageInitiated = true;
                this.divContent.innerHTML= "";
                console.log(this.id + "_setPage");
                if (pageObj) {
                    var pageContext = new mendix.lib.MxContext();
                    pageContext.setTrackObject(pageObj);
                    this._form = mx.ui.openForm(this.pageContent, {
                                    context: pageContext,
                                    location: "node",
                                    domNode: this.divContent,
                                    callback: dojoLang.hitch(this, this._showPage),
                                    error: function (error) {
                                        console.log(error.description);
                                    }
                                });
                } else {
                    this._form = mx.ui.openForm(this.pageContent, {
                                    location: "node",
                                    domNode: this.divContent,
                                    callback: dojoLang.hitch(this, this._showPage),
                                    error: function (error) {
                                        console.log(error.description);
                                    }
                                });
                }
            }
        },

        _showPage: function (mxform) {
            logger.debug(this.id + "._showPage on form");

            if(this.prevForm != null && mxform != null){
                this.prevForm.destroy();
            }
            this.prevForm = mxform;

            dojoStyle.set(this.divContent, "display", "block");
            dojoStyle.set(this.divLoader, "display", "none");

            this._loadingStarted = false;
        },

        // Reset subscriptions.
        _resetSubscriptions: function () {
            logger.debug(this.id + "._resetSubscriptions");
            // Release handles on previous object, if any.
            this.unsubscribeAll();

            // When a mendix object exists create subscribtions.
            if (this._contextObj && (this.refreshAction === "Object" || this.refreshAction === "Attribute")) {
                console.log(this.id + "._resetSubscriptions setup refresh handler: " + this.refreshAction);
                this.subscribe({
                    guid: this._contextObj.getGuid(),
                    callback: dojoLang.hitch(this, function (guid) {
                        if(this._loadingStarted == false){
                            if(this.refreshAction == "Attribute" && this.refreshtAttr && this._contextObj.get(this.refreshtAttr)){
                                console.log(this.id + ".Refresh triggered on attribute change.");
                                this._updateRendering();
                            } else if(this.refreshAction == "Object") {
                                console.log(this.id + ".Refresh triggered on object change.");
                                this._updateRendering();
                            }
                        } else {
                            console.log(this.id + ".Refresh skip because of loading started.");
                        }
                    })
                });
            }
        },

        _execMf: function (mf, guid, cb, cbfailure) {
            logger.debug(this.id + "._execMf" + (mf ? ": " + mf : ""));
            if (mf && guid) {
                mx.ui.action(mf, {
                    async : this.asyncCall,
                    params: {
                        applyto: "selection",
                        guids: [guid]
                    },
                    callback: (cb && typeof cb === "function" ? dojoLang.hitch(this, cb) : null),
                    error: (cbfailure && typeof cbfailure === "function" ? dojoLang.hitch(this, cbfailure) : null)
                }, this);
            }
        },

        _executeCallback: function (cb, from) {
            logger.debug(this.id + "._executeCallback" + (from ? " from " + from : ""));
            if (cb && typeof cb === "function") {
                cb();
            }
        }
    });
});

require(["DataviewLoader/widget/DataviewLoader"]);
<|endoftext|>


<commit_before>/**
* CONFIDENTIAL
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
* This is unpublished proprietary source code of Red Hat.
**/
'use strict';

angular.module('wfm-mobile.workorders', [
  'ui.router'
])

.config(function($stateProvider) {
  $stateProvider
    .state('app.workorders', {
        url: '/workorders',
        templateUrl: 'app/workorder/workorder-list.tpl.html',
        controller: 'WorkordersCtrl as ctrl',
        resolve: {
          workorders: function(workorderManager) {
            return workorderManager.list();
          },
          resultMap: function(resultManager) {
            return resultManager.list()
            .then(function(results) {
              var map = {};
              results.forEach(function(result) {
                map[result.workorderId] = result;
              });
              return map;
            })
          }
        }
      })
})

.controller('WorkordersCtrl', function($scope, $filter, workorderManager, mediator, workorders, resultMap) {
  var self = this;
  self.workorders = workorders;
  self.resultMap = resultMap;
  mediator.subscribeForScope('wfm:sync:record_delta_received:workorders', $scope, function(notification) {
    console.log(notification);
     workorderManager.list().then(function(workorders) {
       self.workorders = workorders;
     })
  })
})

;

module.exports = 'wfm-mobile.workorders';
<commit_msg>Cleared the workorder list on logout<commit_after>/**
* CONFIDENTIAL
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
* This is unpublished proprietary source code of Red Hat.
**/
'use strict';

angular.module('wfm-mobile.workorders', [
  'ui.router'
])

.config(function($stateProvider) {
  $stateProvider
    .state('app.workorders', {
        url: '/workorders',
        templateUrl: 'app/workorder/workorder-list.tpl.html',
        controller: 'WorkordersCtrl as ctrl',
        resolve: {
          workorders: function(workorderManager) {
            return workorderManager.list();
          },
          resultMap: function(resultManager) {
            return resultManager.list()
            .then(function(results) {
              var map = {};
              results.forEach(function(result) {
                map[result.workorderId] = result;
              });
              return map;
            })
          }
        }
      })
})

.controller('WorkordersCtrl', function($scope, $filter, workorderManager, mediator, workorders, resultMap) {
  var self = this;
  self.workorders = workorders;
  self.resultMap = resultMap;
  mediator.subscribeForScope('wfm:auth:profile:change', $scope, function(profileData) {
    if (!profileData) {
      self.workorders = [];
    }
  })
  mediator.subscribeForScope('wfm:sync:record_delta_received:workorders', $scope, function(notification) {
    console.log(notification);
     workorderManager.list().then(function(workorders) {
       self.workorders = workorders;
     })
  })
})

;

module.exports = 'wfm-mobile.workorders';
<|endoftext|>


<commit_before>import cornerstone from 'cornerstone-core';
import { redux } from 'ohif-core';
import store from './../store/';

const { setToolActive } = redux.actions;

const actions = {
  rotateViewport: ({ viewports, rotation }) => {
    const enabledElement = _getActiveViewportEnabledElement(
      viewports.viewportSpecificData,
      viewports.activeViewportIndex
    );

    if (enabledElement) {
      let viewport = cornerstone.getViewport(enabledElement);
      viewport.rotation += rotation;
      cornerstone.setViewport(enabledElement, viewport);
    }
  },
  flipViewportHorizontal: ({ viewports }) => {
    const enabledElement = _getActiveViewportEnabledElement(
      viewports.viewportSpecificData,
      viewports.activeViewportIndex
    );

    if (enabledElement) {
      let viewport = cornerstone.getViewport(enabledElement);
      viewport.hflip = !viewport.hflip;
      cornerstone.setViewport(enabledElement, viewport);
    }
  },
  flipViewportVertical: ({ viewports }) => {
    const enabledElement = _getActiveViewportEnabledElement(
      viewports.viewportSpecificData,
      viewports.activeViewportIndex
    );

    if (enabledElement) {
      let viewport = cornerstone.getViewport(enabledElement);
      viewport.vflip = !viewport.vflip;
      cornerstone.setViewport(enabledElement, viewport);
    }
  },
  scaleViewport: ({ viewports, direction }) => {
    const enabledElement = _getActiveViewportEnabledElement(
      viewports.viewportSpecificData,
      viewports.activeViewportIndex
    );
    const step = direction * 0.15;

    if (enabledElement) {
      if (step) {
        let viewport = cornerstone.getViewport(enabledElement);
        viewport.scale += step;
        cornerstone.setViewport(enabledElement, viewport);
      } else {
        cornerstone.fitToWindow(enabledElement);
      }
    }
  },
  resetViewport: ({ viewports }) => {
    const enabledElement = _getActiveViewportEnabledElement(
      viewports.viewportSpecificData,
      viewports.activeViewportIndex
    );

    if (enabledElement) {
      cornerstone.reset(enabledElement);
    }
  },
  invertViewport: ({ viewports }) => {
    const enabledElement = _getActiveViewportEnabledElement(
      viewports.viewportSpecificData,
      viewports.activeViewportIndex
    );

    if (enabledElement) {
      let viewport = cornerstone.getViewport(enabledElement);
      viewport.invert = !viewport.invert;
      cornerstone.setViewport(enabledElement, viewport);
    }
  },
  // This has a weird hard dependency on the tools that are available as toolbar
  // buttons. You can see this in `ohif-core/src/redux/reducers/tools.js`
  // the `toolName` needs to equal the button's `command` property.
  // NOTE: It would be nice if `hotkeys` could set this, instead of creating a command per tool
  setCornerstoneToolActive: ({ toolName }) => {
    store.dispatch(setToolActive(toolName));
  },
  updateViewportDisplaySet: ({ direction }) => {
    // TODO
    console.warn('updateDisplaySet: ', direction);
  },
  clearAnnotations: () => {
    console.warn('clearAnnotations: not yet implemented');
    // const toolState =
    //   cornerstoneTools.globalImageIdSpecificToolStateManager.toolState;
    // if (!toolState) return;
    // Object.keys(toolState).forEach(imageId => {
    //   if (!cornerstoneImageId || cornerstoneImageId === imageId)
    //     delete toolState[imageId];
    // });
  },
};

const definitions = {
  rotateViewportCW: {
    commandFn: actions.rotateViewport,
    storeContexts: ['viewports'],
    options: { rotation: 90 },
  },
  rotateViewportCCW: {
    commandFn: actions.rotateViewport,
    storeContexts: ['viewports'],
    options: { rotation: -90 },
  },
  invertViewport: {
    commandFn: actions.invertViewport,
    storeContexts: ['viewports'],
    options: {},
  },
  flipViewportVertical: {
    commandFn: actions.flipViewportVertical,
    storeContexts: ['viewports'],
    options: {},
  },
  flipViewportHorizontal: {
    commandFn: actions.flipViewportHorizontal,
    storeContexts: ['viewports'],
    options: {},
  },
  scaleUpViewport: {
    keys: '',
    commandFn: actions.scaleViewport,
    storeContexts: ['viewports'],
    options: { direction: 1 },
  },
  scaleDownViewport: {
    keys: '',
    commandFn: actions.scaleViewport,
    storeContexts: ['viewports'],
    options: { direction: -1 },
  },
  fitViewportToWindow: {
    commandFn: actions.scaleViewport,
    storeContexts: ['viewports'],
    options: { direction: 0 },
  },
  resetViewport: {
    commandFn: actions.resetViewport,
    storeContexts: ['viewports'],
    options: {},
  },
  // TODO: Clear Annotations
  // TODO: Next/Previous image
  // TODO: First/Last image
  // Next/Previous series/DisplaySet
  nextViewportDisplaySet: {
    commandFn: actions.updateViewportDisplaySet,
    storeContexts: [],
    options: { direction: 1 },
  },
  previousViewportDisplaySet: {
    commandFn: actions.updateViewportDisplaySet,
    storeContexts: [],
    options: { direction: 1 },
  },
  // TOOLS
  setZoomTool: {
    commandFn: actions.setCornerstoneToolActive,
    storeContexts: [],
    options: { toolName: 'Zoom' },
  },
};

/**
 * Grabs `dom` reference for the enabledElement of
 * the active viewport
 */
function _getActiveViewportEnabledElement(viewports, activeIndex) {
  const activeViewport = viewports[activeIndex] || {};
  return activeViewport.dom;
}

export default definitions;
<commit_msg>fix: command direction for previousViewportDisplaySet<commit_after>import cornerstone from 'cornerstone-core';
import { redux } from 'ohif-core';
import store from './../store/';

const { setToolActive } = redux.actions;

const actions = {
  rotateViewport: ({ viewports, rotation }) => {
    const enabledElement = _getActiveViewportEnabledElement(
      viewports.viewportSpecificData,
      viewports.activeViewportIndex
    );

    if (enabledElement) {
      let viewport = cornerstone.getViewport(enabledElement);
      viewport.rotation += rotation;
      cornerstone.setViewport(enabledElement, viewport);
    }
  },
  flipViewportHorizontal: ({ viewports }) => {
    const enabledElement = _getActiveViewportEnabledElement(
      viewports.viewportSpecificData,
      viewports.activeViewportIndex
    );

    if (enabledElement) {
      let viewport = cornerstone.getViewport(enabledElement);
      viewport.hflip = !viewport.hflip;
      cornerstone.setViewport(enabledElement, viewport);
    }
  },
  flipViewportVertical: ({ viewports }) => {
    const enabledElement = _getActiveViewportEnabledElement(
      viewports.viewportSpecificData,
      viewports.activeViewportIndex
    );

    if (enabledElement) {
      let viewport = cornerstone.getViewport(enabledElement);
      viewport.vflip = !viewport.vflip;
      cornerstone.setViewport(enabledElement, viewport);
    }
  },
  scaleViewport: ({ viewports, direction }) => {
    const enabledElement = _getActiveViewportEnabledElement(
      viewports.viewportSpecificData,
      viewports.activeViewportIndex
    );
    const step = direction * 0.15;

    if (enabledElement) {
      if (step) {
        let viewport = cornerstone.getViewport(enabledElement);
        viewport.scale += step;
        cornerstone.setViewport(enabledElement, viewport);
      } else {
        cornerstone.fitToWindow(enabledElement);
      }
    }
  },
  resetViewport: ({ viewports }) => {
    const enabledElement = _getActiveViewportEnabledElement(
      viewports.viewportSpecificData,
      viewports.activeViewportIndex
    );

    if (enabledElement) {
      cornerstone.reset(enabledElement);
    }
  },
  invertViewport: ({ viewports }) => {
    const enabledElement = _getActiveViewportEnabledElement(
      viewports.viewportSpecificData,
      viewports.activeViewportIndex
    );

    if (enabledElement) {
      let viewport = cornerstone.getViewport(enabledElement);
      viewport.invert = !viewport.invert;
      cornerstone.setViewport(enabledElement, viewport);
    }
  },
  // This has a weird hard dependency on the tools that are available as toolbar
  // buttons. You can see this in `ohif-core/src/redux/reducers/tools.js`
  // the `toolName` needs to equal the button's `command` property.
  // NOTE: It would be nice if `hotkeys` could set this, instead of creating a command per tool
  setCornerstoneToolActive: ({ toolName }) => {
    store.dispatch(setToolActive(toolName));
  },
  updateViewportDisplaySet: ({ direction }) => {
    // TODO
    console.warn('updateDisplaySet: ', direction);
  },
  clearAnnotations: () => {
    console.warn('clearAnnotations: not yet implemented');
    // const toolState =
    //   cornerstoneTools.globalImageIdSpecificToolStateManager.toolState;
    // if (!toolState) return;
    // Object.keys(toolState).forEach(imageId => {
    //   if (!cornerstoneImageId || cornerstoneImageId === imageId)
    //     delete toolState[imageId];
    // });
  },
};

const definitions = {
  rotateViewportCW: {
    commandFn: actions.rotateViewport,
    storeContexts: ['viewports'],
    options: { rotation: 90 },
  },
  rotateViewportCCW: {
    commandFn: actions.rotateViewport,
    storeContexts: ['viewports'],
    options: { rotation: -90 },
  },
  invertViewport: {
    commandFn: actions.invertViewport,
    storeContexts: ['viewports'],
    options: {},
  },
  flipViewportVertical: {
    commandFn: actions.flipViewportVertical,
    storeContexts: ['viewports'],
    options: {},
  },
  flipViewportHorizontal: {
    commandFn: actions.flipViewportHorizontal,
    storeContexts: ['viewports'],
    options: {},
  },
  scaleUpViewport: {
    keys: '',
    commandFn: actions.scaleViewport,
    storeContexts: ['viewports'],
    options: { direction: 1 },
  },
  scaleDownViewport: {
    keys: '',
    commandFn: actions.scaleViewport,
    storeContexts: ['viewports'],
    options: { direction: -1 },
  },
  fitViewportToWindow: {
    commandFn: actions.scaleViewport,
    storeContexts: ['viewports'],
    options: { direction: 0 },
  },
  resetViewport: {
    commandFn: actions.resetViewport,
    storeContexts: ['viewports'],
    options: {},
  },
  // TODO: Clear Annotations
  // TODO: Next/Previous image
  // TODO: First/Last image
  // Next/Previous series/DisplaySet
  nextViewportDisplaySet: {
    commandFn: actions.updateViewportDisplaySet,
    storeContexts: [],
    options: { direction: 1 },
  },
  previousViewportDisplaySet: {
    commandFn: actions.updateViewportDisplaySet,
    storeContexts: [],
    options: { direction: -1 },
  },
  // TOOLS
  setZoomTool: {
    commandFn: actions.setCornerstoneToolActive,
    storeContexts: [],
    options: { toolName: 'Zoom' },
  },
};

/**
 * Grabs `dom` reference for the enabledElement of
 * the active viewport
 */
function _getActiveViewportEnabledElement(viewports, activeIndex) {
  const activeViewport = viewports[activeIndex] || {};
  return activeViewport.dom;
}

export default definitions;
<|endoftext|>


<commit_before>/**
 * Created by Nightpaws on 31/01/2016.
 */
var app = function(){
    //load config, filesystem, express router,
    var config = require('./../config'),
        fs = require('fs'),
        bodyParser = require('body-parser'),
        express = require('express'),
        csv = require('./csv');
    var app = express();//set up express

    //Database link
    var mongoose = require('mongoose');
    mongoose.connect(config.mongoDB.string);
    var csvHeaders = {
        classes: {
            headers: ['code', 'name', 'uid']
        }
    };
    csv.importFile(__dirname + '/classes.csv', csvHeaders.classes.headers, 'classes');

    //var mysql = require('mysql');
    ////db connect string
    //var connection = mysql.createConnection(config.mySQL);
    //connection.connect();

    //serve favicon before logging for tidiness
    var favicon = require('serve-favicon');
    app.use(favicon(config.favicon.src));

    //Configure Logging
    var logger = require('morgan');
    var logfile = config.logs.dir + config.logs.file;
    fs.exists(logfile, function(exists){
        if(!exists){
            fs.mkdirSync(config.logs.dir);
            fs.writeFileSync(logfile,'',[], function(err){
                if(err){
                    console.error('Error creating log file');
                }else{
                    console.info('Log file created at: ' + logfile)
                }
            })
        }else{
            console.info('Using log file at: ' + logfile)
        }
    });
    var accessLogStream = fs.createWriteStream(logfile, {flags: 'a'});
    app.use(logger('combined', {stream: accessLogStream}));
    app.use(logger('dev'));

    //Handle Static Acts
     app.use(express.static('public'));

     var corsOptions = {
         origin: 'https://localhost',
         methods: ['GET', 'PUT', 'POST', 'DELETE'],
         allowedHeaders: ['x-access-token', 'Content-Type']
     };

     var cors = require('cors');
     app.options('*', cors(corsOptions));
     app.use(cors(corsOptions));

    ////Authentication and other middleware
    var auth = require('./privilege/authentication.js');
    app.use('/application/api/', auth);

	////check permissions
	var entitlements = require('./privilege/entitlements');
	app.use('/application/api/', entitlements);

    //parse the json we have received
	 app.use(bodyParser.urlencoded({ extended: false }));
	 app.use(bodyParser.json());

    //Routing API calls
    var APIControlRouter = require('./router/APIControlRouter')();
    //app.use('/api', APIControlRouter);
     app.use('/application/api', APIControlRouter);

    //catchall
    app.use('*', function(req, res, next){

        if(req.originalUrl.indexOf('/') !== -1){
            var path = require('path');
             //res.sendFile(path.resolve('public/application/index.html'));
            res.sendFile(path.resolve('public/index.html'));
        }else{
            res.redirect('https://advertise.nightpaws.eu/page-not-found');
        }

    });

    return app;
};

module.exports = app;
<commit_msg>providing model for context<commit_after>/**
 * Created by Nightpaws on 31/01/2016.
 */
var app = function(){
    //load config, filesystem, express router,
    var config = require('./../config'),
        fs = require('fs'),
        bodyParser = require('body-parser'),
        express = require('express'),
        csv = require('./csv');
    var app = express();//set up express

    //Database link
    var mongoose = require('mongoose');
    mongoose.connect(config.mongoDB.string);
    var classes = require('../../models/course.model.js');
    var csvHeaders = {
        classes: {
            headers: ['code', 'name', 'uid']
        }
    };
    csv.importFile(__dirname + '/classes.csv', csvHeaders.classes.headers, classes);

    //var mysql = require('mysql');
    ////db connect string
    //var connection = mysql.createConnection(config.mySQL);
    //connection.connect();

    //serve favicon before logging for tidiness
    var favicon = require('serve-favicon');
    app.use(favicon(config.favicon.src));

    //Configure Logging
    var logger = require('morgan');
    var logfile = config.logs.dir + config.logs.file;
    fs.exists(logfile, function(exists){
        if(!exists){
            fs.mkdirSync(config.logs.dir);
            fs.writeFileSync(logfile,'',[], function(err){
                if(err){
                    console.error('Error creating log file');
                }else{
                    console.info('Log file created at: ' + logfile)
                }
            })
        }else{
            console.info('Using log file at: ' + logfile)
        }
    });
    var accessLogStream = fs.createWriteStream(logfile, {flags: 'a'});
    app.use(logger('combined', {stream: accessLogStream}));
    app.use(logger('dev'));

    //Handle Static Acts
     app.use(express.static('public'));

     var corsOptions = {
         origin: 'https://localhost',
         methods: ['GET', 'PUT', 'POST', 'DELETE'],
         allowedHeaders: ['x-access-token', 'Content-Type']
     };

     var cors = require('cors');
     app.options('*', cors(corsOptions));
     app.use(cors(corsOptions));

    ////Authentication and other middleware
    var auth = require('./privilege/authentication.js');
    app.use('/application/api/', auth);

	////check permissions
	var entitlements = require('./privilege/entitlements');
	app.use('/application/api/', entitlements);

    //parse the json we have received
	 app.use(bodyParser.urlencoded({ extended: false }));
	 app.use(bodyParser.json());

    //Routing API calls
    var APIControlRouter = require('./router/APIControlRouter')();
    //app.use('/api', APIControlRouter);
     app.use('/application/api', APIControlRouter);

    //catchall
    app.use('*', function(req, res, next){

        if(req.originalUrl.indexOf('/') !== -1){
            var path = require('path');
             //res.sendFile(path.resolve('public/application/index.html'));
            res.sendFile(path.resolve('public/index.html'));
        }else{
            res.redirect('https://advertise.nightpaws.eu/page-not-found');
        }

    });

    return app;
};

module.exports = app;
<|endoftext|>