<commit_before>var fs = require("fs");
var util = require("util");
var events = require("events");
var Perfmon = require("../perfmon.js");
var iis = require("../iis.js");
var _ = require("underscore");

function LocalDataSource(argv) {
  var _this = this;

  _this.argv = argv;
}

util.inherits(LocalDataSource, events.EventEmitter);

LocalDataSource.prototype.start = function(config) {
  var _this = this;

  _this.normalize(config);

  iis.getWorkerProcesses(function(error, processes) {
    _this.iisWorkerProcesses = !error ? processes : [];

    var counters = _.chain(config.groups)
                    .map(function(group) { return [group.counters, group.lists] })
                    .flatten()
                    .compact()
                    .map(function(item) { return item.id })
                    .unique()
                    .value();

    var perfmon = new Perfmon(counters);
    perfmon.start();

    perfmon.on("data", function(data) {
      var snapshot = {
        host: data.host,
        time: data.time,
        groups: _.map(config.groups, function(group) {
          return {
            name: group.name,
            column: group.column || 1,
            counters: _.map(group.counters, function(counter) {
              var match = _.find(data.counters, function(item) { return item.name === counter.id });
              var value = match ? match.value : NaN;

              if (counter.stats) {
                if (!counter.history)
                  counter.history = [];

                counter.history.push(value);
                counter.history = _.last(counter.history, _.max(_.map(counter.stats, function(stat) { return stat.count })));

                var stats = _.map(counter.stats, function(stat) {
                  var value = _this.calc(_.last(counter.history, stat.count), stat.func);

                  return {
                    name: stat.func + "(" + stat.count + ")",
                    value: value,
                    threshold: getThresholdByValue(value, counter.threshold)
                  };
                });
              }

              return {
                name: counter.name,
                value: value,
                format: counter.format || "0,0",
                threshold: getThresholdByValue(value, counter.threshold),
                stats: stats,
              };
            }),
            lists: _.map(group.lists, function(list) {
              var regex = new RegExp(list.id.replace(/./g, function(c) { return (c === "*") ? "(.*?)" : "\\x" + c.charCodeAt(0).toString(16) }));

              var items = [];
              data.counters.forEach(function(counter) {
                var counterMatch = regex.exec(counter.name);

                if (!counterMatch)
                  return;

                var name = counterMatch[1];

                if (name[0] === "_")
                  return;

                var iisWorkerProcessMatch = /w3wp_(\d+)/.exec(name);

                if (iisWorkerProcessMatch) {
                  var iisWorkerProcessId = parseInt(iisWorkerProcessMatch[1], 10);
                  var iisWorkerProcess = _.find(_this.iisWorkerProcesses, function(workerProcess) { return workerProcess.processId === iisWorkerProcessId });

                  if (iisWorkerProcess)
                    name += "/" + iisWorkerProcess.appPool;
                }

                items.push({
                  name: name,
                  value: counter.value,
                });
              });

              items = _.sortBy(items, function(item) { return (list.sort === "desc" ? -1 : 1) * item.value });

              if (list.stats) {
                if (!list.history)
                  list.history = [];

                list.history.push(items);
                list.history = _.last(list.history, _.max(_.map(list.stats, function(stat) { return stat.count })));

                var stats = _.map(list.stats, function(stat) {
                  var items = _.zip.apply(null, list.history, stat.count);

                  items.forEach(function(group, index) {
                    items[index] = {
                      name: group[0].name,
                      value: _this.calc(_.map(group, function(item) { return item.value }), stat.func)
                    };
                  });

                  items = _.sortBy(items, function(item) { return (list.sort === "desc" ? -1 : 1) * item.value });

                  return {
                    name: stat.func + "(" + stat.count + ")",
                    items: _.first(items, list.count),
                  };
                });
              }

              return {
                name: list.name,
                items: _.first(items, list.count),
                format: list.format || "0,0",
                stats: stats,
              };
            }),
          };
        })
      };

      _this.emit("snapshot", snapshot);
    });

    _this.perfmon = perfmon;

    _this.emit("start");
  });
};

LocalDataSource.prototype.stop = function() {
  var _this = this;

  _this.perfmon.stop();
  _this.emit("stop");
};

LocalDataSource.prototype.normalize = function(config) {
  var _this = this;

  config.groups.forEach(function (group) {
    if (group.counters) {
      group.counters.forEach(function (counter, index) {
        if (_.isString(counter)) {
          counter = {
            id: counter
          };

          group.counters[index] = counter;
        }

        counter.id = counter.id.replace(/%\w+%/gi, function(match) {
          return config.variables ? config.variables[match.replace(/%/g, "")] || "" : "";
        })

        if (!counter.name)
          counter.name = /\\([^\\]+)\\(.+)/.exec(counter.id)[2];

        if (counter.threshold)
          counter.threshold = _.map(counter.threshold, function(v, k) {
            return {
              "level": (k === "*" ? Number.MAX_VALUE : k),
              "name": v
            }
          });

        if (counter.stats) {
          counter.stats.forEach(function(stat, index) {
            var match = /(\w+)\((\d+)\)/.exec(stat);
            if (match)
              counter.stats[index] = {
                func: match[1],
                count: match[2]
              };
          });
        }
      });
    }

    if (group.lists) {
      group.lists.forEach(function (list, index) {
        if (_.isString(group.list)) {
          list = {
            id: group.list
          };

          group.lists[index] = list;
        }

        if (!list.count)
          list.count = 5;

        if (!list.sort)
          list.sort = "desc";

        if (list.stats) {
          list.stats.forEach(function(stat, index) {
            var match = /(\w+)\((\d+)\)/.exec(stat);
            if (match)
              list.stats[index] = {
                func: match[1],
                count: match[2]
              };
          });
        }
      });
    }
  });
}

LocalDataSource.prototype.calc = function(data, func) {
  if (func == "sum")
    return _.reduce(data, function(memo, item) { return memo + item }, 0);

  if (func == "avg")
    return _.reduce(data, function(memo, item) { return memo + item }, 0) / data.length;
};

module.exports = LocalDataSource;

function getThresholdByValue(value, thresholds) {
  if (!thresholds)
    return null;

  return _.chain(thresholds)
          .filter(function(item) { return item.level >= value })
          .sortBy(function(item) { item.name })
          .first()
          .value();
}
<commit_msg>Bug fix: stopping a non-existing perfmon instance.<commit_after>var fs = require("fs");
var util = require("util");
var events = require("events");
var Perfmon = require("../perfmon.js");
var iis = require("../iis.js");
var _ = require("underscore");

function LocalDataSource(argv) {
  var _this = this;

  _this.argv = argv;
}

util.inherits(LocalDataSource, events.EventEmitter);

LocalDataSource.prototype.start = function(config) {
  var _this = this;

  _this.normalize(config);

  iis.getWorkerProcesses(function(error, processes) {
    _this.iisWorkerProcesses = !error ? processes : [];

    var counters = _.chain(config.groups)
                    .map(function(group) { return [group.counters, group.lists] })
                    .flatten()
                    .compact()
                    .map(function(item) { return item.id })
                    .unique()
                    .value();

    var perfmon = new Perfmon(counters);
    perfmon.start();

    perfmon.on("data", function(data) {
      var snapshot = {
        host: data.host,
        time: data.time,
        groups: _.map(config.groups, function(group) {
          return {
            name: group.name,
            column: group.column || 1,
            counters: _.map(group.counters, function(counter) {
              var match = _.find(data.counters, function(item) { return item.name === counter.id });
              var value = match ? match.value : NaN;

              if (counter.stats) {
                if (!counter.history)
                  counter.history = [];

                counter.history.push(value);
                counter.history = _.last(counter.history, _.max(_.map(counter.stats, function(stat) { return stat.count })));

                var stats = _.map(counter.stats, function(stat) {
                  var value = _this.calc(_.last(counter.history, stat.count), stat.func);

                  return {
                    name: stat.func + "(" + stat.count + ")",
                    value: value,
                    threshold: getThresholdByValue(value, counter.threshold)
                  };
                });
              }

              return {
                name: counter.name,
                value: value,
                format: counter.format || "0,0",
                threshold: getThresholdByValue(value, counter.threshold),
                stats: stats,
              };
            }),
            lists: _.map(group.lists, function(list) {
              var regex = new RegExp(list.id.replace(/./g, function(c) { return (c === "*") ? "(.*?)" : "\\x" + c.charCodeAt(0).toString(16) }));

              var items = [];
              data.counters.forEach(function(counter) {
                var counterMatch = regex.exec(counter.name);

                if (!counterMatch)
                  return;

                var name = counterMatch[1];

                if (name[0] === "_")
                  return;

                var iisWorkerProcessMatch = /w3wp_(\d+)/.exec(name);

                if (iisWorkerProcessMatch) {
                  var iisWorkerProcessId = parseInt(iisWorkerProcessMatch[1], 10);
                  var iisWorkerProcess = _.find(_this.iisWorkerProcesses, function(workerProcess) { return workerProcess.processId === iisWorkerProcessId });

                  if (iisWorkerProcess)
                    name += "/" + iisWorkerProcess.appPool;
                }

                items.push({
                  name: name,
                  value: counter.value,
                });
              });

              items = _.sortBy(items, function(item) { return (list.sort === "desc" ? -1 : 1) * item.value });

              if (list.stats) {
                if (!list.history)
                  list.history = [];

                list.history.push(items);
                list.history = _.last(list.history, _.max(_.map(list.stats, function(stat) { return stat.count })));

                var stats = _.map(list.stats, function(stat) {
                  var items = _.zip.apply(null, list.history, stat.count);

                  items.forEach(function(group, index) {
                    items[index] = {
                      name: group[0].name,
                      value: _this.calc(_.map(group, function(item) { return item.value }), stat.func)
                    };
                  });

                  items = _.sortBy(items, function(item) { return (list.sort === "desc" ? -1 : 1) * item.value });

                  return {
                    name: stat.func + "(" + stat.count + ")",
                    items: _.first(items, list.count),
                  };
                });
              }

              return {
                name: list.name,
                items: _.first(items, list.count),
                format: list.format || "0,0",
                stats: stats,
              };
            }),
          };
        })
      };

      _this.emit("snapshot", snapshot);
    });

    _this.perfmon = perfmon;

    _this.emit("start");
  });
};

LocalDataSource.prototype.stop = function() {
  var _this = this;

  if (_this.perfmon)
    _this.perfmon.stop();

  _this.emit("stop");
};

LocalDataSource.prototype.normalize = function(config) {
  var _this = this;

  config.groups.forEach(function (group) {
    if (group.counters) {
      group.counters.forEach(function (counter, index) {
        if (_.isString(counter)) {
          counter = {
            id: counter
          };

          group.counters[index] = counter;
        }

        counter.id = counter.id.replace(/%\w+%/gi, function(match) {
          return config.variables ? config.variables[match.replace(/%/g, "")] || "" : "";
        })

        if (!counter.name)
          counter.name = /\\([^\\]+)\\(.+)/.exec(counter.id)[2];

        if (counter.threshold)
          counter.threshold = _.map(counter.threshold, function(v, k) {
            return {
              "level": (k === "*" ? Number.MAX_VALUE : k),
              "name": v
            }
          });

        if (counter.stats) {
          counter.stats.forEach(function(stat, index) {
            var match = /(\w+)\((\d+)\)/.exec(stat);
            if (match)
              counter.stats[index] = {
                func: match[1],
                count: match[2]
              };
          });
        }
      });
    }

    if (group.lists) {
      group.lists.forEach(function (list, index) {
        if (_.isString(group.list)) {
          list = {
            id: group.list
          };

          group.lists[index] = list;
        }

        if (!list.count)
          list.count = 5;

        if (!list.sort)
          list.sort = "desc";

        if (list.stats) {
          list.stats.forEach(function(stat, index) {
            var match = /(\w+)\((\d+)\)/.exec(stat);
            if (match)
              list.stats[index] = {
                func: match[1],
                count: match[2]
              };
          });
        }
      });
    }
  });
}

LocalDataSource.prototype.calc = function(data, func) {
  if (func == "sum")
    return _.reduce(data, function(memo, item) { return memo + item }, 0);

  if (func == "avg")
    return _.reduce(data, function(memo, item) { return memo + item }, 0) / data.length;
};

module.exports = LocalDataSource;

function getThresholdByValue(value, thresholds) {
  if (!thresholds)
    return null;

  return _.chain(thresholds)
          .filter(function(item) { return item.level >= value })
          .sortBy(function(item) { item.name })
          .first()
          .value();
}
<|endoftext|>


<commit_before>import { combineReducers } from 'redux';
import * from 'login';

const rootReducer = combineReducers({

});

export default rootReducer

<commit_msg>Added the newly implemented login reducer<commit_after>import { combineReducers } from 'redux';
import login from './login';

const rootReducer = combineReducers({
    login
});

export default rootReducer
<|endoftext|>


<commit_before>'use strict'; // eslint-disable-line strict

const proc = require('child_process');
const process = require('process');
const assert = require('assert');

const program = 's3cmd';
const upload = 'test1MB';
const emptyUpload = 'Utest0B';
const emptyDownload = 'Dtest0B';
const download = 'tmpfile';
const MPUpload = 'test16MB';
const MPDownload = 'MPtmpfile';
const bucket = 'universe';
const nonexist = 'nonexist';
const invalidName = 'VOID';
const emailAccount = 'sampleAccount1@sampling.com';
const lowerCaseEmail = emailAccount.toLowerCase();

const isIronman = process.env.CI ? ['-c', `${__dirname}/s3cfg`] : null;

function diff(putFile, receivedFile, done) {
    process.stdout.write(`diff ${putFile} ${receivedFile}\n`);
    proc.spawn('diff', [putFile, receivedFile]).on('exit', code => {
        assert.strictEqual(code, 0);
        done();
    });
}

function createFile(name, bytes, callback) {
    process.stdout.write(`dd if=/dev/urandom of=${name} bs=${bytes} count=1\n`);
    proc.spawn('dd', ['if=/dev/urandom', `of=${name}`,
        `bs=${bytes}`, 'count=1'], { stdio: 'inherit' }).on('exit', code => {
            assert.strictEqual(code, 0);
            callback();
        });
}

function createEmptyFile(name, callback) {
    process.stdout.write(`touch ${name}\n`);
    proc.spawn('touch', [name], { stdio: 'inherit' }).on('exit', code => {
        assert.strictEqual(code, 0);
        callback();
    });
}

function deleteFile(file, callback) {
    process.stdout.write(`rm ${file}\n`);
    proc.spawn('rm', [`${file}`]).on('exit', () => {
        callback();
    });
}

function exec(args, done, exitCode) {
    let exit = exitCode;
    if (exit === undefined) {
        exit = 0;
    }
    let av = args;
    if (isIronman) {
        av = args.concat(isIronman);
    }
    process.stdout.write(`${program} ${av}\n`);
    proc.spawn(program, av, { stdio: 'inherit' })
        .on('exit', code => {
            assert.strictEqual(code, exit,
                               's3cmd did not yield expected exit status.');
            done();
        });
}

// Test stdout against expected output
function checkRawOutput(args, lineFinder, testString, cb) {
    let av = args;
    if (isIronman) {
        av = args.concat(isIronman);
    }
    process.stdout.write(`${program} ${av}\n`);
    const allData = [];
    const child = proc.spawn(program, av);
    child.stdout.on('data', (data) => {
        allData.push(data.toString().trim());
        process.stdout.write(data.toString());
    });
    child.on('close', () => {
        const lineOfInterest = allData.find((item) => {
            return item.indexOf(lineFinder) > -1;
        });
        const foundIt = lineOfInterest.indexOf(testString) > -1;
        return cb(foundIt);
    });
}

// Pull line of interest from stderr (to get debug output)
function provideLineOfInterest(args, lineFinder, cb) {
    const av = isIronman ? args.concat(isIronman) : args;
    process.stdout.write(`${program} ${av}\n`);
    const allData = [];
    const child = proc.spawn(program, av);
    child.stderr.on('data', (data) => {
        allData.push(data.toString().trim());
        process.stdout.write(data.toString());
    });
    child.on('close', () => {
        const lineOfInterest = allData.find((item) => {
            return item.indexOf(lineFinder) > -1;
        });
        return cb(lineOfInterest);
    });
}

describe('s3cmd putBucket', () => {
    it('should put a valid bucket', (done) => {
        exec(['mb', `s3://${bucket}`], done);
    });

    it('put the same bucket, should fail', (done) => {
        exec(['mb', `s3://${bucket}`], done, 13);
    });

    it('put an invalid bucket, should fail', (done) => {
        exec(['mb', `s3://${invalidName}`], done, 11);
    });
});

describe(`s3cmd put and get bucket ACL's`, function aclBuck() {
    this.timeout(60000);
    // Note that s3cmd first gets the current ACL and then
    // sets the new one so by running setacl you are running a
    // get and a put
    it('should set a canned ACL', (done) => {
        exec(['setacl', `s3://${bucket}`, '--acl-public'], done);
    });

    it('should get canned ACL that was set', (done) => {
        checkRawOutput(['info', `s3://${bucket}`], 'ACL', `*anon*: READ`,
        (foundIt) => {
            assert(foundIt);
            done();
        });
    });

    it('should set a specific ACL', (done) => {
        exec(['setacl', `s3://${bucket}`,
        `--acl-grant=write:${emailAccount}`], done);
    });

    it('should get specific ACL that was set', (done) => {
        checkRawOutput(['info', `s3://${bucket}`], 'ACL',
        `${lowerCaseEmail}: WRITE`, (foundIt) => {
            assert(foundIt);
            done();
        });
    });
});

describe('s3cmd getBucket', () => {
    it('should list existing bucket', (done) => {
        exec(['ls', `s3://${bucket}`], done);
    });

    it('list non existing bucket, should fail', (done) => {
        exec(['ls', `s3://${nonexist}`], done, 12);
    });
});

describe('s3cmd getService', () => {
    it(`should get a list of a user's buckets`, (done) => {
        checkRawOutput(['ls'], 's3://',
        `${bucket}`, (foundIt) => {
            assert(foundIt);
            done();
        });
    });

    it(`should have response headers matching AWS's response headers`,
        (done) => {
            provideLineOfInterest(['ls', '--debug'], 'DEBUG: Response:',
            (lineOfInterest) => {
                const openingBracket = lineOfInterest.indexOf('{');
                const resObject = lineOfInterest.slice(openingBracket)
                    .replace(/"/g, '\\"').replace(/'/g, '"');
                const parsedObject = JSON.parse(resObject);
                assert(parsedObject.headers['x-amz-id-2']);
                assert.strictEqual(parsedObject.headers.server, 'AmazonS3');
                assert(parsedObject.headers['transfer-encoding']);
                assert(parsedObject.headers['x-amz-request-id']);
                const gmtDate = new Date(parsedObject.headers.date)
                    .toUTCString();
                assert.strictEqual(parsedObject.headers.date, gmtDate);
                assert.strictEqual(parsedObject
                    .headers['content-type'], 'application/xml');
                assert.strictEqual(parsedObject
                    .headers['set-cookie'], undefined);
                done();
            });
        });
});

describe('s3cmd putObject', () => {
    before('create file to put', (done) => {
        createFile(upload, 1048576, done);
    });

    it('should put file in existing bucket', (done) => {
        exec(['put', upload, `s3://${bucket}`], done);
    });

    it('should put file with the same name in existing bucket', (done) => {
        exec(['put', upload, `s3://${bucket}`], done);
    });

    it('put file in non existing bucket, should fail', (done) => {
        exec(['put', upload, `s3://${nonexist}`], done, 12);
    });
});

describe('s3cmd getObject', function toto() {
    this.timeout(0);
    after('delete downloaded file', done => {
        deleteFile(download, done);
    });

    it('should get existing file in existing bucket', (done) => {
        exec(['get', `s3://${bucket}/${upload}`, download], done);
    });

    it('downloaded file should equal uploaded file', (done) => {
        diff(upload, download, done);
    });

    it('get non existing file in existing bucket, should fail', (done) => {
        exec(['get', `s3://${bucket}/${nonexist}`, 'fail'], done, 12);
    });

    it('get file in non existing bucket, should fail', (done) => {
        exec(['get', `s3://${nonexist}/${nonexist}`, 'fail2'], done, 12);
    });
});

describe(`s3cmd put and get object ACL's`, function aclObj() {
    this.timeout(60000);
    // Note that s3cmd first gets the current ACL and then
    // sets the new one so by running setacl you are running a
    // get and a put
    it('should set a canned ACL', (done) => {
        exec(['setacl', `s3://${bucket}/${upload}`, '--acl-public'], done);
    });

    it('should get canned ACL that was set', (done) => {
        checkRawOutput(['info', `s3://${bucket}/${upload}`], 'ACL',
        `*anon*: READ`, (foundIt) => {
            assert(foundIt);
            done();
        });
    });

    it('should set a specific ACL', (done) => {
        exec(['setacl', `s3://${bucket}/${upload}`,
            `--acl-grant=read:${emailAccount}`], done);
    });

    it('should get specific ACL that was set', (done) => {
        checkRawOutput(['info', `s3://${bucket}/${upload}`], 'ACL',
        `${lowerCaseEmail}: READ`, (foundIt) => {
            assert(foundIt);
            done();
        });
    });

    it('should return error if set acl for ' +
        'nonexistent object', (done) => {
        exec(['setacl', `s3://${bucket}/${nonexist}`,
            '--acl-public'], done, 12);
    });
});

describe('s3cmd delObject', () => {
    it('should delete existing object', (done) => {
        exec(['rm', `s3://${bucket}/${upload}`], done);
    });

    it('delete non existing object, should fail', (done) => {
        exec(['rm', `s3://${bucket}/${nonexist}`], done, 12);
    });

    it('try to get the deleted object, should fail', (done) => {
        exec(['get', `s3://${bucket}/${upload}`, download], done, 12);
    });
});

describe('connector edge cases', function tata() {
    this.timeout(0);
    before('create file to put', (done) => {
        createEmptyFile(emptyUpload, done);
    });
    after('delete uploaded and downloaded file', (done) => {
        deleteFile(upload, () => {
            deleteFile(download, () => {
                deleteFile(emptyUpload, () => {
                    deleteFile(emptyDownload, done);
                });
            });
        });
    });

    it('should put previous file in existing bucket', (done) => {
        exec(['put', upload, `s3://${bucket}`], done);
    });

    it('should get existing file in existing bucket', (done) => {
        exec(['get', `s3://${bucket}/${upload}`, download], done);
    });

    it('should put a 0 Bytes file', (done) => {
        exec(['put', emptyUpload, `s3://${bucket}`], done);
    });

    it('should get a 0 Bytes file', (done) => {
        exec(['get', `s3://${bucket}/${emptyUpload}`, emptyDownload], done);
    });

    it('should delete a 0 Bytes file', (done) => {
        exec(['del', `s3://${bucket}/${emptyUpload}`], done);
    });
});

describe('s3cmd multipart upload', function titi() {
    this.timeout(0);
    before('create the multipart file', function createMPUFile(done) {
        this.timeout(60000);
        createFile(MPUpload, 16777216, done);
    });

    after('delete the multipart and the downloaded file', done => {
        deleteFile(MPUpload, () => {
            deleteFile(MPDownload, done);
        });
    });

    it('should put an object via a multipart upload', (done) => {
        exec(['put', MPUpload, `s3://${bucket}`], done);
    });

    it('should list multipart uploads', (done) => {
        exec(['multipart', `s3://${bucket}`], done);
    });

    it('should get an object that was put via multipart upload', (done) => {
        exec(['get', `s3://${bucket}/${MPUpload}`, MPDownload], done);
    });

    it('downloaded file should equal uploaded file', (done) => {
        diff(MPUpload, MPDownload, done);
    });

    it('should delete multipart uploaded object', (done) => {
        exec(['rm', `s3://${bucket}/${MPUpload}`], done);
    });

    it('should not be able to get deleted object', (done) => {
        exec(['get', `s3://${bucket}/${MPUpload}`, download], done, 12);
    });
});

describe('s3cmd delBucket', () => {
    it('delete non-empty bucket, should fail', (done) => {
        exec(['rb', `s3://${bucket}`], done, 13);
    });

    it('should delete remaining object', (done) => {
        exec(['rm', `s3://${bucket}/${upload}`], done);
    });

    it('should delete empty bucket', (done) => {
        exec(['rb', `s3://${bucket}`], done);
    });

    it('try to get the deleted bucket, should fail', (done) => {
        exec(['ls', `s3://${bucket}`], done, 12);
    });
});
<commit_msg>Refactor raw output testing function.<commit_after>'use strict'; // eslint-disable-line strict

const proc = require('child_process');
const process = require('process');
const assert = require('assert');

const program = 's3cmd';
const upload = 'test1MB';
const emptyUpload = 'Utest0B';
const emptyDownload = 'Dtest0B';
const download = 'tmpfile';
const MPUpload = 'test16MB';
const MPDownload = 'MPtmpfile';
const bucket = 'universe';
const nonexist = 'nonexist';
const invalidName = 'VOID';
const emailAccount = 'sampleAccount1@sampling.com';
const lowerCaseEmail = emailAccount.toLowerCase();

const isIronman = process.env.CI ? ['-c', `${__dirname}/s3cfg`] : null;

function diff(putFile, receivedFile, done) {
    process.stdout.write(`diff ${putFile} ${receivedFile}\n`);
    proc.spawn('diff', [putFile, receivedFile]).on('exit', code => {
        assert.strictEqual(code, 0);
        done();
    });
}

function createFile(name, bytes, callback) {
    process.stdout.write(`dd if=/dev/urandom of=${name} bs=${bytes} count=1\n`);
    proc.spawn('dd', ['if=/dev/urandom', `of=${name}`,
        `bs=${bytes}`, 'count=1'], { stdio: 'inherit' }).on('exit', code => {
            assert.strictEqual(code, 0);
            callback();
        });
}

function createEmptyFile(name, callback) {
    process.stdout.write(`touch ${name}\n`);
    proc.spawn('touch', [name], { stdio: 'inherit' }).on('exit', code => {
        assert.strictEqual(code, 0);
        callback();
    });
}

function deleteFile(file, callback) {
    process.stdout.write(`rm ${file}\n`);
    proc.spawn('rm', [`${file}`]).on('exit', () => {
        callback();
    });
}

function exec(args, done, exitCode) {
    let exit = exitCode;
    if (exit === undefined) {
        exit = 0;
    }
    let av = args;
    if (isIronman) {
        av = args.concat(isIronman);
    }
    process.stdout.write(`${program} ${av}\n`);
    proc.spawn(program, av, { stdio: 'inherit' })
        .on('exit', code => {
            assert.strictEqual(code, exit,
                               's3cmd did not yield expected exit status.');
            done();
        });
}

// Test stdout against expected output
function checkRawOutput(args, lineFinder, testString, cb) {
    let av = args;
    if (isIronman) {
        av = args.concat(isIronman);
    }
    process.stdout.write(`${program} ${av}\n`);
    const allData = [];
    const child = proc.spawn(program, av);
    child.stdout.on('data', (data) => {
        allData.push(data.toString().trim());
        process.stdout.write(data.toString());
    });
    child.on('close', () => {
        const linesOfInterest = allData.filter((item) => {
            return item.indexOf(lineFinder) > -1;
        });
        const foundIt = linesOfInterest.some(item => {
            return item.indexOf(testString) > -1;
        });
        return cb(foundIt);
    });
}

// Pull line of interest from stderr (to get debug output)
function provideLineOfInterest(args, lineFinder, cb) {
    const av = isIronman ? args.concat(isIronman) : args;
    process.stdout.write(`${program} ${av}\n`);
    const allData = [];
    const child = proc.spawn(program, av);
    child.stderr.on('data', (data) => {
        allData.push(data.toString().trim());
        process.stdout.write(data.toString());
    });
    child.on('close', () => {
        const lineOfInterest = allData.find((item) => {
            return item.indexOf(lineFinder) > -1;
        });
        return cb(lineOfInterest);
    });
}

describe('s3cmd putBucket', () => {
    it('should put a valid bucket', (done) => {
        exec(['mb', `s3://${bucket}`], done);
    });

    it('put the same bucket, should fail', (done) => {
        exec(['mb', `s3://${bucket}`], done, 13);
    });

    it('put an invalid bucket, should fail', (done) => {
        exec(['mb', `s3://${invalidName}`], done, 11);
    });
});

describe(`s3cmd put and get bucket ACL's`, function aclBuck() {
    this.timeout(60000);
    // Note that s3cmd first gets the current ACL and then
    // sets the new one so by running setacl you are running a
    // get and a put
    it('should set a canned ACL', (done) => {
        exec(['setacl', `s3://${bucket}`, '--acl-public'], done);
    });

    it('should get canned ACL that was set', (done) => {
        checkRawOutput(['info', `s3://${bucket}`], 'ACL', `*anon*: READ`,
        (foundIt) => {
            assert(foundIt);
            done();
        });
    });

    it('should set a specific ACL', (done) => {
        exec(['setacl', `s3://${bucket}`,
        `--acl-grant=write:${emailAccount}`], done);
    });

    it('should get specific ACL that was set', (done) => {
        checkRawOutput(['info', `s3://${bucket}`], 'ACL',
        `${lowerCaseEmail}: WRITE`, (foundIt) => {
            assert(foundIt);
            done();
        });
    });
});

describe('s3cmd getBucket', () => {
    it('should list existing bucket', (done) => {
        exec(['ls', `s3://${bucket}`], done);
    });

    it('list non existing bucket, should fail', (done) => {
        exec(['ls', `s3://${nonexist}`], done, 12);
    });
});

describe('s3cmd getService', () => {
    it(`should get a list of a user's buckets`, (done) => {
        checkRawOutput(['ls'], 's3://',
        `${bucket}`, (foundIt) => {
            assert(foundIt);
            done();
        });
    });

    it(`should have response headers matching AWS's response headers`,
        (done) => {
            provideLineOfInterest(['ls', '--debug'], 'DEBUG: Response:',
            (lineOfInterest) => {
                const openingBracket = lineOfInterest.indexOf('{');
                const resObject = lineOfInterest.slice(openingBracket)
                    .replace(/"/g, '\\"').replace(/'/g, '"');
                const parsedObject = JSON.parse(resObject);
                assert(parsedObject.headers['x-amz-id-2']);
                assert.strictEqual(parsedObject.headers.server, 'AmazonS3');
                assert(parsedObject.headers['transfer-encoding']);
                assert(parsedObject.headers['x-amz-request-id']);
                const gmtDate = new Date(parsedObject.headers.date)
                    .toUTCString();
                assert.strictEqual(parsedObject.headers.date, gmtDate);
                assert.strictEqual(parsedObject
                    .headers['content-type'], 'application/xml');
                assert.strictEqual(parsedObject
                    .headers['set-cookie'], undefined);
                done();
            });
        });
});

describe('s3cmd putObject', () => {
    before('create file to put', (done) => {
        createFile(upload, 1048576, done);
    });

    it('should put file in existing bucket', (done) => {
        exec(['put', upload, `s3://${bucket}`], done);
    });

    it('should put file with the same name in existing bucket', (done) => {
        exec(['put', upload, `s3://${bucket}`], done);
    });

    it('put file in non existing bucket, should fail', (done) => {
        exec(['put', upload, `s3://${nonexist}`], done, 12);
    });
});

describe('s3cmd getObject', function toto() {
    this.timeout(0);
    after('delete downloaded file', done => {
        deleteFile(download, done);
    });

    it('should get existing file in existing bucket', (done) => {
        exec(['get', `s3://${bucket}/${upload}`, download], done);
    });

    it('downloaded file should equal uploaded file', (done) => {
        diff(upload, download, done);
    });

    it('get non existing file in existing bucket, should fail', (done) => {
        exec(['get', `s3://${bucket}/${nonexist}`, 'fail'], done, 12);
    });

    it('get file in non existing bucket, should fail', (done) => {
        exec(['get', `s3://${nonexist}/${nonexist}`, 'fail2'], done, 12);
    });
});

describe(`s3cmd put and get object ACL's`, function aclObj() {
    this.timeout(60000);
    // Note that s3cmd first gets the current ACL and then
    // sets the new one so by running setacl you are running a
    // get and a put
    it('should set a canned ACL', (done) => {
        exec(['setacl', `s3://${bucket}/${upload}`, '--acl-public'], done);
    });

    it('should get canned ACL that was set', (done) => {
        checkRawOutput(['info', `s3://${bucket}/${upload}`], 'ACL',
        `*anon*: READ`, (foundIt) => {
            assert(foundIt);
            done();
        });
    });

    it('should set a specific ACL', (done) => {
        exec(['setacl', `s3://${bucket}/${upload}`,
            `--acl-grant=read:${emailAccount}`], done);
    });

    it('should get specific ACL that was set', (done) => {
        checkRawOutput(['info', `s3://${bucket}/${upload}`], 'ACL',
        `${lowerCaseEmail}: READ`, (foundIt) => {
            assert(foundIt);
            done();
        });
    });

    it('should return error if set acl for ' +
        'nonexistent object', (done) => {
        exec(['setacl', `s3://${bucket}/${nonexist}`,
            '--acl-public'], done, 12);
    });
});

describe('s3cmd delObject', () => {
    it('should delete existing object', (done) => {
        exec(['rm', `s3://${bucket}/${upload}`], done);
    });

    it('delete non existing object, should fail', (done) => {
        exec(['rm', `s3://${bucket}/${nonexist}`], done, 12);
    });

    it('try to get the deleted object, should fail', (done) => {
        exec(['get', `s3://${bucket}/${upload}`, download], done, 12);
    });
});

describe('connector edge cases', function tata() {
    this.timeout(0);
    before('create file to put', (done) => {
        createEmptyFile(emptyUpload, done);
    });
    after('delete uploaded and downloaded file', (done) => {
        deleteFile(upload, () => {
            deleteFile(download, () => {
                deleteFile(emptyUpload, () => {
                    deleteFile(emptyDownload, done);
                });
            });
        });
    });

    it('should put previous file in existing bucket', (done) => {
        exec(['put', upload, `s3://${bucket}`], done);
    });

    it('should get existing file in existing bucket', (done) => {
        exec(['get', `s3://${bucket}/${upload}`, download], done);
    });

    it('should put a 0 Bytes file', (done) => {
        exec(['put', emptyUpload, `s3://${bucket}`], done);
    });

    it('should get a 0 Bytes file', (done) => {
        exec(['get', `s3://${bucket}/${emptyUpload}`, emptyDownload], done);
    });

    it('should delete a 0 Bytes file', (done) => {
        exec(['del', `s3://${bucket}/${emptyUpload}`], done);
    });
});

describe('s3cmd multipart upload', function titi() {
    this.timeout(0);
    before('create the multipart file', function createMPUFile(done) {
        this.timeout(60000);
        createFile(MPUpload, 16777216, done);
    });

    after('delete the multipart and the downloaded file', done => {
        deleteFile(MPUpload, () => {
            deleteFile(MPDownload, done);
        });
    });

    it('should put an object via a multipart upload', (done) => {
        exec(['put', MPUpload, `s3://${bucket}`], done);
    });

    it('should list multipart uploads', (done) => {
        exec(['multipart', `s3://${bucket}`], done);
    });

    it('should get an object that was put via multipart upload', (done) => {
        exec(['get', `s3://${bucket}/${MPUpload}`, MPDownload], done);
    });

    it('downloaded file should equal uploaded file', (done) => {
        diff(MPUpload, MPDownload, done);
    });

    it('should delete multipart uploaded object', (done) => {
        exec(['rm', `s3://${bucket}/${MPUpload}`], done);
    });

    it('should not be able to get deleted object', (done) => {
        exec(['get', `s3://${bucket}/${MPUpload}`, download], done, 12);
    });
});

describe('s3cmd delBucket', () => {
    it('delete non-empty bucket, should fail', (done) => {
        exec(['rb', `s3://${bucket}`], done, 13);
    });

    it('should delete remaining object', (done) => {
        exec(['rm', `s3://${bucket}/${upload}`], done);
    });

    it('should delete empty bucket', (done) => {
        exec(['rb', `s3://${bucket}`], done);
    });

    it('try to get the deleted bucket, should fail', (done) => {
        exec(['ls', `s3://${bucket}`], done, 12);
    });
});
<|endoftext|>


<commit_before>import { combineReducers } from 'redux';
import { handleEvent, previous } from './login.js';

const rootReducer = combineReducers({
    login: handleEvent,
    lastAction: previous
});

export default rootReducer
<commit_msg>Added the file event handler reducer<commit_after>import { combineReducers } from 'redux';
import { handleLoginEvent, previous } from './login.js';
import { handleFileEvent } from './file.js';

const rootReducer = combineReducers({
    file: handleFileEvent,
    login: handleLoginEvent,
    lastAction: previous
});

export default rootReducer
<|endoftext|>


<commit_before>app.controller('NavbarCtrl',
    ['$scope', 'logSvc', 'soapSvc', 'config', 'layoutSvc', 'sceneSvc',
        function ($scope, logSvc, soapSvc, config, layoutSvc, sceneSvc) {

            $scope.$on(AngularHelper.constants.EVENTS.COMMAND_HISTORY_CHANGED, function() {
                $scope.safeDigest();
            });

            $scope.editGameScene = function() {
                EventManager.emit(AngularHelper.constants.EVENTS.OBJECTS_SELECTION, [sceneSvc.getActiveGameScene()]);
            };

            $scope.showConsole = function () {
                layoutSvc.addWindow(constants.WINDOW_TYPES.CONSOLE);
            };

            $scope.showProjectExplorer = function () {
                layoutSvc.addWindow(constants.WINDOW_TYPES.PROJECT_EXPLORER);
            };

            $scope.showSceneHierarchy = function () {
                layoutSvc.addWindow(constants.WINDOW_TYPES.SCENE_HIERARCHY);
            };

            $scope.showAtlasEditor = function () {
                layoutSvc.addWindow(constants.WINDOW_TYPES.ATLAS_EDITOR);
            };

            $scope.showSceneView = function () {
                layoutSvc.addWindow(constants.WINDOW_TYPES.SCENE_VIEW);
            };

            $scope.showInspector = function () {
                layoutSvc.addWindow(constants.WINDOW_TYPES.INSPECTOR);
            };

            $scope.safeDigest = function () {
                !$scope.$$phase && $scope.$digest();
            };

            $scope.canUndo = function () {
                return AngularHelper.commandHistory.canUndo();
            };

            $scope.canRedo = function () {
                return AngularHelper.commandHistory.canRedo();
            };

            $scope.undo = function () {
                if ($scope.canUndo()) {
                    AngularHelper.commandHistory.undo();
                    AngularHelper.rootScope.$broadcast(AngularHelper.constants.EVENTS.GAME_OBJECT_UPDATED);
                }
            };

            $scope.isToolActive = function (id) {
                return EditorGameScene.activeTransformTool == id;
            };

            $scope.setActiveTool = function (id) {
                EditorGameScene.activeTransformTool = id;
            };

            $scope.redo = function () {
                if ($scope.canRedo()) {
                    AngularHelper.commandHistory.redo();
                    AngularHelper.rootScope.$broadcast(AngularHelper.constants.EVENTS.GAME_OBJECT_UPDATED);
                }
            };
        }]
);

<commit_msg>Added constants dependency to Navbar Controller<commit_after>app.controller('NavbarCtrl',
    ['$scope', 'logSvc', 'soapSvc', 'config', 'layoutSvc', 'sceneSvc', 'constants',
        function ($scope, logSvc, soapSvc, config, layoutSvc, sceneSvc, constants) {

            $scope.$on(AngularHelper.constants.EVENTS.COMMAND_HISTORY_CHANGED, function() {
                $scope.safeDigest();
            });

            $scope.editGameScene = function() {
                EventManager.emit(AngularHelper.constants.EVENTS.OBJECTS_SELECTION, [sceneSvc.getActiveGameScene()]);
            };

            $scope.showConsole = function () {
                layoutSvc.addWindow(constants.WINDOW_TYPES.CONSOLE);
            };

            $scope.showProjectExplorer = function () {
                layoutSvc.addWindow(constants.WINDOW_TYPES.PROJECT_EXPLORER);
            };

            $scope.showSceneHierarchy = function () {
                layoutSvc.addWindow(constants.WINDOW_TYPES.SCENE_HIERARCHY);
            };

            $scope.showAtlasEditor = function () {
                layoutSvc.addWindow(constants.WINDOW_TYPES.ATLAS_EDITOR);
            };

            $scope.showSceneView = function () {
                layoutSvc.addWindow(constants.WINDOW_TYPES.SCENE_VIEW);
            };

            $scope.showInspector = function () {
                layoutSvc.addWindow(constants.WINDOW_TYPES.INSPECTOR);
            };

            $scope.safeDigest = function () {
                !$scope.$$phase && $scope.$digest();
            };

            $scope.canUndo = function () {
                return AngularHelper.commandHistory.canUndo();
            };

            $scope.canRedo = function () {
                return AngularHelper.commandHistory.canRedo();
            };

            $scope.undo = function () {
                if ($scope.canUndo()) {
                    AngularHelper.commandHistory.undo();
                    AngularHelper.rootScope.$broadcast(AngularHelper.constants.EVENTS.GAME_OBJECT_UPDATED);
                }
            };

            $scope.isToolActive = function (id) {
                return EditorGameScene.activeTransformTool == id;
            };

            $scope.setActiveTool = function (id) {
                EditorGameScene.activeTransformTool = id;
            };

            $scope.redo = function () {
                if ($scope.canRedo()) {
                    AngularHelper.commandHistory.redo();
                    AngularHelper.rootScope.$broadcast(AngularHelper.constants.EVENTS.GAME_OBJECT_UPDATED);
                }
            };
        }]
);

<|endoftext|>


<commit_before>'use strict';

module.exports =

/*@ngInject*/
function ($httpProvider, $stateProvider) {
  $httpProvider.interceptors.push(require('./oauth_interceptor.js'));

  $stateProvider.state('access_token', {
    url: '/access_token={accessToken}&token_type={tokenType}&expires_in={expiresIn}',
    template: '',
    controller: function ($stateParams, AccessToken, $location, $state, Storage) {
      var hashStr = [
        'access_token=' + $stateParams.accessToken,
        'token_type=' + $stateParams.tokenType,
        'expires_in=' + $stateParams.expiresIn
      ].join('&');
      AccessToken.setTokenFromString(hashStr);
      var postAuthenticationRedirect = Storage.delete('postAuthenticationRedirect');
      if (postAuthenticationRedirect === undefined) {
        parent.postMessage("message", "http://localhost:3000");
      } else {
        $state.go(postAuthenticationRedirect.stateName, postAuthenticationRedirect.stateParams);
      }
    }
  });
};
<commit_msg>Support feature in production<commit_after>'use strict';

module.exports =

/*@ngInject*/
function ($httpProvider, $stateProvider) {
  $httpProvider.interceptors.push(require('./oauth_interceptor.js'));

  $stateProvider.state('access_token', {
    url: '/access_token={accessToken}&token_type={tokenType}&expires_in={expiresIn}',
    template: '',
    controller: function ($stateParams, AccessToken, $location, $state, Storage) {
      var hashStr = [
        'access_token=' + $stateParams.accessToken,
        'token_type=' + $stateParams.tokenType,
        'expires_in=' + $stateParams.expiresIn
      ].join('&');
      AccessToken.setTokenFromString(hashStr);
      var postAuthenticationRedirect = Storage.delete('postAuthenticationRedirect');
      if (postAuthenticationRedirect === undefined) {
        parent.postMessage('message', 'http://localhost:3000');
        parent.postMessage('message', 'https://www.quill.org');
      } else {
        $state.go(postAuthenticationRedirect.stateName, postAuthenticationRedirect.stateParams);
      }
    }
  });
};
<|endoftext|>


<commit_before>define('marketplace', ['jquery', 'tmpl!marketplace.table,marketplace.details', 'uikit'], function($, tmpl, uikit) {

    var updates = {}, packages = {}, element, form, details, modal, params;

    // details modal
    function detailsModal(e) {
        e.preventDefault();

        var name = $(this).data('package'), data = packages[name];

        data.iframe = params.api.replace(/\/api$/, '') + '/marketplace/frame/' + name;
        details.html(tmpl.render('marketplace.details', data));

        if (!modal) {
            modal = new uikit.modal.Modal(details);
        }

        modal.show();

    }

    // details install button
    function installButton(e) {
        e.preventDefault();

        var $this = $(this), name = $this.data('install');

        $this.removeAttr('data-install').html('');

        $.post(params.url, { package: JSON.stringify(packages[name].version) }, function(data) {

            $this.removeClass('uk-button-primary');

            if (data.message) {
                packages[name].installed = true;
                $this.addClass('uk-button-success').html('');
            } else {
                $this.html('Error!');
            }

        });

    }

    // query marketplace
    function queryMarketplace(e) {
        e.preventDefault();

        var content = '', message = '';

        $.post(params.api + '/package/search', $(this).serialize(), function(data) {

            if (data.packages.length) {

                packages = {};

                $.each(data.packages, function(i, p) {

                    packages[p.name] = p;

                    if (updates[p.name]) {
                        p.update = true;
                    } else if (params.installed[p.name]) {
                        p.installed = true;
                    } else {
                        p.install = true;
                    }

                });

                content = tmpl.render('marketplace.table', data);

            } else {
                message = 'no-packages';
            }

        }, 'jsonp').fail(function() {

            message = 'no-connection';

        }).always(function() {

            $('[data-msg]', element).each(function() {

                var $this = $(this);

                if ($this.data('msg') == message) {
                    $this.removeClass('uk-hidden');
                } else {
                    $this.addClass('uk-hidden');
                }

            });

            $('.js-marketplace-content', element).html(content);

        });

    }

    return {

        init: function(el, p) {

            element = $(el), form = $('form', el), details = $('.js-marketplace-details', el), params = p, updates = p.updates;

            element.on('click', '[data-package]', detailsModal);
            details.on('click', '[data-install]', installButton);

            form
                .on('submit', queryMarketplace)
                .on('keyup', 'input', uikit.Utils.debounce(function() {
                    form.submit();
                }, 150))
                .on('change', 'select', function() {
                    form.submit();
                })
                .submit();
        }

    };

});<commit_msg>Show error message on failed install (fixes #20)<commit_after>define('marketplace', ['jquery', 'tmpl!marketplace.table,marketplace.details', 'uikit'], function($, tmpl, uikit) {

    var updates = {}, packages = {}, element, form, details, modal, params;

    // details modal
    function detailsModal(e) {
        e.preventDefault();

        var name = $(this).data('package'), data = packages[name];

        data.iframe = params.api.replace(/\/api$/, '') + '/marketplace/frame/' + name;
        details.html(tmpl.render('marketplace.details', data));

        if (!modal) {
            modal = new uikit.modal.Modal(details);
        }

        modal.show();

    }

    // details install button
    function installButton(e) {
        e.preventDefault();

        var $this = $(this), label = $this.text(), name = $this.data('install');

        $this.removeAttr('data-install').html('');

        $.post(params.url, { package: JSON.stringify(packages[name].version) }, function(data) {

            if (data.message) {
                packages[name].installed = true;
                $this.addClass('uk-button-success').html('');
            } else {
                uikit.notify(data.error, 'danger');
                $this.attr('data-install', name).html(label);
            }

        });

    }

    // query marketplace
    function queryMarketplace(e) {
        e.preventDefault();

        var content = '', message = '';

        $.post(params.api + '/package/search', $(this).serialize(), function(data) {

            if (data.packages.length) {

                packages = {};

                $.each(data.packages, function(i, p) {

                    packages[p.name] = p;

                    if (updates[p.name]) {
                        p.update = true;
                    } else if (params.installed[p.name]) {
                        p.installed = true;
                    } else {
                        p.install = true;
                    }

                });

                content = tmpl.render('marketplace.table', data);

            } else {
                message = 'no-packages';
            }

        }, 'jsonp').fail(function() {

            message = 'no-connection';

        }).always(function() {

            $('[data-msg]', element).each(function() {

                var $this = $(this);

                if ($this.data('msg') == message) {
                    $this.removeClass('uk-hidden');
                } else {
                    $this.addClass('uk-hidden');
                }

            });

            $('.js-marketplace-content', element).html(content);

        });

    }

    return {

        init: function(el, p) {

            element = $(el), form = $('form', el), details = $('.js-marketplace-details', el), params = p, updates = p.updates;

            element.on('click', '[data-package]', detailsModal);
            details.on('click', '[data-install]', installButton);

            form
                .on('submit', queryMarketplace)
                .on('keyup', 'input', uikit.Utils.debounce(function() {
                    form.submit();
                }, 150))
                .on('change', 'select', function() {
                    form.submit();
                })
                .submit();
        }

    };

});<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * @fileoverview
 *
 * Provides access to user prefs, module dimensions, and messages.
 *
 * Clients can access their preferences by constructing an instance of
 * gadgets.Prefs and passing in their module id.  Example:
 *
 *   var prefs = new gadgets.Prefs();
 *   var name = prefs.getString("name");
 *   var lang = prefs.getLang();
 *
 * Modules with type=url can also use this library to parse arguments passed
 * by URL, but this is not the common case:
 *
 *   <script src="http://apache.org/shindig/prefs.js"></script>
 *   <script>
 *   gadgets.Prefs.parseUrl();
 *   var prefs = new gadgets.Prefs();
 *   var name = prefs.getString("name");
 *   </script≶
 */

var gadgets = gadgets || {};

(function() {

var instance = null;
var prefs = {};
var esc = gadgets.util.escapeString;
var messages = {};
var defaultPrefs = {};
var language = "en";
var country = "US";
var moduleId = 0;

/**
 * Parses all parameters from the url and stores them
 * for later use when creating a new gadgets.Prefs object.
 */
function parseUrl() {
  var params = gadgets.util.getUrlParameters();
  for (var i in params) {
    if (params.hasOwnProperty(i)) {
      if (i.indexOf("up_") === 0 && i.length > 3) {
        prefs[i.substr(3)] = String(params[i]);
      } else if (i === "country") {
        country = params[i];
      } else if (i === "lang") {
        language = params[i];
      } else if (i === "mid") {
        moduleId = params[i];
      }
    }
  }
}

/**
 * Sets default pref values for values left unspecified in the
 * rendering call, but with default_value provided in the spec.
 */
function mergeDefaults() {
  for (var name in defaultPrefs) {
    if (!prefs[name]) {
      prefs[name] = defaultPrefs[name];
    }
  }
}

/**
 * @class
 * Provides access to user preferences, module dimensions, and messages.
 *
 * Clients can access their preferences by constructing an instance of
 * gadgets.Prefs and passing in their module id.  Example:
 *

var prefs = new gadgets.Prefs();
var name = prefs.getString("name");
var lang = prefs.getLang();

 *
 * @description Creates a new Prefs object.
 *
 * Note: this is actually a singleton. All prefs are linked. If you're wondering
 * why this is a singleton and not just a collection of package functions, the
 * simple answer is that it's how the spec is written. The spec is written this
 * way for legacy compatibility with igoogle.
 */
gadgets.Prefs = function() {
  if (!instance) {
    parseUrl();
    mergeDefaults();
    instance = this;
  }
  return instance;
};

/**
 * Sets internal values
 */
gadgets.Prefs.setInternal_ = function(key, value) {
  if (typeof key === "string") {
    prefs[key] = value;
  } else {
    for (var k in key) {
      if (key.hasOwnProperty(k)) {
        prefs[k] = key[k];
      }
    }
  }
};

/**
 * Initializes message bundles.
 */
gadgets.Prefs.setMessages_ = function(msgs) {
  messages = msgs;
};

/**
 * Initializes default user prefs values.
 */
gadgets.Prefs.setDefaultPrefs_ = function(defprefs) {
  defaultPrefs = defprefs;
};

/**
 * Retrieves a preference as a string.
 * Returned value will be html entity escaped.
 *
 * @param {String} key The preference to fetch
 * @return {String} The preference; if not set, an empty string
 */
gadgets.Prefs.prototype.getString = function(key) {
  return prefs[key] ? esc(prefs[key]) : "";
};

/*
 * Indicates not to escape string values when retrieving them.
 * This is an internal detail used by _IG_Prefs for backward compatibility.
 */
gadgets.Prefs.prototype.setDontEscape_ = function() {
  esc = function(k) { return k; };
};

/**
 * Retrieves a preference as an integer.
 * @param {String} key The preference to fetch
 * @return {Number} The preference; if not set, 0
 */
gadgets.Prefs.prototype.getInt = function(key) {
  var val = parseInt(prefs[key], 10);
  return isNaN(val) ? 0 : val;
};

/**
 * Retrieves a preference as a floating-point value.
 * @param {String} key The preference to fetch
 * @return {Number} The preference; if not set, 0
 */
gadgets.Prefs.prototype.getFloat = function(key) {
  var val = parseFloat(prefs[key]);
  return isNaN(val) ? 0 : val;
};

/**
 * Retrieves a preference as a boolean.
 * @param {String} key The preference to fetch
 * @return {Boolean} The preference; if not set, false
 */
gadgets.Prefs.prototype.getBool = function(key) {
  var val = prefs[key];
  if (val) {
    return val === "true" || val === true || !!parseInt(val, 10);
  }
  return false;
};

/**
 * Stores a preference.
 * To use this call,
 * the gadget must require the feature setprefs.
 *
 *

 * Note:
 * If the gadget needs to store an Array it should use setArray instead of
 * this call.
 *

 *
 * @param {String} key The pref to store
 * @param {Object} val The values to store
 */
gadgets.Prefs.prototype.set = function(key, value) {
  throw new Error("setprefs feature required to make this call.");
};

/**
 * Retrieves a preference as an array.
 * UserPref values that were not declared as lists are treated as
 * one-element arrays.
 *
 * @param {String} key The preference to fetch
 * @return {Array.<String>} The preference; if not set, an empty array
 */
gadgets.Prefs.prototype.getArray = function(key) {
  var val = prefs[key];
  if (val) {
    var arr = val.split("|");
    // Decode pipe characters.
    for (var i = 0, j = arr.length; i < j; ++i) {
      arr[i] = esc(arr[i].replace(/%7C/g, "|"));
    }
    return arr;
  }
  return [];
};

/**
 * Stores an array preference.
 * To use this call,
 * the gadget must require the feature setprefs.
 *
 * @param {String} key The pref to store
 * @param {Array} val The values to store
 */
gadgets.Prefs.prototype.setArray = function(key, val) {
  throw new Error("setprefs feature required to make this call.");
};

/**
 * Fetches an unformatted message.
 * @param {String} key The message to fetch
 * @return {String} The message
 */
gadgets.Prefs.prototype.getMsg = function(key) {
  return messages[key] || "";
};

/**
 * Gets the current country, returned as ISO 3166-1 alpha-2 code.
 *
 * @return {String} The country for this module instance
 */
gadgets.Prefs.prototype.getCountry = function() {
  return country;
};

/**
 * Gets the current language the gadget should use when rendering, returned as a
 * ISO 639-1 language code.
 *
 * @return {String} The language for this module instance
 */
gadgets.Prefs.prototype.getLang = function() {
  return language;
};

/**
 * Gets the module id for the current instance.
 *
 * @return {String | Number} The module id for this module instance
 */
gadgets.Prefs.prototype.getModuleId = function() {
  return moduleId;
};

})();
<commit_msg>No longer overwrite empty-string userprefs with default pref values.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * @fileoverview
 *
 * Provides access to user prefs, module dimensions, and messages.
 *
 * Clients can access their preferences by constructing an instance of
 * gadgets.Prefs and passing in their module id.  Example:
 *
 *   var prefs = new gadgets.Prefs();
 *   var name = prefs.getString("name");
 *   var lang = prefs.getLang();
 *
 * Modules with type=url can also use this library to parse arguments passed
 * by URL, but this is not the common case:
 *
 *   <script src="http://apache.org/shindig/prefs.js"></script>
 *   <script>
 *   gadgets.Prefs.parseUrl();
 *   var prefs = new gadgets.Prefs();
 *   var name = prefs.getString("name");
 *   </script≶
 */

var gadgets = gadgets || {};

(function() {

var instance = null;
var prefs = {};
var esc = gadgets.util.escapeString;
var messages = {};
var defaultPrefs = {};
var language = "en";
var country = "US";
var moduleId = 0;

/**
 * Parses all parameters from the url and stores them
 * for later use when creating a new gadgets.Prefs object.
 */
function parseUrl() {
  var params = gadgets.util.getUrlParameters();
  for (var i in params) {
    if (params.hasOwnProperty(i)) {
      if (i.indexOf("up_") === 0 && i.length > 3) {
        prefs[i.substr(3)] = String(params[i]);
      } else if (i === "country") {
        country = params[i];
      } else if (i === "lang") {
        language = params[i];
      } else if (i === "mid") {
        moduleId = params[i];
      }
    }
  }
}

/**
 * Sets default pref values for values left unspecified in the
 * rendering call, but with default_value provided in the spec.
 */
function mergeDefaults() {
  for (var name in defaultPrefs) {
    if (typeof prefs[name] === 'undefined') {
      prefs[name] = defaultPrefs[name];
    }
  }
}

/**
 * @class
 * Provides access to user preferences, module dimensions, and messages.
 *
 * Clients can access their preferences by constructing an instance of
 * gadgets.Prefs and passing in their module id.  Example:
 *

var prefs = new gadgets.Prefs();
var name = prefs.getString("name");
var lang = prefs.getLang();

 *
 * @description Creates a new Prefs object.
 *
 * Note: this is actually a singleton. All prefs are linked. If you're wondering
 * why this is a singleton and not just a collection of package functions, the
 * simple answer is that it's how the spec is written. The spec is written this
 * way for legacy compatibility with igoogle.
 */
gadgets.Prefs = function() {
  if (!instance) {
    parseUrl();
    mergeDefaults();
    instance = this;
  }
  return instance;
};

/**
 * Sets internal values
 */
gadgets.Prefs.setInternal_ = function(key, value) {
  if (typeof key === "string") {
    prefs[key] = value;
  } else {
    for (var k in key) {
      if (key.hasOwnProperty(k)) {
        prefs[k] = key[k];
      }
    }
  }
};

/**
 * Initializes message bundles.
 */
gadgets.Prefs.setMessages_ = function(msgs) {
  messages = msgs;
};

/**
 * Initializes default user prefs values.
 */
gadgets.Prefs.setDefaultPrefs_ = function(defprefs) {
  defaultPrefs = defprefs;
};

/**
 * Retrieves a preference as a string.
 * Returned value will be html entity escaped.
 *
 * @param {String} key The preference to fetch
 * @return {String} The preference; if not set, an empty string
 */
gadgets.Prefs.prototype.getString = function(key) {
  return prefs[key] ? esc(prefs[key]) : "";
};

/*
 * Indicates not to escape string values when retrieving them.
 * This is an internal detail used by _IG_Prefs for backward compatibility.
 */
gadgets.Prefs.prototype.setDontEscape_ = function() {
  esc = function(k) { return k; };
};

/**
 * Retrieves a preference as an integer.
 * @param {String} key The preference to fetch
 * @return {Number} The preference; if not set, 0
 */
gadgets.Prefs.prototype.getInt = function(key) {
  var val = parseInt(prefs[key], 10);
  return isNaN(val) ? 0 : val;
};

/**
 * Retrieves a preference as a floating-point value.
 * @param {String} key The preference to fetch
 * @return {Number} The preference; if not set, 0
 */
gadgets.Prefs.prototype.getFloat = function(key) {
  var val = parseFloat(prefs[key]);
  return isNaN(val) ? 0 : val;
};

/**
 * Retrieves a preference as a boolean.
 * @param {String} key The preference to fetch
 * @return {Boolean} The preference; if not set, false
 */
gadgets.Prefs.prototype.getBool = function(key) {
  var val = prefs[key];
  if (val) {
    return val === "true" || val === true || !!parseInt(val, 10);
  }
  return false;
};

/**
 * Stores a preference.
 * To use this call,
 * the gadget must require the feature setprefs.
 *
 *

 * Note:
 * If the gadget needs to store an Array it should use setArray instead of
 * this call.
 *

 *
 * @param {String} key The pref to store
 * @param {Object} val The values to store
 */
gadgets.Prefs.prototype.set = function(key, value) {
  throw new Error("setprefs feature required to make this call.");
};

/**
 * Retrieves a preference as an array.
 * UserPref values that were not declared as lists are treated as
 * one-element arrays.
 *
 * @param {String} key The preference to fetch
 * @return {Array.<String>} The preference; if not set, an empty array
 */
gadgets.Prefs.prototype.getArray = function(key) {
  var val = prefs[key];
  if (val) {
    var arr = val.split("|");
    // Decode pipe characters.
    for (var i = 0, j = arr.length; i < j; ++i) {
      arr[i] = esc(arr[i].replace(/%7C/g, "|"));
    }
    return arr;
  }
  return [];
};

/**
 * Stores an array preference.
 * To use this call,
 * the gadget must require the feature setprefs.
 *
 * @param {String} key The pref to store
 * @param {Array} val The values to store
 */
gadgets.Prefs.prototype.setArray = function(key, val) {
  throw new Error("setprefs feature required to make this call.");
};

/**
 * Fetches an unformatted message.
 * @param {String} key The message to fetch
 * @return {String} The message
 */
gadgets.Prefs.prototype.getMsg = function(key) {
  return messages[key] || "";
};

/**
 * Gets the current country, returned as ISO 3166-1 alpha-2 code.
 *
 * @return {String} The country for this module instance
 */
gadgets.Prefs.prototype.getCountry = function() {
  return country;
};

/**
 * Gets the current language the gadget should use when rendering, returned as a
 * ISO 639-1 language code.
 *
 * @return {String} The language for this module instance
 */
gadgets.Prefs.prototype.getLang = function() {
  return language;
};

/**
 * Gets the module id for the current instance.
 *
 * @return {String | Number} The module id for this module instance
 */
gadgets.Prefs.prototype.getModuleId = function() {
  return moduleId;
};

})();
<|endoftext|>


<commit_before>'use strict';

angular.module('hateoasUiApp')
  .controller('CollectionCtrl', ['$scope', '$rootScope', '$location',
    function ($scope, $rootScope, $location) {
      /**
       * Handle a link being clicked.
       */
      $scope.$on('linkClicked', function (e, link) {
        switch (link.method) {
        case 'POST':
          $location.url(
            '/view?model=' + (link.schema.$ref.indexOf('/') === 0 ? link.schema.$ref.substr(1) : link.schema.$ref) +
            '&create=' + (link.href.indexOf('/') === 0 ? link.href.substr(1) : link.href)
          );
          break;
        default:
          $location.url('/view?res=/' + (link.href.indexOf('/') === 0 ? link.href.substr(1) : link.href));
        }
      });

      /**
       * Handle an item in the collection being clicked.
       */
      $scope.itemClick = function (item) {
        $location.url('view?res=' + item.uri);
      };
    }
  ]);<commit_msg>url consistency<commit_after>'use strict';

angular.module('hateoasUiApp')
  .controller('CollectionCtrl', ['$scope', '$rootScope', '$location',
    function ($scope, $rootScope, $location) {
      /**
       * Handle a link being clicked.
       */
      $scope.$on('linkClicked', function (e, link) {
        switch (link.method) {
        case 'POST':
          $location.url(
            '/view?model=' + (link.schema.$ref.indexOf('/') === 0 ? link.schema.$ref.substr(1) : link.schema.$ref) +
            '&create=' + (link.href.indexOf('/') === 0 ? link.href.substr(1) : link.href)
          );
          break;
        default:
          $location.url('/view?res=' + (link.href.indexOf('/') === 0 ? link.href.substr(1) : link.href));
        }
      });

      /**
       * Handle an item in the collection being clicked.
       */
      $scope.itemClick = function (item) {
        $location.url('view?res=' + item.uri);
      };
    }
  ]);<|endoftext|>


<commit_before>import React from 'react';
// import CloudinaryImage from 'react-cloudinary-img';
import ItemsTableValue from '../../../admin/client/components/ItemsTableValue';

const IMAGE_SIZE = 18;

const linkStyle = {
	marginRight: 8,
};
const boxStyle = {
	borderRadius: 3,
	display: 'inline-block',
	height: IMAGE_SIZE,
	overflow: 'hidden',
	verticalAlign: 'middle',
	width: IMAGE_SIZE,
};
const imageStyle = {
	display: 'block',
	height: IMAGE_SIZE,
	left: '50%',
	position: 'relative',

	WebkitTransform: 'translateX(-50%)',
	MozTransform:    'translateX(-50%)',
	msTransform:     'translateX(-50%)',
	transform:       'translateX(-50%)',
};
const textStyle = {
	color: '#888',
	display: 'inline-block',
	fontSize: '.8rem',
	marginLeft: 8,
	verticalAlign: 'middle'
};

var CloudinaryImageSummary = React.createClass({
	displayName: 'CloudinaryImageSummary',
	propTypes: {
		label: React.PropTypes.oneOf(['dimensions', 'publicId']),
		image: React.PropTypes.object.isRequired,
	},
	renderLabel () {
		if (!this.props.label) return;

		let { label, image } = this.props;

		let text;
		if (label === 'dimensions') {
			text = `${image.width} × ${image.height}`;
		} else {
			text = `${image.public_id}.${image.format}`;
		}

		return (

				{text}

		);
	},
	renderImageThumbnail () {
		if (!this.props.image) return;

		let url = this.props.image.url.replace(/image\/upload/, `image/upload/c_thumb,g_face,h_${IMAGE_SIZE},w_${IMAGE_SIZE}`);

		return ;
	},
	render () {
		return (

					{this.renderImageThumbnail()}

				{this.renderLabel()}

		);
	}
});

module.exports = CloudinaryImageSummary;
<commit_msg>Remove duplicates<commit_after>import React from 'react';
// import CloudinaryImage from 'react-cloudinary-img';
import ItemsTableValue from '../../../admin/client/components/ItemsTableValue';

const IMAGE_SIZE = 18;

const linkStyle = {
	marginRight: 8,
};
const boxStyle = {
	borderRadius: 3,
	display: 'inline-block',
	height: IMAGE_SIZE,
	overflow: 'hidden',
	verticalAlign: 'middle',
	width: IMAGE_SIZE,
};
const imageStyle = {
	display: 'block',
	height: IMAGE_SIZE,
	left: '50%',
	position: 'relative',

	WebkitTransform: 'translateX(-50%)',
	MozTransform:    'translateX(-50%)',
	msTransform:     'translateX(-50%)',
	transform:       'translateX(-50%)',
};
const textStyle = {
	color: '#888',
	display: 'inline-block',
	fontSize: '.8rem',
	marginLeft: 8,
	verticalAlign: 'middle'
};

var CloudinaryImageSummary = React.createClass({
	displayName: 'CloudinaryImageSummary',
	propTypes: {
		label: React.PropTypes.oneOf(['dimensions', 'publicId']),
		image: React.PropTypes.object.isRequired,
	},
	renderLabel () {
		if (!this.props.label) return;

		let { label, image } = this.props;

		let text;
		if (label === 'dimensions') {
			text = `${image.width} × ${image.height}`;
		} else {
			text = `${image.public_id}.${image.format}`;
		}

		return (

				{text}

		);
	},
	renderImageThumbnail () {
		if (!this.props.image) return;

		let url = this.props.image.url.replace(/image\/upload/, `image/upload/c_thumb,g_face,h_${IMAGE_SIZE},w_${IMAGE_SIZE}`);

		return ;
	},
	render () {
		return (

					{this.renderImageThumbnail()}

				{this.renderLabel()}

		);
	}
});

module.exports = CloudinaryImageSummary;
<|endoftext|>


<commit_before>'use strict';

angular.module('app')
  .controller('ServerDataCtrl', function ($scope, webSocket, Gateway, settings, RandomValueDataModel, WebSocketDataModel, TimeSeriesDataModel, PieChartDataModel) {
    $scope.value1 = 'not defined';
    $scope.value2 = 'not defined';

    var widgetDefinitions = [
      {
        name: 'Value',
        directive: 'wt-scope-watch',
        dataAttrName: 'value',
        attrs: {
          'value-class': 'alert-info'
        },
        dataTypes: ['percentage', 'simple'],
        dataModelType: WebSocketDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.piValue
        }
      },
      {
        name: 'Progressbar',
        directive: 'progressbar',
        attrs: {
          class: 'progress-striped',
          type: 'success'
        },
        dataAttrName: 'value',
        dataTypes: ['percentage', 'simple'],
        dataModelType: WebSocketDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.progress
        }
      },
      {
        name: 'Line Chart',
        directive: 'wt-line-chart',
        dataAttrName: 'chart',
        dataTypes: ['timeseries'],
        dataModelType: TimeSeriesDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.chartValue
        },
        style: {
          width: '50%'
        }
      },
      {
        name: 'TopN',
        directive: 'wt-top-n',
        attrs: {
          data: 'serverTopTen'
        },
        dataAttrName: 'data',
        dataTypes: ['topN'],
        dataModelType: WebSocketDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.topn
        }
      },
      {
        name: 'Pie Chart',
        directive: 'wt-pie-chart',
        style: {
          width: '350px',
          height: '350px'
        },
        dataAttrName: 'data',
        dataTypes: ['piechart'],
        dataModelType: PieChartDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.pieChart
        }
      },
      {
        name: 'Gauge',
        directive: 'wt-gauge',
        dataAttrName: 'value',
        dataTypes: ['percentage', 'simple'],
        dataModelType: WebSocketDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.percentage
        },
        style: {
          width: '250px'
        }
      },
      {
        name: 'JSON',
        directive: 'wt-json',
        dataAttrName: 'value',
        dataModelType: WebSocketDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.topn
        }
      },
      {
        name: 'WebSocket Debugger',
        templateUrl: 'template/topics.html'
      }
    ];

    function find(name) {
      return _.findWhere(widgetDefinitions, {name: name});
    }

    function copy(name, extend) {
      var dest = angular.copy(find(name));

      if (extend) {
        angular.extend(dest, extend);
      }

      return dest;
    }

    //var defaultWidgets = _.clone(widgetDefinitions);
    var defaultWidgets = [
      copy('Value', {
        title: 'Value 1'
      }),
      copy('Value', {
        title: 'Value 2',
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.percentage
        }
      }),
      copy('Progressbar', {
        title: 'Progressbar'
      }),
      copy('Line Chart', {
        title: 'Line Chart 1'
      }),
      copy('Line Chart', {
        title: 'Line Chart 2',
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.chartValue2
        }
      }),
      copy('TopN', {
        title: 'Top N'
      }),
      copy('Pie Chart', {
        title: 'Pie Chart'
      }),
      copy('Gauge', {
        title: 'Gauge'
      }),
      copy('JSON', {
        title: 'JSON'
      }),
      copy('WebSocket Debugger', {
        title: 'WebSocket Debugger'
      })
    ];

    $scope.dashboardOptions = {
      useLocalStorage: true, //TODO enable by default
      widgetButtons: true,
      widgetDefinitions: widgetDefinitions,
      defaultWidgets: defaultWidgets,
      optionsTemplateUrl: 'template/widgetOptions.html'
    };

    // initialize widgets with default topics
    var topicsPromise = Gateway.getTopics();

    $scope.$on('widgetAdded', function (event, widget) {
      event.stopPropagation();

      if (widget.dataModel && widget.dataModelOptions && widget.dataModelOptions.defaultTopic) {
        topicsPromise.then(function (topics) {
          var defaultTopic = widget.dataModelOptions.defaultTopic;

          var topic = _.find(topics, function (topic) {
            return topic.name.indexOf(defaultTopic) >= 0;
          });

          if (topic) {
            widget.dataModel.update(topic.topic);
          }
        });
      }
    });
  });<commit_msg>Widget Definitions<commit_after>'use strict';

angular.module('app')
  .controller('ServerDataCtrl', function ($scope, webSocket, Gateway, settings, RandomValueDataModel, WebSocketDataModel, TimeSeriesDataModel, PieChartDataModel) {
    $scope.value1 = 'not defined';
    $scope.value2 = 'not defined';

    var widgetDefinitions = [
      {
        name: 'Value',
        directive: 'wt-scope-watch',
        dataAttrName: 'value',
        attrs: {
          'value-class': 'alert-info'
        },
        dataTypes: ['percentage', 'simple'],
        dataModelType: WebSocketDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.piValue
        }
      },
      {
        name: 'Progressbar',
        directive: 'progressbar',
        attrs: {
          class: 'progress-striped',
          type: 'success'
        },
        dataAttrName: 'value',
        dataTypes: ['percentage', 'simple'],
        dataModelType: WebSocketDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.progress
        }
      },
      {
        name: 'Line Chart',
        directive: 'wt-line-chart',
        dataAttrName: 'chart',
        dataTypes: ['timeseries'],
        dataModelType: TimeSeriesDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.chartValue
        },
        style: {
          width: '50%'
        }
      },
      {
        name: 'TopN',
        directive: 'wt-top-n',
        attrs: {
          data: 'serverTopTen'
        },
        dataAttrName: 'data',
        dataTypes: ['topN'],
        dataModelType: WebSocketDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.topn
        }
      },
      {
        name: 'Pie Chart',
        directive: 'wt-pie-chart',
        style: {
          width: '350px',
          height: '350px'
        },
        dataAttrName: 'data',
        dataTypes: ['piechart'],
        dataModelType: PieChartDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.pieChart
        }
      },
      {
        name: 'Gauge',
        directive: 'wt-gauge',
        dataAttrName: 'value',
        dataTypes: ['percentage', 'simple'],
        dataModelType: WebSocketDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.percentage
        },
        style: {
          width: '250px'
        }
      },
      {
        name: 'JSON',
        directive: 'wt-json',
        dataAttrName: 'value',
        dataModelType: WebSocketDataModel,
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.topn
        }
      },
      {
        name: 'WebSocket Debugger',
        templateUrl: 'template/topics.html'
      }
    ];

    var defaultWidgets = [
      {
        name: 'Value',
        title: 'Value 1'
      },
      {
        name: 'Value',
        title: 'Value 2',
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.percentage
        }
      },
      {
        name: 'Progressbar',
        title: 'Progressbar'
      },
      {
        name: 'Line Chart',
        title: 'Line Chart 1'
      },
      {
        name: 'Line Chart',
        title: 'Line Chart 2',
        dataModelOptions: {
          defaultTopic: settings.topic.visualdata.chartValue2
        }
      },
      {
        name: 'TopN',
        title: 'Top N'
      },
      {
        name: 'Pie Chart',
        title: 'Pie Chart'
      },
      {
        name: 'JSON',
        title: 'JSON'
      },
      {
        name: 'WebSocket Debugger',
        title: 'WebSocket Debugger'
      }
    ];

    $scope.dashboardOptions = {
      //useLocalStorage: true, //TODO enable by default
      widgetButtons: true,
      widgetDefinitions: widgetDefinitions,
      defaultWidgets: defaultWidgets,
      optionsTemplateUrl: 'template/widgetOptions.html'
    };

    // initialize widgets with default topics
    var topicsPromise = Gateway.getTopics();

    $scope.$on('widgetAdded', function (event, widget) {
      event.stopPropagation();

      if (widget.dataModel && widget.dataModelOptions && widget.dataModelOptions.defaultTopic) {
        topicsPromise.then(function (topics) {
          var defaultTopic = widget.dataModelOptions.defaultTopic;

          var topic = _.find(topics, function (topic) {
            return topic.name.indexOf(defaultTopic) >= 0;
          });

          if (topic) {
            widget.dataModel.update(topic.topic);
          }
        });
      }
    });
  });<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var StringCalculator = function() {

  var replaceNewlinesWithCommas = function(x) {
    return x.replace('\n', ',');
  };

  var tokenize = function(x,delim) {
    return x.split(delim);
  };

  var isCustomDelimiter = function(x) {
     if (x.indexOf('//') === 0) {
       return x.substr(2,1);
     } else {
       return ',';
     }
  };

  var stripDelimiter = function(x) {
    return (x.indexOf('//') === 0) ? x.substr(4) : x;
  };

  var tidyString = function(x) {
    return replaceNewlinesWithCommas(stripDelimiter(x));
  };

  var shouldIgnore = function(n) { return n > 1000; };

  return {
    add: function(s) {

      var delimiter = isCustomDelimiter(s);
      s = tidyString(s);
      var tokens = tokenize(s, delimiter);
      var sum = 0;

      var illegal = [];

      for (var i=0;i<tokens.length;++i) {
        var num = tokens[i]|0;
        if (shouldIgnore(num)) {
          continue;
        }

        sum += num;
        if (num < 0) {
          illegal.push(num);
        }
      }

      if (illegal.length !== 0) {
        throw new Error(illegal);
      }

      return sum;
    }
  };
};

describe('string calculator', function() {
  it('should exist', function() {
    assert(new StringCalculator());
  });

  it('has an add method', function() {
    assert(new StringCalculator().add);
  });

  describe('add', function() {

    var stringCalculator = new StringCalculator();

    it('returns the empty string for 0', function() {
      assert.equal(0, stringCalculator.add(''));
    });

    it('is identity for a single number', function() {
      assert.equal(123, stringCalculator.add('123'));
    });

    it('adds two numbers', function() {
      assert.equal(4, stringCalculator.add('1,3'));
    });

    it('adds all numbers', function() {
      assert.equal(6, stringCalculator.add('1,2,3'));
    });

    it('treats newlines as delimiters', function() {
      assert.equal(4, stringCalculator.add('1\n3'));
    });

    it('supports custom delimiters', function() {
      assert.equal(5, stringCalculator.add('//q\n1q4'));
    });

    it('disallows negatives', function() {
      assert.throws(function() { stringCalculator.add('-1'); });
    });

    it('reports all', function() {
      assert.throws(function() { stringCalculator.add('-1\n-2'); }, function(x) {
        return x.message.indexOf('-1,-2') >= 0;
      });
    });

    it('numbers greater than 1000 ignored', function() {
      assert.equal(5, stringCalculator.add('5,1005'));
    });
  });
});<commit_msg>further refactor<commit_after>"use strict";

var assert = require('assert');

var StringCalculator = function() {

  var replaceNewlinesWithCommas = function(x) {
    return x.replace('\n', ',');
  };

  var tokenize = function(x,delim) {
    return x.split(delim);
  };

  var isCustomDelimiter = function(x) {
     if (x.indexOf('//') === 0) {
       return x.substr(2,1);
     } else {
       return ',';
     }
  };

  var stripDelimiter = function(x) {
    return (x.indexOf('//') === 0) ? x.substr(4) : x;
  };

  var tidyString = function(x) {
    return replaceNewlinesWithCommas(stripDelimiter(x));
  };

  var shouldIgnore = function(n) { return n > 1000; };
  var isIllegal = function(n) { return n < 0; };

  return {
    add: function(s) {

      var delimiter = isCustomDelimiter(s);
      s = tidyString(s);
      var tokens = tokenize(s, delimiter);
      var sum = 0;

      var illegal = [];

      for (var i=0;i<tokens.length;++i) {
        var num = tokens[i]|0;
        if (shouldIgnore(num)) {
          continue;
        }

        if (isIllegal(num)) {
          illegal.push(num);
        }

        sum += num;
      }

      if (illegal.length !== 0) {
        throw new Error(illegal);
      }

      return sum;
    }
  };
};

describe('string calculator', function() {
  it('should exist', function() {
    assert(new StringCalculator());
  });

  it('has an add method', function() {
    assert(new StringCalculator().add);
  });

  describe('add', function() {

    var stringCalculator = new StringCalculator();

    it('returns the empty string for 0', function() {
      assert.equal(0, stringCalculator.add(''));
    });

    it('is identity for a single number', function() {
      assert.equal(123, stringCalculator.add('123'));
    });

    it('adds two numbers', function() {
      assert.equal(4, stringCalculator.add('1,3'));
    });

    it('adds all numbers', function() {
      assert.equal(6, stringCalculator.add('1,2,3'));
    });

    it('treats newlines as delimiters', function() {
      assert.equal(4, stringCalculator.add('1\n3'));
    });

    it('supports custom delimiters', function() {
      assert.equal(5, stringCalculator.add('//q\n1q4'));
    });

    it('disallows negatives', function() {
      assert.throws(function() { stringCalculator.add('-1'); });
    });

    it('reports all', function() {
      assert.throws(function() { stringCalculator.add('-1\n-2'); }, function(x) {
        return x.message.indexOf('-1,-2') >= 0;
      });
    });

    it('numbers greater than 1000 ignored', function() {
      assert.equal(5, stringCalculator.add('5,1005'));
    });
  });
});<|endoftext|>


<commit_before>import Ember from 'ember';
export default Ember.Route.extend({
  session: Ember.inject.service(),
  beforeModel: function() {
    return this.get('session').fetch().catch(function() {});
  },
  actions: {
    signOut: function() {
      this.get('session').close();
    },
    refreshModel: function() {
      if (this.get('session.isAuthenticated')){
        this.refresh();
      }
    }
  },
  model() {
    if (this.get('session.isAuthenticated')){
      return this.store.findRecord('user', this.get('session.currentUser.uid'));
    }
  }
});
<commit_msg>Update application.js<commit_after>import Ember from 'ember';

export default Ember.Route.extend({
  session: Ember.inject.service(),

  beforeModel() {
    return this.get('session').fetch().catch(function() {});
  },

  model() {
    if (this.get('session.isAuthenticated')){
      return this.store.findRecord('user', this.get('session.currentUser.uid'));
    }
  },

  actions: {
    signOut() {
      this.get('session').close();
    },
    refreshModel() {
      if (this.get('session.isAuthenticated')){
        this.refresh();
      }
    }
  }
});
<|endoftext|>