<commit_before>var test = require('tape');
var utils = require('../utils');
var acetate = require('../../../index.js');

var path = require('path');
var async = require('async');
var fs = require('fs');
var _ = require('lodash');

var root = __dirname;

acetate({
  log: 'silent',
  root: root,
  clean: true
}, function(error, site){
  test('should build a page with data from a module', function (t) {
    t.plan(1);

    var output = 'build/dynamic-data/index.html';
    var expected = 'expected/dynamic-data.html';

    async.parallel({
      actual: _.partial(fs.readFile, path.join(root, output)),
      expected: _.partial(fs.readFile, path.join(root, expected))
    }, function(error, results){
      t.equal(results.actual.toString(), results.expected.toString());
    });

    // utils.equal(t, root, output, expected);
  });

  test('should build a page with data from a json file', function (t) {
    t.plan(1);

    var output = 'build/json-data/index.html';
    var expected = 'expected/json-data.html';

    utils.equal(t, root, output, expected);
  });

  test('should build a page with data from a yaml file', function (t) {
    t.plan(1);

    var output = 'build/yaml-data/index.html';
    var expected = 'expected/yaml-data.html';

    utils.equal(t, root, output, expected);
  });

  test('should build a page with data from a yml file', function (t) {
    t.plan(1);

    var output = 'build/yml-data/index.html';
    var expected = 'expected/yml-data.html';

    utils.equal(t, root, output, expected);
  });

  test('should build a page with global data from config file', function (t) {
    t.plan(1);

    var output = 'build/global-data/index.html';
    var expected = 'expected/global-data.html';

    utils.equal(t, root, output, expected);
  });

  test('should override global with a local declaration', function (t) {
    t.plan(1);

    var output = 'build/override-data/index.html';
    var expected = 'expected/override-data.html';

    utils.equal(t, root, output, expected);
  });

  test('should be able to require many data files', function (t) {
    t.plan(1);

    var output = 'build/all-data/index.html';
    var expected = 'expected/all-data.html';

    utils.equal(t, root, output, expected);
  });

});<commit_msg>cleanup<commit_after>var test = require('tape');
var utils = require('../utils');
var acetate = require('../../../index.js');

var root = __dirname;

acetate({
  log: 'silent',
  root: root,
  clean: true
}, function(error, site){
  test('should build a page with data from a module', function (t) {
    t.plan(1);

    var output = 'build/dynamic-data/index.html';
    var expected = 'expected/dynamic-data.html';

    utils.equal(t, root, output, expected);
  });

  test('should build a page with data from a json file', function (t) {
    t.plan(1);

    var output = 'build/json-data/index.html';
    var expected = 'expected/json-data.html';

    utils.equal(t, root, output, expected);
  });

  test('should build a page with data from a yaml file', function (t) {
    t.plan(1);

    var output = 'build/yaml-data/index.html';
    var expected = 'expected/yaml-data.html';

    utils.equal(t, root, output, expected);
  });

  test('should build a page with data from a yml file', function (t) {
    t.plan(1);

    var output = 'build/yml-data/index.html';
    var expected = 'expected/yml-data.html';

    utils.equal(t, root, output, expected);
  });

  test('should build a page with global data from config file', function (t) {
    t.plan(1);

    var output = 'build/global-data/index.html';
    var expected = 'expected/global-data.html';

    utils.equal(t, root, output, expected);
  });

  test('should override global with a local declaration', function (t) {
    t.plan(1);

    var output = 'build/override-data/index.html';
    var expected = 'expected/override-data.html';

    utils.equal(t, root, output, expected);
  });

  test('should be able to require many data files', function (t) {
    t.plan(1);

    var output = 'build/all-data/index.html';
    var expected = 'expected/all-data.html';

    utils.equal(t, root, output, expected);
  });

});<|endoftext|>


<commit_before>/* global window */

window.deprecationWorkflow = window.deprecationWorkflow || {};
window.deprecationWorkflow.config = {
  workflow: [
    { handler: "silence", matchId: "ember-cli-page-object.old-collection-api"},
    { handler: "silence", matchId: "ember-metal.run.sync"},
    { handler: "silence", matchId: "ember-routing.route-router"},
    { handler: "silence", matchId: "ember-runtime.deprecate-copy-copyable"},
  ]
};
<commit_msg>Ignore new deprecations for now<commit_after>/* global window */

window.deprecationWorkflow = window.deprecationWorkflow || {};
window.deprecationWorkflow.config = {
  workflow: [
    { handler: "silence", matchId: "ember-cli-page-object.old-collection-api"},
    { handler: "silence", matchId: "ember-metal.run.sync"},
    { handler: "silence", matchId: "ember-routing.route-router"},
    { handler: "silence", matchId: "ember-runtime.deprecate-copy-copyable"},
    { handler: "silence", matchId: "ember-polyfills.deprecate-merge"},
    { handler: "silence", matchId: "deprecate-router-events"},
  ]
};
<|endoftext|>


<commit_before>var globals = require('../globals'),
  util = require('../util');

module.exports = stacking;

function stacking(spec, encoding, mdef, facets) {
  if (!marks[encoding.marktype()].stack) return false;
  if (!encoding.has(COLOR)) return false;

  var dim = X, val = Y, idx = 1;
  if (encoding.isType(X, Q | T) && !encoding.isType(Y, Q | T) && encoding.has(Y)) {
    dim = Y;
    val = X;
    idx = 0;
  }

  // add transform to compute sums for scale
  var stacked = {
    name: STACKED,
    source: TABLE,
    transform: [{
      type: 'aggregate',
      groupby: [encoding.field(dim)].concat(facets), // dim and other facets
      fields: [{op: 'sum', field: encoding.field(val)}] // TODO check if field with aggr is correct?
    }]
  };

  if (facets && facets.length > 0) {
    stacked.transform.push({ //calculate max for each facet
      type: 'aggregate',
      groupby: facets,
      fields: [{op: 'max', field: 'data.sum_' + encoding.field(val, true)}]
    });
  }

  spec.data.push(stacked);

  // add stack transform to mark
  mdef.from.transform = [{
    type: 'stack',
    point: encoding.field(dim),
    height: encoding.field(val),
    output: {y1: val, y0: val + '2'}
  }];

  // TODO: This is super hack-ish -- consolidate into modular mark properties?
  mdef.properties.update[val] = mdef.properties.enter[val] = {scale: val, field: val};
  mdef.properties.update[val + '2'] = mdef.properties.enter[val + '2'] = {scale: val, field: val + '2'};

  return val; //return stack encoding
}
<commit_msg>fix missing require in stacking.js<commit_after>"use strict";

var globals = require('../globals'),
  util = require('../util'),
  marks = require('./marks');

module.exports = stacking;

function stacking(spec, encoding, mdef, facets) {
  if (!marks[encoding.marktype()].stack) return false;
  if (!encoding.has(COLOR)) return false;

  var dim = X, val = Y, idx = 1;
  if (encoding.isType(X, Q | T) && !encoding.isType(Y, Q | T) && encoding.has(Y)) {
    dim = Y;
    val = X;
    idx = 0;
  }

  // add transform to compute sums for scale
  var stacked = {
    name: STACKED,
    source: TABLE,
    transform: [{
      type: 'aggregate',
      groupby: [encoding.field(dim)].concat(facets), // dim and other facets
      fields: [{op: 'sum', field: encoding.field(val)}] // TODO check if field with aggr is correct?
    }]
  };

  if (facets && facets.length > 0) {
    stacked.transform.push({ //calculate max for each facet
      type: 'aggregate',
      groupby: facets,
      fields: [{op: 'max', field: 'data.sum_' + encoding.field(val, true)}]
    });
  }

  spec.data.push(stacked);

  // add stack transform to mark
  mdef.from.transform = [{
    type: 'stack',
    point: encoding.field(dim),
    height: encoding.field(val),
    output: {y1: val, y0: val + '2'}
  }];

  // TODO: This is super hack-ish -- consolidate into modular mark properties?
  mdef.properties.update[val] = mdef.properties.enter[val] = {scale: val, field: val};
  mdef.properties.update[val + '2'] = mdef.properties.enter[val + '2'] = {scale: val, field: val + '2'};

  return val; //return stack encoding
}
<|endoftext|>


<commit_before>
const RG = require('./rg.js');
RG.Random = require('./random');

// Default configuration for creation
const defaultConf = {
    seed: 0,
    // Direct impact on low-level stuff
    difficulty: 'Medium',
    items: 'Medium',
    monsters: 'Medium',

    worldSize: 'Medium',
    areaSize: 'Medium',

    // World generation params
    climate: 'Medium',
    elevation: 'Medium',
    excavation: 'Medium',
    forestation: 'Medium',
    population: 'Medium',
    size: 'Medium',
    water: 'Sparse'
};

// Maps sizes such as Small or Medium to numbers
const worldSizeToNum = {
    Small: 1,
    Medium: 2,
    Large: 4,
    Huge: 8
};

// Maps sizes such as Small or Medium to numbers
const areaSizeToXY = {
    Small: {x: 3, y: 3},
    Medium: {x: 5, y: 5},
    Large: {x: 5, y: 7},
    Huge: {x: 7, y: 9}
};

// Elevation created using noise, map to thresholds. We need
/* const elevToThr = {

}; */

// Climate created using linear gradient, right now simply from south (high Y)
// to north (low Y, down to 0).
// 0 = zero degrees C, warm > 0, cold < 0. Determines amount of snow.
// At low-level, this can be achieved with snow ratio from 0 -> 1.
/* const climateToGradient = {
    Warm: 0.5,
    Medium: 0.3,
    Cold: 0.1,
    Freezing: -0.2
};*/

/* The object creates the initial high-level world configuration which is used
 * to build the world containing all playable levels.
 * NOTE: To keep the code shorter, 'conf' refers always to the global
 * configuration. It's always the last param for each function.
 */
const Creator = function() {

    // Assumptions: Increase difficulty the more player travels from starting
    // position. Start is always at Math.floor(xMax/2), yMax.
    // Moving between areas is equivalent of X difficulty steps increase

    this.createWorldConf = function(conf) {
        // Assign user conf over default first
        Object.keys(defaultConf).forEach(key => {
            if (!conf.hasOwnProperty(key)) {
                conf[key] = defaultConf[key];
            }
        });

        this.rand = new RG.Random();
        this.rand.setSeed(conf.seed);

        const areas = this.createAreasConf(conf);
        const playerStart = this.getPlayerStart(areas, conf);
        return {
            name: conf.name,
            nAreas: areas.length,
            area: areas,
            playerStart
        };
    };

    /* Create object for player position. */
    this.getPlayerStart = function(areas, conf) {
        const firstArea = areas[0];
        const maxY = firstArea.maxY;
        const midX = Math.floor(firstArea.maxX);
        return {
            place: conf.name, // rename to area.name
            x: midX, y: maxY
        };
    };

    //---------------
    // AREAS
    //---------------

    this.createAreasConf = function(conf) {
        const nAreas = worldSizeToNum[conf.worldSize];
        const areas = [];
        for (let i = 0; i < nAreas; i++) {
            const areaConf = this.createSingleAreaConf(i, conf);
            areas.push(areaConf);
        }
        return areas;
    };

    /* Creates configuration for single area. Assume player starts at areaNum ==
     * 0, and adjust difficulty accordingly. */
    this.createSingleAreaConf = function(areaNum, conf) {
        const areaSize = areaSizeToXY[conf.areaSize];
        const maxX = areaSize.x;
        const maxY = areaSize.y;

        // Need to pass this info other functions to determine number of
        // features and difficulty
        const areaConf = {
            maxX, maxY, areaNum
        };

        // Finally, get config for different sub-features in the world
        const dungeons = this.createDungeonsConf(areaConf, conf);
        const cities = this.createCitiesConf(areaConf, conf);
        const mountains = this.createMountainsConf(areaConf, conf);

        return {
            maxX,
            maxY,
            nDungeons: dungeons.length,
            nCities: cities.length,
            nMountains: mountains.length,
            dungeon: dungeons,
            city: cities,
            mountain: mountains
        };
    };

    //---------------
    // DUNGEONS
    //---------------

    // :w
    this.createDungeonsConf = function(areaConf, conf) {
        const nDungeons = this.getNumFeatures('dungeon', areaConf, conf);
        const dungeons = [];
        for (let i = 0; i < nDungeons; i++) {
            const dungeon = this.createSingleDungeonConf(areaConf, conf);
            dungeons.push(dungeon);
        }
        return dungeons;
    };

    /* Creates conf for a single dungeon. */
    this.createSingleDungeonConf = function(areaConf, conf) {
        const xy = this.getXYInArea(areaConf);
        const dungeonConf = Object.assign({}, areaConf);
        dungeonConf.x = xy.x;
        dungeonConf.y = xy.y;

        const branches = this.createBranchesConf(dungeonConf, conf);
        const connect = this.createBranchConnections(branches);

        const obj = {
            name: '',
            x: xy.x,
            y: xy.y,
            nBranches: branches.length,
            branch: branches
        };
        if (connect) {obj.connect = connect;}
    };

    /* Creates branches config for dungeon. This include entrance and branch
     * connections. */
    this.createBranchesConf = function(dungeonConf, conf) {
        const nBranches = this.getNumBranches(dungeonConf);
        const branches = [];
        for (let i = 0; i < nBranches; i++) {
            const branch = this.createSingleBranchConf(dungeonConf, conf);
            branches.push(branch);

            // For now, entrance is always from level 0 of br 0
            if (i === 0) {
                branch.entranceLevel = 0;
            }
        }
        return branches;
    };

    this.createSingleBranchConf = function(dungeonConf, conf) {
        const nLevels = this.getNumLevels(dungeonConf, conf);
        return {
            name: this.getName('branch'),
            nLevels
        };
    };

    //---------------
    // CITIES
    //---------------

    this.createCitiesConf = function(areaConf, conf) {
        return [];
    };

    //---------------
    // MOUNTAINS
    //---------------

    this.createMountainsConf = function(areaNum, conf) {
        return [];
    };

    this.getDifficulty = function(x, y) {

    };

    /* Returns the number of features that should be generated. */
    this.getNumFeatures = function(type, areaConf, conf) {
        let nFeatures = (areaConf.maxX + 1) * (areaConf.maxY + 1);
        // TODO based on type/conf, adjust the number
        nFeatures += nFeatures * this.rand.getNormal();
        return nFeatures;
    };

    /* Given areaConf, return x,y position where the feature can be added. */
    this.getXYInArea = function(areaConf) {
        return {
            x: this.rand.getUniformInt(0, areaConf.maxX),
            y: this.rand.getUniformInt(0, areaConf.maxY)
        };
    };

    /* Returns more branches for dungeons further
     * from starting position. */
    this.getNumBranches = function(dungeonConf) {

    };

    //-------------------
    // CONNECTING STUFF
    //-------------------

    /* Loops through feature list and connects them together. The connections
     * depend on the type parameter. */
    this.createBranchConnections = function(type, feats) {
        if (feats.length === 1) {return null;}
        const connections = [];
        for (let i = 0; i < feats.length; i++) {

        }
        return connections;

    };

    //----------------------------
    // NAME GEN FUNCTIONS
    // For debugging, names are stupid for now
    //----------------------------

    this.nCreated = {};
    this.getName = function(type) {
        if (!this.nCreated.hasOwnProperty(type)) {
            this.nCreated[type] = 0;
        }
        this.nCreated[type] += 1;
        return `${type} ${this.nCreated[type]}`;
    };

};

module.exports = Creator;
<commit_msg>Added missing arg to createBranchConnections().<commit_after>
const RG = require('./rg.js');
RG.Random = require('./random');

// Default configuration for creation
const defaultConf = {
    seed: 0,
    // Direct impact on low-level stuff
    difficulty: 'Medium',
    items: 'Medium',
    monsters: 'Medium',

    worldSize: 'Medium',
    areaSize: 'Medium',

    // World generation params
    climate: 'Medium',
    elevation: 'Medium',
    excavation: 'Medium',
    forestation: 'Medium',
    population: 'Medium',
    size: 'Medium',
    water: 'Sparse'
};

// Maps sizes such as Small or Medium to numbers
const worldSizeToNum = {
    Small: 1,
    Medium: 2,
    Large: 4,
    Huge: 8
};

// Maps sizes such as Small or Medium to numbers
const areaSizeToXY = {
    Small: {x: 3, y: 3},
    Medium: {x: 5, y: 5},
    Large: {x: 5, y: 7},
    Huge: {x: 7, y: 9}
};

// Elevation created using noise, map to thresholds. We need
/* const elevToThr = {

}; */

// Climate created using linear gradient, right now simply from south (high Y)
// to north (low Y, down to 0).
// 0 = zero degrees C, warm > 0, cold < 0. Determines amount of snow.
// At low-level, this can be achieved with snow ratio from 0 -> 1.
/* const climateToGradient = {
    Warm: 0.5,
    Medium: 0.3,
    Cold: 0.1,
    Freezing: -0.2
};*/

/* The object creates the initial high-level world configuration which is used
 * to build the world containing all playable levels.
 * NOTE: To keep the code shorter, 'conf' refers always to the global
 * configuration. It's always the last param for each function.
 */
const Creator = function() {

    // Assumptions: Increase difficulty the more player travels from starting
    // position. Start is always at Math.floor(xMax/2), yMax.
    // Moving between areas is equivalent of X difficulty steps increase

    this.createWorldConf = function(conf) {
        // Assign user conf over default first
        Object.keys(defaultConf).forEach(key => {
            if (!conf.hasOwnProperty(key)) {
                conf[key] = defaultConf[key];
            }
        });

        this.rand = new RG.Random();
        this.rand.setSeed(conf.seed);

        const areas = this.createAreasConf(conf);
        const playerStart = this.getPlayerStart(areas, conf);
        return {
            name: conf.name,
            nAreas: areas.length,
            area: areas,
            playerStart
        };
    };

    /* Create object for player position. */
    this.getPlayerStart = function(areas, conf) {
        const firstArea = areas[0];
        const maxY = firstArea.maxY;
        const midX = Math.floor(firstArea.maxX);
        return {
            place: conf.name, // rename to area.name
            x: midX, y: maxY
        };
    };

    //---------------
    // AREAS
    //---------------

    this.createAreasConf = function(conf) {
        const nAreas = worldSizeToNum[conf.worldSize];
        const areas = [];
        for (let i = 0; i < nAreas; i++) {
            const areaConf = this.createSingleAreaConf(i, conf);
            areas.push(areaConf);
        }
        return areas;
    };

    /* Creates configuration for single area. Assume player starts at areaNum ==
     * 0, and adjust difficulty accordingly. */
    this.createSingleAreaConf = function(areaNum, conf) {
        const areaSize = areaSizeToXY[conf.areaSize];
        const maxX = areaSize.x;
        const maxY = areaSize.y;

        // Need to pass this info other functions to determine number of
        // features and difficulty
        const areaConf = {
            maxX, maxY, areaNum
        };

        // Finally, get config for different sub-features in the world
        const dungeons = this.createDungeonsConf(areaConf, conf);
        const cities = this.createCitiesConf(areaConf, conf);
        const mountains = this.createMountainsConf(areaConf, conf);

        return {
            maxX,
            maxY,
            nDungeons: dungeons.length,
            nCities: cities.length,
            nMountains: mountains.length,
            dungeon: dungeons,
            city: cities,
            mountain: mountains
        };
    };

    //---------------
    // DUNGEONS
    //---------------

    // :w
    this.createDungeonsConf = function(areaConf, conf) {
        const nDungeons = this.getNumFeatures('dungeon', areaConf, conf);
        const dungeons = [];
        for (let i = 0; i < nDungeons; i++) {
            const dungeon = this.createSingleDungeonConf(areaConf, conf);
            dungeons.push(dungeon);
        }
        return dungeons;
    };

    /* Creates conf for a single dungeon. */
    this.createSingleDungeonConf = function(areaConf, conf) {
        const xy = this.getXYInArea(areaConf);
        const dungeonConf = Object.assign({}, areaConf);
        dungeonConf.x = xy.x;
        dungeonConf.y = xy.y;

        const branches = this.createBranchesConf(dungeonConf, conf);
        const connect = this.createBranchConnections('branch', branches);

        const obj = {
            name: '',
            x: xy.x,
            y: xy.y,
            nBranches: branches.length,
            branch: branches
        };
        if (connect) {obj.connect = connect;}
    };

    /* Creates branches config for dungeon. This include entrance and branch
     * connections. */
    this.createBranchesConf = function(dungeonConf, conf) {
        const nBranches = this.getNumBranches(dungeonConf);
        const branches = [];
        for (let i = 0; i < nBranches; i++) {
            const branch = this.createSingleBranchConf(dungeonConf, conf);
            branches.push(branch);

            // For now, entrance is always from level 0 of br 0
            if (i === 0) {
                branch.entranceLevel = 0;
            }
        }
        return branches;
    };

    this.createSingleBranchConf = function(dungeonConf, conf) {
        const nLevels = this.getNumLevels(dungeonConf, conf);
        return {
            name: this.getName('branch'),
            nLevels
        };
    };

    //---------------
    // CITIES
    //---------------

    this.createCitiesConf = function(areaConf, conf) {
        return [];
    };

    //---------------
    // MOUNTAINS
    //---------------

    this.createMountainsConf = function(areaNum, conf) {
        return [];
    };

    this.getDifficulty = function(x, y) {

    };

    /* Returns the number of features that should be generated. */
    this.getNumFeatures = function(type, areaConf, conf) {
        let nFeatures = (areaConf.maxX + 1) * (areaConf.maxY + 1);
        // TODO based on type/conf, adjust the number
        nFeatures += nFeatures * this.rand.getNormal();
        return nFeatures;
    };

    /* Given areaConf, return x,y position where the feature can be added. */
    this.getXYInArea = function(areaConf) {
        return {
            x: this.rand.getUniformInt(0, areaConf.maxX),
            y: this.rand.getUniformInt(0, areaConf.maxY)
        };
    };

    /* Returns more branches for dungeons further
     * from starting position. */
    this.getNumBranches = function(dungeonConf) {

    };

    //-------------------
    // CONNECTING STUFF
    //-------------------

    /* Loops through feature list and connects them together. The connections
     * depend on the type parameter. */
    this.createBranchConnections = function(type, feats) {
        if (feats.length === 1) {return null;}
        const connections = [];
        for (let i = 0; i < feats.length; i++) {

        }
        return connections;

    };

    //----------------------------
    // NAME GEN FUNCTIONS
    // For debugging, names are stupid for now
    //----------------------------

    this.nCreated = {};
    this.getName = function(type) {
        if (!this.nCreated.hasOwnProperty(type)) {
            this.nCreated[type] = 0;
        }
        this.nCreated[type] += 1;
        return `${type} ${this.nCreated[type]}`;
    };

};

module.exports = Creator;
<|endoftext|>


<commit_before>export { AddGatherReshape };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
//import * as BoundsArraySet from "../BoundsArraySet.js";
import { FiltersArray_One } from "./Embedding_FiltersArray_One.js";

//!!! ...unfinished... (2022/07/26)
// Embedding assert if input bounds per channel larger than vocabulary count per table.

//!!! ...unfinished... (2022/07/25)
// Perhaps, provide a parameter control whether different input channel uses the same
// or different look-up (i.e. vocabulary) table.

/**
 *
 *
 * @member {function} destroy_or_keep_input
 *   This is a function pointer to one of destroy_input(), keep_input(). If ( this.bKeepInputTensor == false ),
 * it pointer to destroy_input(). If ( this.bKeepInputTensor == true ), it pointer to keep_input().
 *
 * @member {function} apply_and_destroy_or_keep
 *   Process the input and produce output by looking up the weights of this embedding layer. This is a function pointer
 * to one of keep_input_return_copy(), return_input_directly(), apply_and_destroy_or_keep_SplitGatherConcat().
 * It inputs a tensor3d data (e.g. height-width-color for color image, or 1-width-1 for text) with this.inChannels
 * (e.g. 4 for r-g-b-a, or 1 for text) channels. The inputTensor3d.dtype must be int32 (i.e. can not be float32)
 * so that they can be used as tf.gather()'s indices. If ( this.bKeepInputTensor == false ), the inputTensor3d
 * will be disposed. If ( this.bKeepInputTensor == true ), the inputTensor3d will be kept.
 *
 * @see Embedding.FiltersArray_One
 *
 */
class AddGatherReshape extends FiltersArray_One {

  /**
   * Used as default Embedding.AddGatherReshape provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Embedding.AddGatherReshape.Pool", AddGatherReshape, AddGatherReshape.setAsConstructor );

  /**
   *
   */
  constructor(
    input_channelCount,
    channelMultiplier,
    vocabularyCountPerInputChannel = 256, bEmbedVocabularyId = true,
    bKeepInputTensor
  ) {
    super(
      input_channelCount,
      channelMultiplier,
      vocabularyCountPerInputChannel, bEmbedVocabularyId
    );
    AddGatherReshape.setAsConstructor_self.call( this, bKeepInputTensor );
  }

  /** @override */
  static setAsConstructor(
    input_channelCount,
    channelMultiplier,
    vocabularyCountPerInputChannel = 256, bEmbedVocabularyId = true,
    bKeepInputTensor
  ) {
    super.setAsConstructor(
      input_channelCount,
      channelMultiplier,
      vocabularyCountPerInputChannel, bEmbedVocabularyId
    );
    AddGatherReshape.setAsConstructor_self.call( this, bKeepInputTensor );
  }

  /** @override */
  static setAsConstructor_self() {
    this.bKeepInputTensor = bKeepInputTensor;
    return this;
  }

  /** @override */
  disposeResources() {
    this.bKeepInputTensor = undefined;

!!! ...unfinished... (2022/07/17)

    super.disposeResources();
  }

  /**
   * Generator for initializing this object.
   *
   * @param {boolean} bKeepInputTensor
   *   If true, apply_and_destroy_or_keep() will not dispose inputTensor (i.e. keep). For example, for the branch of step 0 of ShuffleNetV2.
   * For another example, the input image should be shared across many neural networks.
   *
   * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray0
   *   The element value bounds (per channel) of input0. Usually, it is The .output0 of the previous Stage value bounds
   * set. It will be kept (not cloned) directly. So caller should not modify them.
   *
   * @return {boolean}
   *   Return true, if successfully. Return false, if failed.
   *
   */
  * init( inputWeightArray, weightElementOffsetBegin,
    input_channelCount,
    channelMultiplier,
    vocabularyCountPerInputChannel = 256, bEmbedVocabularyId = true,
    bKeepInputTensor,
    inputScaleBoundsArray0
  ) {

  }

}
<commit_msg>AddGatherReshape<commit_after>export { AddGatherReshape };

import * as Pool from "../../util/Pool.js";
import * as Recyclable from "../../util/Recyclable.js";
import { FiltersArray_One } from "./Embedding_FiltersArray_One.js";

/**
 *
 *
 * @member {boolean} bKeepInputTensor
 *   If true, .apply() will not dispose inputTensor (i.e. keep). For another example, the input image
 * needs be shared across many neural networks.
 *
 * @member {function} destroy_or_keep_input
 *   This is a function pointer to one of destroy_input(), keep_input(). If ( this.bKeepInputTensor == false ),
 * it pointer to destroy_input(). If ( this.bKeepInputTensor == true ), it pointer to keep_input().
 *
 * @member {function} apply_and_destroy_or_keep
 *   Process the input and produce output by looking up the weights of this embedding layer. This is a function pointer
 * to one of keep_input_return_copy(), return_input_directly(), apply_and_destroy_or_keep_SplitGatherConcat().
 * It inputs a tensor3d data (e.g. height-width-color for color image, or 1-width-1 for text) with this.inChannels
 * (e.g. 4 for r-g-b-a, or 1 for text) channels. The inputTensor3d.dtype must be int32 (i.e. can not be float32)
 * so that they can be used as tf.gather()'s indices. If ( this.bKeepInputTensor == false ), the inputTensor3d
 * will be disposed. If ( this.bKeepInputTensor == true ), the inputTensor3d will be kept.
 *
 * @see Embedding.FiltersArray_One
 *
 */
class AddGatherReshape extends FiltersArray_One {

  /**
   * Used as default Embedding.AddGatherReshape provider for conforming to Recyclable interface.
   */
  static Pool = new Pool.Root( "Embedding.AddGatherReshape.Pool", AddGatherReshape, AddGatherReshape.setAsConstructor );

  /**
   *
   */
  constructor(
    input_height, input_width, input_channelCount,
    channelMultiplier, vocabularyCountPerInputChannel = 256, bEmbedVocabularyId = true,
    bKeepInputTensor
  ) {
    super(
      input_height, input_width, input_channelCount,
      channelMultiplier, vocabularyCountPerInputChannel, bEmbedVocabularyId
    );
    AddGatherReshape.setAsConstructor_self.call( this, bKeepInputTensor );
  }

  /** @override */
  static setAsConstructor(
    input_height, input_width, input_channelCount,
    channelMultiplier, vocabularyCountPerInputChannel = 256, bEmbedVocabularyId = true,
    bKeepInputTensor
  ) {
    super.setAsConstructor(
      input_height, input_width, input_channelCount,
      channelMultiplier, vocabularyCountPerInputChannel, bEmbedVocabularyId
    );
    AddGatherReshape.setAsConstructor_self.call( this, bKeepInputTensor );
  }

  /** @override */
  static setAsConstructor_self() {
    this.bKeepInputTensor = bKeepInputTensor;
    return this;
  }

  /** @override */
  disposeResources() {
    this.bKeepInputTensor = undefined;

!!! ...unfinished... (2022/07/27) Release tensors.

    super.disposeResources();
  }

  /**
   * Initialize this object.
   *
   * @param {ActivationEscaping.ScaleBoundsArray} inputScaleBoundsArray0
   *   The element value bounds (per channel) of input0. Usually, it is The .output0 of the previous Stage value bounds
   * set. It will be kept (not cloned) directly. So caller should not modify them.
   *
   * @return {boolean}
   *   Return true, if successfully. Return false, if failed.
   */
   init( inputWeightArray, weightElementOffsetBegin, inputScaleBoundsArray ) {

    // 1. Extract weights.
    if ( !super.init( inputWeightArray, weightElementOffsetBegin, inputScaleBoundsArray ) ) {
      return false;  // e.g. input array does not have enough data.
    }

!!! ...unfinished... (2022/07/27) Create tensors.

  }

  /**
   * Process input, destroy or keep input, return result.
   *
   * @param {tf.tensor3d} inputTensor
   *   The source input image ( height x width x channel ) which will be processed. This inputTensor may or may not be disposed
   * according to .bKeepInputTensor.
   *
   * @return {tf.tensor3d}
   *   Return a new tensor. All other intermediate tensors were disposed.
   */
  apply( inputTensor ) {

//!!! ...unfinished... (2022/07/27)

  }

}
<|endoftext|>


<commit_before>define(["dojo/_base/kernel", "dojo/_base/declare", "dojo/on", "dojo/query", "dojo/_base/html", 'xstyle/css!../resources/resize.css'], function(dojo, declare, listen){

return declare([], {
	resizeNode: null,
	minWidth: 40,	//minimum column width in px
	detectWidth: 8, //distance from cell edge that the resize mouse cursor changes
	gridWidth: null, //place holder for the grid width property
	_resizedColumns: false, //flag that indicates if resizer has converted column widths to px
	resizeColumnWidth: function(colId, width){
	// Summary:
	//      calls grid's styleColumn function to add a style for the column
	// colId: String
	//      column id
	// width: Integer
	//      new width of the column
		var x = this.styleColumn(colId, "width: " + width + 'px;');
		this.resize();
	},
	postCreate: function(){
		this.inherited(arguments);

		var grid = this,
			body = document.body;
		grid.gridWidth = grid.headerNode.clientWidth - 1; //for some reason, total column width needs to be 1 less than this

		for(id in this.columns){
				var col = this.columns[id];
				var colNode = dojo.query(".column-"+id)[0];//grabs header node
				dojo.create('div',
					{className: 'resizeDgridResizeHandleNode'},
					colNode,
					'last');
		}

		listen(dojo.query(".resizeDgridResizeHandleNode"), "mouseover", function(e){
			console.log("in node");
		});

		listen(dojo.query(".resizeDgridResizeHandleNode"), "mousedown", function(e){
			if(!grid._readyToResize){return;}
				grid._resizeMouseDown(e);
		});

	/*	listen(grid.headerNode, "mousemove", function(e){
			//listens for the mouse to move over the header node
			if(grid._resizing || !grid._getResizeCell(e)){return;}
			grid._resizeMouseMove(e);
		});
		listen(grid, '.' + this.getCSSClass("header") + ":mouseout", function(e){ // should this be the mouse.leave event?
			if(grid._resizing){return;}
			grid._readyToResize = false;

			dojo.removeClass(grid.domNode, 'resizeDgridColumnResizing');
		});
		listen(grid, '.' + this.getCSSClass("header") + ":mousedown", function(e){
			// if ready to resize, allow resize
			if(!grid._readyToResize){return;}
				grid._resizeMouseDown(e);
		});
		listen(body, "mousemove", function(e){
			// while resizing, update the position of the resizer bar
			if(!grid._resizing){return;}
			grid._updateResizerPosition(e);
		});
*/
	},//end postCreate

	_resizeMouseMove: function(e){
	// Summary:
	//      called when mouse moves over the header node
	// e: Object
	//      mousemove event object

		if(this._isInResizeRange(e)){
			this._readyToResize = true;
			dojo.addClass(this.domNode, 'resizeDgridColumnResizing');
		}else{
			this._readyToResize = false;
			dojo.removeClass(this.domNode, 'resizeDgridColumnResizing');
		}
	},

	_resizeMouseDown: function(e){
	// Summary:
	//      called when mouse button is pressed on the header
	// e: Object
	//      mousedown event object

		// preventDefault actually seems to be enough to prevent browser selection
		// in all but IE < 9.  setSelectable works for those.
		e.preventDefault();
		dojo.setSelectable(this.domNode, false);

		var grid = this;
		grid._resizing = true;
		grid._startX = grid._getResizeMouseLocation(e); //position of the target
		grid._gridX = dojo.position(grid.bodyNode).x;//position of the grid in the body *not sure why we need this?*

		// show resizer inlined
		if(!grid._resizer){
			grid._resizer = dojo.create('div', {
				className: 'resizeDgridColumnResizer'},
				grid.domNode, 'last');
			var mouseUpListen = listen(document.body, 'mouseup', function(e){
				if(!grid._resizing){return;}
				grid._resizeMouseUp(e);
			});
		}
		grid._resizer.style.display = 'block';
		grid._updateResizerPosition(e);
	},
	_resizeMouseUp: function(e){
	// Summary:
	//      called when mouse button is released
	// e: Object
	//      mouseup event object

		this._resizing = false;
		this._readyToResize = false;

		//This is used to set all the column widths to a static size
		if(!this._resizedColumns){
			for(id in this.columns){
				var col = this.columns[id];
				var width = dojo.query(".column-"+id)[0].offsetWidth;
				this.resizeColumnWidth(id, width);
			}
			this._resizedColumns = true;
		}
		dojo.removeClass(this.domNode, 'resizeDgridColumnResizing');//not working in opera
		dojo.setSelectable(this.domNode, true);

		var cell = this._targetCell,
			delta = this._getResizeMouseLocation(e) - this._startX, //final change in position of resizer
			newWidth = cell.offsetWidth + delta, //the new width after resize
			obj = this._getResizedColumnWidths(),//get current total column widths before resize
			totalWidth = obj.totalWidth,
			lastCol = obj.lastColId,
			lastColWidth = dojo.query(".column-"+lastCol)[0].offsetWidth;

		if(cell.columnId != lastCol){
			if(totalWidth + delta < this.gridWidth) {
				//need to set last column's width to auto
				this.styleColumn(lastCol, "width: auto;");
			}else if(lastColWidth-delta <= this.minWidth) {
				//change last col width back to px, unless it is the last column itself being resized...
				this.resizeColumnWidth(lastCol, this.minWidth);
			}
		}
		if(newWidth < this.minWidth){
			//enforce minimum widths
			newWidth = this.minWidth;
		}

		this.resizeColumnWidth(cell.columnId, newWidth);
		this._hideResizer();
	},
	_updateResizerPosition: function(e){
	// Summary:
	//      updates position of resizer bar as mouse moves
	// e: Object
	//      mousemove event object

		var mousePos = this._getResizeMouseLocation(e),
			delta = mousePos - this._startX, //change from where user clicked to where they drag
			cell = this._targetCell,
			left = mousePos - this._gridX;

		if(cell.offsetWidth + delta < this.minWidth){
			left = this._startX - this._gridX - (cell.offsetWidth - this.minWidth);
		}
		this._resizer.style.left = left  + 'px';
	},
	_hideResizer: function(){
	// Summary:
	//      sets resizer bar display to none

		this._resizer.style.display = 'none';
	},

	_isInResizeRange: function(e){
	// Summary:
	//      checks if mouse is within 5px of the edge of the header cell
	// e: Object
	//      mousemove event object

		var cell = this._getResizeCell(e);
		this._targetCell = cell;
		var mouseX = this._getResizeMouseLocation(e);
		var cellPos = dojo.position(cell, true).x;
		var zoneStart = cellPos + cell.offsetWidth - this.detectWidth;
		var zoneEnd = cellPos + cell.offsetWidth;
		if(mouseX > zoneStart && mouseX <= zoneEnd){
			return true;
		}
		return false;
	},

	_getResizeMouseLocation: function(e){
		var posX = 0;
		if(e.pageX){
			posX = e.pageX;
		}
		else if(e.clientX){
			posX = e.clientX + document.body.scrollLeft
				+ document.documentElement.scrollLeft;
		}
		return posX;
	},

	_getResizeCell: function(e){
	// Summary:
	//      get the target of the mouse move event
	// e: Object
	//      mousemove event object
		var node;
		if(e.target){
			node = e.target;
		}else if(e.srcElement){
			node = e.srcElement;
		}
		if(node.nodeType == 3 || !node.columnId){ // defeat Safari bug first and IE oddity 2nd
			node = node.parentNode;
		}
		return node;
	},

	_getResizedColumnWidths: function (){
		var totalWidth = 0;
		var lastColId = null;
		for(id in this.columns){
			var col = this.columns[id];
			var width = dojo.query(".column-"+id)[0].offsetWidth;
			totalWidth += width;
			lastColId = id;
		}
		return {totalWidth: totalWidth, lastColId: lastColId};
	}
});
});
<commit_msg>updated resize column to use a div to know when to resize instead of a mouse location calculation.<commit_after>define(["dojo/_base/kernel", "dojo/_base/declare", "dojo/on", "dojo/query", "dojo/_base/html", 'xstyle/css!../resources/resize.css'], function(dojo, declare, listen){

return declare([], {
	resizeNode: null,
	minWidth: 40,	//minimum column width in px
	gridWidth: null, //place holder for the grid width property
	_resizedColumns: false, //flag that indicates if resizer has converted column widths to px
	resizeColumnWidth: function(colId, width){
	// Summary:
	//      calls grid's styleColumn function to add a style for the column
	// colId: String
	//      column id
	// width: Integer
	//      new width of the column
		var x = this.styleColumn(colId, "width: " + width + 'px;');
		this.resize();
	},
	postCreate: function(){
		this.inherited(arguments);

		var grid = this;
		grid.gridWidth = grid.headerNode.clientWidth - 1; //for some reason, total column width needs to be 1 less than this

		for(id in this.columns){
				var col = this.columns[id];
				var colNode = dojo.query(".column-"+id)[0];//grabs header node
				dojo.create('div',
					{className: 'resizeDgridResizeHandleNode'},
					colNode,
					'last');
		}

		listen(dojo.query(".resizeDgridResizeHandleNode"), "mousedown", function(e){
				grid._resizeMouseDown(e);
		});
		grid.mouseMoveListen = listen.pausable(document.body, "mousemove", function(e){
			// while resizing, update the position of the resizer bar
			if(!grid._resizing){return;}
			grid._updateResizerPosition(e);
		});
		grid.mouseUpListen = listen.pausable(document.body, 'mouseup', function(e){
				if(!grid._resizing){return;}
				grid._resizeMouseUp(e);
				grid.mouseMoveListen.pause();
				grid.mouseUpListen.pause();
			});
	},//end postCreate

	_resizeMouseDown: function(e){
	// Summary:
	//      called when mouse button is pressed on the header
	// e: Object
	//      mousedown event object

		// preventDefault actually seems to be enough to prevent browser selection
		// in all but IE < 9.  setSelectable works for those.
		e.preventDefault();
		dojo.setSelectable(this.domNode, false);
		var grid = this;
		grid._resizing = true;
		grid._startX = grid._getResizeMouseLocation(e); //position of the target
		grid._gridX = dojo.position(grid.bodyNode).x;//position of the grid in the body *not sure why we need this?*
		grid._targetCell = grid._getResizeCell(e);

		// show resizer inlined
		if(!grid._resizer){
			grid._resizer = dojo.create('div', {
				className: 'resizeDgridColumnResizer'},
				grid.domNode, 'last');
		}else{
			grid.mouseMoveListen.resume();
			grid.mouseUpListen.resume();
		}

		grid._resizer.style.display = 'block';
		grid._updateResizerPosition(e);
	},
	_resizeMouseUp: function(e){
	// Summary:
	//      called when mouse button is released
	// e: Object
	//      mouseup event object

		this._resizing = false;
		this._readyToResize = false;

		//This is used to set all the column widths to a static size
		if(!this._resizedColumns){
			for(id in this.columns){
				var col = this.columns[id];
				var width = dojo.query(".column-"+id)[0].offsetWidth;
				this.resizeColumnWidth(id, width);
			}
			this._resizedColumns = true;
		}
		dojo.removeClass(this.domNode, 'resizeDgridColumnResizing');//not working in opera
		dojo.setSelectable(this.domNode, true);

		var cell = this._targetCell,
			delta = this._getResizeMouseLocation(e) - this._startX, //final change in position of resizer
			newWidth = cell.offsetWidth + delta, //the new width after resize
			obj = this._getResizedColumnWidths(),//get current total column widths before resize
			totalWidth = obj.totalWidth,
			lastCol = obj.lastColId,
			lastColWidth = dojo.query(".column-"+lastCol)[0].offsetWidth;

		if(cell.columnId != lastCol){
			if(totalWidth + delta < this.gridWidth) {
				//need to set last column's width to auto
				this.styleColumn(lastCol, "width: auto;");
			}else if(lastColWidth-delta <= this.minWidth) {
				//change last col width back to px, unless it is the last column itself being resized...
				this.resizeColumnWidth(lastCol, this.minWidth);
			}
		}
		if(newWidth < this.minWidth){
			//enforce minimum widths
			newWidth = this.minWidth;
		}

		this.resizeColumnWidth(cell.columnId, newWidth);
		this._hideResizer();
	},
	_updateResizerPosition: function(e){
	// Summary:
	//      updates position of resizer bar as mouse moves
	// e: Object
	//      mousemove event object

		var mousePos = this._getResizeMouseLocation(e),
			delta = mousePos - this._startX, //change from where user clicked to where they drag
			cell = this._targetCell,
			left = mousePos - this._gridX;
		if(cell.offsetWidth + delta < this.minWidth){
			left = this._startX - this._gridX - (cell.offsetWidth - this.minWidth);
		}
		this._resizer.style.left = left  + 'px';
	},

	_hideResizer: function(){
	// Summary:
	//      sets resizer bar display to none
		this._resizer.style.display = 'none';
	},
	_getResizeMouseLocation: function(e){
	//Summary:
	//      returns position of mouse relative to the left edge
	// e: event object
	//      mouse move event object
		var posX = 0;
		if(e.pageX){
			posX = e.pageX;
		}
		else if(e.clientX){
			posX = e.clientX + document.body.scrollLeft
				+ document.documentElement.scrollLeft;
		}
		return posX;
	},
	_getResizeCell: function(e){
	// Summary:
	//      get the target of the mouse move event
	// e: Object
	//      mousemove event object
		var node;
		if(e.target){
			node = e.target;
		}else if(e.srcElement){
			node = e.srcElement;
		}
		if(node.nodeType == 3 || !node.columnId){ // defeat Safari bug first and IE oddity 2nd
			node = node.parentNode;
		}
		return node;
	},
	_getResizedColumnWidths: function (){
	//Summary:
	//      returns object containing new column width and column id
		var totalWidth = 0;
		var lastColId = null;
		for(id in this.columns){
			var col = this.columns[id];
			var width = dojo.query(".column-"+id)[0].offsetWidth;
			totalWidth += width;
			lastColId = id;
		}
		return {totalWidth: totalWidth, lastColId: lastColId};
	}
});
});
<|endoftext|>


<commit_before>var assert = require("assert");
var {join} = require("fs");
var SEPARATOR = require('ringo/utils/files').separator;

// the old implementation
var join_011 = function() {
    var args = Array.prototype.filter.call(arguments, function(p) p != "");
    return args.join(SEPARATOR);
};

// these tests should work as in 0.11
var positiveTests = [
    ["foo", "bar", "baz.js"],
    ["foo", "bar", ".baz.js"],
    ["foo", "bar", ".baz"],
    ["", ".baz"],
    ["", "", ".baz"],
    ["foo", "bar", "baz"],
    ["foo", "..", "bar"],
    ["foo", ".", "bar"],
    ["." + SEPARATOR + "foo"]
];

var negativeTests = [
    ["foo" + SEPARATOR, ""],
    ["foo" + SEPARATOR, "bar" + SEPARATOR + SEPARATOR, "baz"],
    ["." + SEPARATOR, "..", SEPARATOR + "foo"],
    ["." + SEPARATOR, "..", "..", SEPARATOR + "foo"],
    [".", "..", "..", SEPARATOR + "foo"],
    [".", null]
];

positiveTests.forEach(function(item, index, arr) {
    exports["test compat fs.join('" + item.join("', '") + "')"] = function() {
        assert.equal(join.apply(this, item), join_011.apply(this, item));
    }
});

negativeTests.forEach(function(item, index, arr) {
    exports["test compat fs.join('" + item.join("', '") + "')"] = function() {
        assert.notEqual(join.apply(this, item), join_011.apply(this, item));
    }
});

if (require.main == module.id) {
    require('system').exit(require("test").run(module.id));
}<commit_msg>Made comments for tests clearer<commit_after>var assert = require("assert");
var {join} = require("fs");
var SEPARATOR = require('ringo/utils/files').separator;

// the old naive implementation from RingoJS 0.11
var join_011 = function() {
    var args = Array.prototype.filter.call(arguments, function(p) p != "");
    return args.join(SEPARATOR);
};

// these tests should work as in RingoJS 0.11
var positiveTests = [
    ["foo", "bar", "baz.js"],
    ["foo", "bar", ".baz.js"],
    ["foo", "bar", ".baz"],
    ["", ".baz"],
    ["", "", ".baz"],
    ["foo", "bar", "baz"],
    ["foo", "..", "bar"],
    ["foo", ".", "bar"],
    ["." + SEPARATOR + "foo"]
];

// Paths.get() changed the behavior of these tests >= RingoJS 0.12
var negativeTests = [
    ["foo" + SEPARATOR, ""],
    ["foo" + SEPARATOR, "bar" + SEPARATOR + SEPARATOR, "baz"],
    ["." + SEPARATOR, "..", SEPARATOR + "foo"],
    ["." + SEPARATOR, "..", "..", SEPARATOR + "foo"],
    [".", "..", "..", SEPARATOR + "foo"],
    [".", null]
];

positiveTests.forEach(function(item, index, arr) {
    exports["test compat fs.join('" + item.join("', '") + "')"] = function() {
        assert.equal(join.apply(this, item), join_011.apply(this, item));
    }
});

negativeTests.forEach(function(item, index, arr) {
    exports["test compat fs.join('" + item.join("', '") + "')"] = function() {
        assert.notEqual(join.apply(this, item), join_011.apply(this, item));
    }
});

if (require.main == module.id) {
    require('system').exit(require("test").run(module.id));
}<|endoftext|>


<commit_before>
(function () {
  var Consolator = (function () {

    var C = function (opts) {
      opts = opts || {};
    };

    // application & consumption
    var apply = function (data) {
      if (!data) return;
      data = split(stringify(data));
      var dataArray = [''];
      var i = data.length;
      while (i--) if (data[i]) {
        data[i] = objectify(data[i]);
        var keys = Object.keys(data[i]);
        var k = keys.length;
        dataArray = env === 'browser' ? support.styles ? browser(dataArray, data[i], keys) : bypass(dataArray, data[i]) : server(dataArray, data[i], keys);
      }
      return dataArray;
    };
    var digest = function (data, attribute, value) {
      if (!data) return;
      data = split(stringify(data));
      var dataStr = '';
      var i = data.length;
      while (i--) if (data[i]) {
        data[i] = objectify(data[i]);
        if (!data[i][attribute]) data[i][attribute] = value;
        dataStr = dataStr + '{{{' + JSON.stringify(data[i]) + '}}}';
      }
      return dataStr;
    };
    var post = function (method, args) {
      console[method].apply(console, apply(args));
    };

    // context
    var bypass = function (dataArray, data) {
      dataArray[0] = dataArray[0] + data.msg;
      return dataArray;
    };
    var server = function (dataArray, data, keys) {
      var csi = '\x1B[';
      var styles = [];
      var k = keys.length;
      while (k--) if (keys[k] !== 'msg') styles.push(( keys[k] !== 'background-color' ? ansiKeys[data[keys[k]]] : ansiKeys[data[keys[k]]] + 10 ));
      dataArray[0] = dataArray[0] + csi + styles.join(';') + 'm' + data.msg + csi + '0m';
      return dataArray;
    };
    var browser = function (dataArray, data, keys) {
      dataArray[0] = dataArray[0] + '%c' + data.msg;
      var styles = [];
      var k = keys.length;
      while (k--) if (keys[k] !== 'msg') styles.push(keys[k] + ': ' + data[keys[k]]);
      dataArray.push(styles.join('; '));
      return dataArray;
    };

    // helpers
    var objectify = function (data) {
      if (data.indexOf('{{{{') === 0 && data.indexOf('}}}}') === data.length - 4) data = JSON.parse(data.substr(3, data.length - 6));
      else data = { msg: data };
      return data;
    };
    var split = function (data) {
      return data.match(/\{\{\{\{.*?\}\}\}\}|.*?(?=\{\{\{\{)|.*/g).reverse();
    };
    var stringify = function (data) {
      var type = typeof data;
      if (type === 'object') return JSON.stringify(data);
      if (type === 'number') return data.toString();
      if (type === 'string') return data;
      return '';
    };

    // extentions of the original console object
    C.prototype.log = function (data) {
      return post('log', data);
    };
    C.prototype.error = function (data) {
      return post('error', data);
    };
    C.prototype.info = function (data) {
      return post('info', data);
    };
    C.prototype.warn = function (data) {
      return post('warn', data);
    };

    // text colors
    C.prototype.black = function (data) {
      return digest(data, 'color', 'black');
    };
    C.prototype.red = function (data) {
      return digest(data, 'color', 'red');
    };
    C.prototype.green = function (data) {
      return digest(data, 'color', 'green');
    };
    C.prototype.yellow = function (data) {
      return digest(data, 'color', 'yellow');
    };
    C.prototype.blue = function (data) {
      return digest(data, 'color', 'blue');
    };
    C.prototype.magenta = function (data) {
      return digest(data, 'color', 'magenta');
    };
    C.prototype.cyan = function (data) {
      return digest(data, 'color', 'cyan');
    };
    C.prototype.gray = function (data) {
      return digest(data, 'color', 'gray');
    };

    C.prototype.darkGray = function (data) {
      return digest(data, 'color', 'darkGray');
    };
    C.prototype.brightRed = C.prototype.lightRed = function (data) {
      return digest(data, 'color', 'lightRed');
    };
    C.prototype.brightGreen = C.prototype.lightGreen = function (data) {
      return digest(data, 'color', 'lightGreen');
    };
    C.prototype.brightYellow = C.prototype.lightYellow = function (data) {
      return digest(data, 'color', 'lightYellow');
    };
    C.prototype.brightBlue = C.prototype.lightBlue = function (data) {
      return digest(data, 'color', 'lightBlue');
    };
    C.prototype.brightMagenta = C.prototype.lightMagenta = function (data) {
      return digest(data, 'color', 'lightMagenta');
    };
    C.prototype.brightCyan = C.prototype.lightCyan = function (data) {
      return digest(data, 'color', 'lightCyan');
    };
    C.prototype.white = function (data) {
      return digest(data, 'color', 'white');
    };

    // background colors
    C.prototype.blackBg = function (data) {
      return digest(data, 'background-color', 'black');
    };
    C.prototype.redBg = function (data) {
      return digest(data, 'background-color', 'red');
    };
    C.prototype.greenBg = function (data) {
      return digest(data, 'background-color', 'green');
    };
    C.prototype.yellowBg = function (data) {
      return digest(data, 'background-color', 'yellow');
    };
    C.prototype.blueBg = function (data) {
      return digest(data, 'background-color', 'blue');
    };
    C.prototype.magentaBg = function (data) {
      return digest(data, 'background-color', 'magenta');
    };
    C.prototype.cyanBg = function (data) {
      return digest(data, 'background-color', 'cyan');
    };
    C.prototype.grayBg = function (data) {
      return digest(data, 'background-color', 'gray');
    };

    C.prototype.darkGrayBg = function (data) {
      return digest(data, 'background-color', 'darkGray');
    };
    C.prototype.brightRedBg = C.prototype.lightRedBg = function (data) {
      return digest(data, 'background-color', 'lightRed');
    };
    C.prototype.brightGreenBg = C.prototype.lightGreenBg = function (data) {
      return digest(data, 'background-color', 'lightGreen');
    };
    C.prototype.brightYellowBg = C.prototype.lightYellowBg = function (data) {
      return digest(data, 'background-color', 'lightYellow');
    };
    C.prototype.brightBlueBg = C.prototype.lightBlueBg = function (data) {
      return digest(data, 'background-color', 'lightBlue');
    };
    C.prototype.brightMagentaBg = C.prototype.lightMagentaBg = function (data) {
      return digest(data, 'background-color', 'lightMagenta');
    };
    C.prototype.brightCyanBg = C.prototype.lightCyanBg = function (data) {
      return digest(data, 'background-color', 'lightCyan');
    };
    C.prototype.whiteBg = function (data) {
      return digest(data, 'background-color', 'white');
    };

    // styles
    C.prototype.bold = function (data) {
      return digest(data, 'font-weight', 'bold');
    };
    C.prototype.lighter = C.prototype.faint = function (data) {
      return digest(data, 'font-weight', 'lighter');
    };
    C.prototype.italic = function (data) {
      return digest(data, 'font-style', 'italic');
    };
    C.prototype.underline = function (data) {
      return digest(data, 'text-decoration', 'underline');
    };
    C.prototype.blink = function (data) {
      return digest(data, 'blink', 'blink');
    };
    C.prototype.blinkFast = function (data) {
      return digest(data, 'blink', 'blinkFast');
    };
    C.prototype.negative = C.prototype.inverse = function (data) {
      return digest(data, 'negative', 'negative');
    };
    C.prototype.hidden = C.prototype.conceal = function (data) {
      return digest(data, 'visibility', 'hidden');
    };
    C.prototype.lineThrough = C.prototype.crossedOut = function (data) {
      return digest(data, 'text-decoration', 'line-through');
    };

    // timestamp

    // objects and arrays
    C.prototype.array = function () {};
    C.prototype.object = function () {};

    // manual
    C.prototype.ansi = function () {};
    C.prototype.css = function () {};

    // ansi keys
    var ansiKeys = {
      bold: 1,
      lighter: 2,
      italic: 3,
      underline: 4,
      blink: 5,
      blinkFast: 6,
      negative: 7,
      hidden: 8,
      'line-through': 9,
      black: 30,
      red: 31,
      green: 32,
      yellow: 33,
      blue: 34,
      magenta: 35,
      cyan: 36,
      gray: 37,
      darkGray: 90,
      lightRed: 91,
      lightGreen: 92,
      lightYellow: 93,
      lightBlue: 94,
      lightMagenta: 95,
      lightCyan: 96,
      white: 97
    };

    // environment/support
    var env = typeof window !== 'undefined' ? 'browser' : 'server';
    var support = {};
    support.apply = false;
    support.console = false;
    support.styles = ( typeof window !== 'undefined' && ( window.chrome || console.firebug || console.log.toString().indexOf('apply') !== -1 ));

    return C;
  })();

  if (typeof module !== 'undefined' && module.exports) module.exports = Consolator;
  else if (typeof define === 'function' && define.amd) define([], function() { return Consolator; });
  else window.Consolator = Consolator;
})();
<commit_msg>update variable name<commit_after>
(function () {
  var Consolator = (function () {

    var C = function (opts) {
      opts = opts || {};
    };

    // application & consumption
    var apply = function (data) {
      if (!data) return;
      data = split(stringify(data));
      var dataArray = [''];
      var i = data.length;
      while (i--) if (data[i]) {
        data[i] = objectify(data[i]);
        var keys = Object.keys(data[i]);
        var k = keys.length;
        dataArray = env === 'browser' ? support.styles ? browser(dataArray, data[i], keys) : bypass(dataArray, data[i]) : server(dataArray, data[i], keys);
      }
      return dataArray;
    };
    var digest = function (data, attribute, value) {
      if (!data) return;
      data = split(stringify(data));
      var dataString = '';
      var i = data.length;
      while (i--) if (data[i]) {
        data[i] = objectify(data[i]);
        if (!data[i][attribute]) data[i][attribute] = value;
        dataString = dataString + '{{{' + JSON.stringify(data[i]) + '}}}';
      }
      return dataString;
    };
    var post = function (method, args) {
      console[method].apply(console, apply(args));
    };

    // context
    var bypass = function (dataArray, data) {
      dataArray[0] = dataArray[0] + data.msg;
      return dataArray;
    };
    var server = function (dataArray, data, keys) {
      var csi = '\x1B[';
      var styles = [];
      var k = keys.length;
      while (k--) if (keys[k] !== 'msg') styles.push(( keys[k] !== 'background-color' ? ansiKeys[data[keys[k]]] : ansiKeys[data[keys[k]]] + 10 ));
      dataArray[0] = dataArray[0] + csi + styles.join(';') + 'm' + data.msg + csi + '0m';
      return dataArray;
    };
    var browser = function (dataArray, data, keys) {
      dataArray[0] = dataArray[0] + '%c' + data.msg;
      var styles = [];
      var k = keys.length;
      while (k--) if (keys[k] !== 'msg') styles.push(keys[k] + ': ' + data[keys[k]]);
      dataArray.push(styles.join('; '));
      return dataArray;
    };

    // helpers
    var objectify = function (data) {
      if (data.indexOf('{{{{') === 0 && data.indexOf('}}}}') === data.length - 4) data = JSON.parse(data.substr(3, data.length - 6));
      else data = { msg: data };
      return data;
    };
    var split = function (data) {
      return data.match(/\{\{\{\{.*?\}\}\}\}|.*?(?=\{\{\{\{)|.*/g).reverse();
    };
    var stringify = function (data) {
      var type = typeof data;
      if (type === 'object') return JSON.stringify(data);
      if (type === 'number') return data.toString();
      if (type === 'string') return data;
      return '';
    };

    // extentions of the original console object
    C.prototype.log = function (data) {
      return post('log', data);
    };
    C.prototype.error = function (data) {
      return post('error', data);
    };
    C.prototype.info = function (data) {
      return post('info', data);
    };
    C.prototype.warn = function (data) {
      return post('warn', data);
    };

    // text colors
    C.prototype.black = function (data) {
      return digest(data, 'color', 'black');
    };
    C.prototype.red = function (data) {
      return digest(data, 'color', 'red');
    };
    C.prototype.green = function (data) {
      return digest(data, 'color', 'green');
    };
    C.prototype.yellow = function (data) {
      return digest(data, 'color', 'yellow');
    };
    C.prototype.blue = function (data) {
      return digest(data, 'color', 'blue');
    };
    C.prototype.magenta = function (data) {
      return digest(data, 'color', 'magenta');
    };
    C.prototype.cyan = function (data) {
      return digest(data, 'color', 'cyan');
    };
    C.prototype.gray = function (data) {
      return digest(data, 'color', 'gray');
    };

    C.prototype.darkGray = function (data) {
      return digest(data, 'color', 'darkGray');
    };
    C.prototype.brightRed = C.prototype.lightRed = function (data) {
      return digest(data, 'color', 'lightRed');
    };
    C.prototype.brightGreen = C.prototype.lightGreen = function (data) {
      return digest(data, 'color', 'lightGreen');
    };
    C.prototype.brightYellow = C.prototype.lightYellow = function (data) {
      return digest(data, 'color', 'lightYellow');
    };
    C.prototype.brightBlue = C.prototype.lightBlue = function (data) {
      return digest(data, 'color', 'lightBlue');
    };
    C.prototype.brightMagenta = C.prototype.lightMagenta = function (data) {
      return digest(data, 'color', 'lightMagenta');
    };
    C.prototype.brightCyan = C.prototype.lightCyan = function (data) {
      return digest(data, 'color', 'lightCyan');
    };
    C.prototype.white = function (data) {
      return digest(data, 'color', 'white');
    };

    // background colors
    C.prototype.blackBg = function (data) {
      return digest(data, 'background-color', 'black');
    };
    C.prototype.redBg = function (data) {
      return digest(data, 'background-color', 'red');
    };
    C.prototype.greenBg = function (data) {
      return digest(data, 'background-color', 'green');
    };
    C.prototype.yellowBg = function (data) {
      return digest(data, 'background-color', 'yellow');
    };
    C.prototype.blueBg = function (data) {
      return digest(data, 'background-color', 'blue');
    };
    C.prototype.magentaBg = function (data) {
      return digest(data, 'background-color', 'magenta');
    };
    C.prototype.cyanBg = function (data) {
      return digest(data, 'background-color', 'cyan');
    };
    C.prototype.grayBg = function (data) {
      return digest(data, 'background-color', 'gray');
    };

    C.prototype.darkGrayBg = function (data) {
      return digest(data, 'background-color', 'darkGray');
    };
    C.prototype.brightRedBg = C.prototype.lightRedBg = function (data) {
      return digest(data, 'background-color', 'lightRed');
    };
    C.prototype.brightGreenBg = C.prototype.lightGreenBg = function (data) {
      return digest(data, 'background-color', 'lightGreen');
    };
    C.prototype.brightYellowBg = C.prototype.lightYellowBg = function (data) {
      return digest(data, 'background-color', 'lightYellow');
    };
    C.prototype.brightBlueBg = C.prototype.lightBlueBg = function (data) {
      return digest(data, 'background-color', 'lightBlue');
    };
    C.prototype.brightMagentaBg = C.prototype.lightMagentaBg = function (data) {
      return digest(data, 'background-color', 'lightMagenta');
    };
    C.prototype.brightCyanBg = C.prototype.lightCyanBg = function (data) {
      return digest(data, 'background-color', 'lightCyan');
    };
    C.prototype.whiteBg = function (data) {
      return digest(data, 'background-color', 'white');
    };

    // styles
    C.prototype.bold = function (data) {
      return digest(data, 'font-weight', 'bold');
    };
    C.prototype.lighter = C.prototype.faint = function (data) {
      return digest(data, 'font-weight', 'lighter');
    };
    C.prototype.italic = function (data) {
      return digest(data, 'font-style', 'italic');
    };
    C.prototype.underline = function (data) {
      return digest(data, 'text-decoration', 'underline');
    };
    C.prototype.blink = function (data) {
      return digest(data, 'blink', 'blink');
    };
    C.prototype.blinkFast = function (data) {
      return digest(data, 'blink', 'blinkFast');
    };
    C.prototype.negative = C.prototype.inverse = function (data) {
      return digest(data, 'negative', 'negative');
    };
    C.prototype.hidden = C.prototype.conceal = function (data) {
      return digest(data, 'visibility', 'hidden');
    };
    C.prototype.lineThrough = C.prototype.crossedOut = function (data) {
      return digest(data, 'text-decoration', 'line-through');
    };

    // timestamp

    // objects and arrays
    C.prototype.array = function () {};
    C.prototype.object = function () {};

    // manual
    C.prototype.ansi = function () {};
    C.prototype.css = function () {};

    // ansi keys
    var ansiKeys = {
      bold: 1,
      lighter: 2,
      italic: 3,
      underline: 4,
      blink: 5,
      blinkFast: 6,
      negative: 7,
      hidden: 8,
      'line-through': 9,
      black: 30,
      red: 31,
      green: 32,
      yellow: 33,
      blue: 34,
      magenta: 35,
      cyan: 36,
      gray: 37,
      darkGray: 90,
      lightRed: 91,
      lightGreen: 92,
      lightYellow: 93,
      lightBlue: 94,
      lightMagenta: 95,
      lightCyan: 96,
      white: 97
    };

    // environment/support
    var env = typeof window !== 'undefined' ? 'browser' : 'server';
    var support = {};
    support.apply = false;
    support.console = false;
    support.styles = ( typeof window !== 'undefined' && ( window.chrome || console.firebug || console.log.toString().indexOf('apply') !== -1 ));

    return C;
  })();

  if (typeof module !== 'undefined' && module.exports) module.exports = Consolator;
  else if (typeof define === 'function' && define.amd) define([], function() { return Consolator; });
  else window.Consolator = Consolator;
})();
<|endoftext|>


<commit_before>/**
 * Appjs window script
 * This is part of the executable.
 */

var app = module.exports = require('appjs');
var open = require('open');

app.serveFilesFrom(__dirname + '/content');
process.title = 'Remote Control - XBMC';

var Rectangle = function(x, y, width, height)
{
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
};

var windowSize = {
    WIN : new Rectangle(0, 0, 350, 600),
    LINUX: new Rectangle(0, 0, 350, 540),
    MAC: new Rectangle(0, 0, 350, 540),
    OTHERS: new Rectangle(0, 0, 350, 580)
};

console.log(windowSize.WIN.width);
console.log(windowSize.WIN.height);

var menubar = app.createMenu([
    {
        label:'&File',
            submenu:[
            {
                label:'E&xit',
                action: function()
                {
                    window.close();
                }
            }
        ]
    },
    {
        label:'&Options',
        submenu:[
            {
                label:'&Settings',
                action: function()
                {
                    window.location.href = "settings.html";
                }
            }
        ]
    },
    {
        label:'&Help',
        submenu:[
            {
                label:'&About',
                action: function()
                {
                    aboutWindow.show();
                }
            }
        ]
    }

]);

menubar.on('select',function(item)
{
    console.log("menu item "+item.label+" clicked");
});

var selectWindowSize = windowSize.OTHERS;
var platform = process.platform;

if(platform == "win32")
{
    selectWindowSize = windowSize.WIN;
}
else if(platform == "linux")
{
    selectWindowSize = windowSize.LINUX;
}
else if(platform == "darwin")
{
    selectWindowSize = windowSize.MAC;
}
else
{
    selectWindowSize = windowSize.OTHERS;
}

var window = app.createWindow({
    width           : selectWindowSize.width,
    height          : selectWindowSize.height,
    icons           : __dirname + '/content/icons',
    resizable       : true,
    topmost         : false,
    url             : 'http://appjs/remote.html',
    disableSecurity : true,
    autoResize      : false
});

window.on('create', function(){
    //console.log("Window Created");
    window.frame.show();
    window.frame.center();
    window.frame.setMenuBar(menubar);
    //window.frame.topmost = false;
});

window.on('ready', function(){
    console.log("Window Ready");
    window.process = process;
    window.module = module;

    /*function F12(e){ return e.keyIdentifier === 'F12' }
    function Command_Option_J(e){ return e.keyCode === 74 && e.metaKey && e.altKey }

    window.addEventListener('keydown', function(e){
        if (F12(e) || Command_Option_J(e)) {
          window.frame.openDevTools();

        }
    });*/

});

window.on('close', function(){
    aboutWindow.close();
    console.log("Window Closed");
});

var aboutWindow = new function()
{
    var aWindow;

    this.show =function()
    {
        if(aWindow)
        {
            if(aWindow.window.frame)
            {
                aWindow.close();
            }
        }

        aWindow = app.createWindow({
            width           : 350,
            height          : 250,
            icons           : __dirname + '/content/icons',
            resizable       : false,
            topmost         : false,
            url             : 'http://appjs/about.html'
        });

        aWindow.on('create', function(){
            //console.log("Window Created");
            aWindow.frame.show();
            aWindow.frame.center();
            //aWindow.frame.openDevTools();
        });

        aWindow.on('ready', function(){
            console.log("About Window Ready");
            aWindow.process = process;
            aWindow.module = module;

            aWindow.addEventListener("open-email", function()
            {
                open("mailto:karthikeyanvj@gmail.com");
            });

            aWindow.addEventListener("open-twitter", function()
            {
                open("https://twitter.com/karthikvj");
            });

        });
    };

    this.close = function()
    {
        if(aWindow)
        {
            if(aWindow.window.frame)
            {
                aWindow.close();
            }
        }
    };

    this.openDevTools = function()
    {
        if(aWindow)
        {
            aWindow.frame.openDevTools();
        }

    };
};

<commit_msg>updated window width and height for executable<commit_after>/**
 * Appjs window script
 * This is part of the executable.
 */

var app = module.exports = require('appjs');
var open = require('open');

app.serveFilesFrom(__dirname + '/content');
process.title = 'Remote Control - XBMC';

var Rectangle = function(x, y, width, height)
{
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
};

var windowSize = {
    WIN : new Rectangle(0, 0, 350, 580),
    LINUX: new Rectangle(0, 0, 350, 520),
    MAC: new Rectangle(0, 0, 350, 520),
    OTHERS: new Rectangle(0, 0, 350, 560)
};

console.log(windowSize.WIN.width);
console.log(windowSize.WIN.height);

var menubar = app.createMenu([
    {
        label:'&File',
            submenu:[
            {
                label:'E&xit',
                action: function()
                {
                    window.close();
                }
            }
        ]
    },
    {
        label:'&Options',
        submenu:[
            {
                label:'&Settings',
                action: function()
                {
                    window.location.href = "settings.html";
                }
            }
        ]
    },
    {
        label:'&Help',
        submenu:[
            {
                label:'&About',
                action: function()
                {
                    aboutWindow.show();
                }
            }
        ]
    }

]);

menubar.on('select',function(item)
{
    console.log("menu item "+item.label+" clicked");
});

var selectWindowSize = windowSize.OTHERS;
var platform = process.platform;

if(platform == "win32")
{
    selectWindowSize = windowSize.WIN;
}
else if(platform == "linux")
{
    selectWindowSize = windowSize.LINUX;
}
else if(platform == "darwin")
{
    selectWindowSize = windowSize.MAC;
}
else
{
    selectWindowSize = windowSize.OTHERS;
}

var window = app.createWindow({
    width           : selectWindowSize.width,
    height          : selectWindowSize.height,
    icons           : __dirname + '/content/icons',
    resizable       : true,
    topmost         : false,
    url             : 'http://appjs/remote.html',
    disableSecurity : true,
    autoResize      : false
});

window.on('create', function(){
    //console.log("Window Created");
    window.frame.show();
    window.frame.center();
    window.frame.setMenuBar(menubar);
    //window.frame.topmost = false;
});

window.on('ready', function(){
    console.log("Window Ready");
    window.process = process;
    window.module = module;

    /*function F12(e){ return e.keyIdentifier === 'F12' }
    function Command_Option_J(e){ return e.keyCode === 74 && e.metaKey && e.altKey }

    window.addEventListener('keydown', function(e){
        if (F12(e) || Command_Option_J(e)) {
          window.frame.openDevTools();

        }
    });*/

});

window.on('close', function(){
    aboutWindow.close();
    console.log("Window Closed");
});

var aboutWindow = new function()
{
    var aWindow;

    this.show =function()
    {
        if(aWindow)
        {
            if(aWindow.window.frame)
            {
                aWindow.close();
            }
        }

        aWindow = app.createWindow({
            width           : 350,
            height          : 250,
            icons           : __dirname + '/content/icons',
            resizable       : false,
            topmost         : false,
            url             : 'http://appjs/about.html'
        });

        aWindow.on('create', function(){
            //console.log("Window Created");
            aWindow.frame.show();
            aWindow.frame.center();
            //aWindow.frame.openDevTools();
        });

        aWindow.on('ready', function(){
            console.log("About Window Ready");
            aWindow.process = process;
            aWindow.module = module;

            aWindow.addEventListener("open-email", function()
            {
                open("mailto:karthikeyanvj@gmail.com");
            });

            aWindow.addEventListener("open-twitter", function()
            {
                open("https://twitter.com/karthikvj");
            });

        });
    };

    this.close = function()
    {
        if(aWindow)
        {
            if(aWindow.window.frame)
            {
                aWindow.close();
            }
        }
    };

    this.openDevTools = function()
    {
        if(aWindow)
        {
            aWindow.frame.openDevTools();
        }

    };
};

<|endoftext|>


<commit_before>import '/imports/collections/Log.js';

Router.map(function () {
	this.route('log',  {
		path: '/log',
		template: 'showLog',
		data: function() {
			return this.params.query;
		},
		onAfterAction: function() {
			document.title = webpagename + "LOG";
		}
	});
});

Template.showLog.onCreated(function() {
	const instance = this;
	const batchLoad = 100;
	instance.updateUrl = () => {
		var filterParams = instance.filter.toParams();
		var queryString = UrlTools.paramsToQueryString(filterParams);

		var options = {};

		if (queryString.length) {
			options.query = queryString;
		}

		RouterAutoscroll.cancelNext();

		var router = Router.current();
		Router.go(router.route.getName(), {}, options);

		return true;
	};

	instance.ready = new ReactiveVar(false);
	instance.limit = new ReactiveVar(batchLoad);

	var filter = Filtering(LogPredicates);
	instance.filter = filter;

	// Read URL state
	instance.autorun(function() {
		var query = Template.currentData();
		filter
			.clear()
			.read(query)
			.done();
	});

	// Update whenever filter changes
	instance.autorun(function() {
		var filterQuery = filter.toQuery();
		instance.ready.set(false);

		// Have some extra log entries ready so that they are shown immediately
		// when more are demanded
		const overLimit = instance.limit.get() + batchLoad + 1;
		subs.subscribe('log', filterQuery, overLimit, function() {
			instance.ready.set(true);
		});
	});
});

Template.showLog.helpers({
	'privileged': function() {
		return privileged(Meteor.user(), 'admin');
	},

	'date': function() {
		const start = Template.instance().filter.get('start');
		return start && start.toISOString() || "";
	},

	'relFilter': function() {
		const rel = Template.instance().filter.toParams().rel;
		return rel || "";
	},

	'trFilter': function() {
		const tr = Template.instance().filter.toParams().tr;
		return tr || "";
	},

	isodate: function(date) {
		return moment(date).toISOString();
	},

	'hasMore': function() {
		var instance = Template.instance();

		var filterQuery = instance.filter.toQuery();
		var limit = instance.limit.get();
		var results = Log.findFilter(filterQuery, limit + 1);

		return results.count() > limit;
	},

	'results': function() {
		var instance = Template.instance();
		var filterQuery = instance.filter.toQuery();
		const entries = Log.findFilter(filterQuery, instance.limit.get()).fetch();
		let last = false;
		const inter = [];
		_.each(entries, (entry) => {
			const ts = moment(entry.ts);
			if (last) {
				let interval = moment.duration(last.diff(ts));
				if (interval.asMinutes() > 1) {
					inter.push({ interval: interval.humanize() });
				}
			}
			inter.push(entry);
			last = ts;
		});
		return inter;
	},

	'loading': function() {
		return !Template.instance().ready.get();
	},
});

Template.showLog.events({
	// Update the URI when the search-field was changed an loses focus
	'change .js-update-url': function(event, instance) {
		instance.updateUrl();
	},

	'keyup .js-tr-input': _.debounce(function(event, instance) {
		const filter = instance.filter;
		filter.disable('tr');

		const trStr = $('.js-tr-input').val().trim();
		if (trStr) filter.add('tr', trStr)

		filter.done();
	}, 200),

	'keyup .js-date-input': _.debounce(function(event, instance) {
		const filter = instance.filter;
		var dateStr = $('.js-date-input').val().trim();
		if (dateStr === '') {
			filter.disable('date').done();
		} else {
			filter.add('date', dateStr).done();
		}
	}, 200),

	'keyup .js-rel-input': _.debounce(function(event, instance) {
		const filter = instance.filter;
		filter.disable('rel');

		const relStr = $('.js-rel-input').val().trim();
		if (relStr) filter.add('rel', relStr)

		filter.done();
	}, 200),

	'click .js-tr': function(event, instance) {
		instance.filter.add('tr', ""+this).done();
		instance.updateUrl();
		window.scrollTo(0, 0);
	},

	'click .js-date': function(event, instance) {
		var start = moment(this).toISOString();
		instance.filter.add('start', start).done();
		instance.updateUrl();
		window.scrollTo(0, 0);
	},

	'click .js-rel-id': function(event, instance) {
		instance.filter.add('rel', ""+this).done();
		instance.updateUrl();
		window.scrollTo(0, 0);
	},

	'click .js-more': function(event, instance) {
		var limit = instance.limit;
		limit.set(limit.get() + 100);
	}
});
<commit_msg>allow using shift to delay applying the filter<commit_after>import '/imports/collections/Log.js';

Router.map(function () {
	this.route('log',  {
		path: '/log',
		template: 'showLog',
		data: function() {
			return this.params.query;
		},
		onAfterAction: function() {
			document.title = webpagename + "LOG";
		}
	});
});

Template.showLog.onCreated(function() {
	const instance = this;
	const batchLoad = 100;
	instance.updateUrl = () => {
		var filterParams = instance.filter.toParams();
		var queryString = UrlTools.paramsToQueryString(filterParams);

		var options = {};

		if (queryString.length) {
			options.query = queryString;
		}

		RouterAutoscroll.cancelNext();

		var router = Router.current();
		Router.go(router.route.getName(), {}, options);

		return true;
	};

	instance.ready = new ReactiveVar(false);
	instance.limit = new ReactiveVar(batchLoad);

	var filter = Filtering(LogPredicates);
	instance.filter = filter;

	// Read URL state
	instance.autorun(function() {
		var query = Template.currentData();
		filter
			.clear()
			.read(query)
			.done();
	});

	// Update whenever filter changes
	instance.autorun(function() {
		var filterQuery = filter.toQuery();
		instance.ready.set(false);

		// Have some extra log entries ready so that they are shown immediately
		// when more are demanded
		const overLimit = instance.limit.get() + batchLoad + 1;
		subs.subscribe('log', filterQuery, overLimit, function() {
			instance.ready.set(true);
		});
	});
});

Template.showLog.helpers({
	'privileged': function() {
		return privileged(Meteor.user(), 'admin');
	},

	'date': function() {
		const start = Template.instance().filter.get('start');
		return start && start.toISOString() || "";
	},

	'relFilter': function() {
		const rel = Template.instance().filter.toParams().rel;
		return rel || "";
	},

	'trFilter': function() {
		const tr = Template.instance().filter.toParams().tr;
		return tr || "";
	},

	isodate: function(date) {
		return moment(date).toISOString();
	},

	'hasMore': function() {
		var instance = Template.instance();

		var filterQuery = instance.filter.toQuery();
		var limit = instance.limit.get();
		var results = Log.findFilter(filterQuery, limit + 1);

		return results.count() > limit;
	},

	'results': function() {
		var instance = Template.instance();
		var filterQuery = instance.filter.toQuery();
		const entries = Log.findFilter(filterQuery, instance.limit.get()).fetch();
		let last = false;
		const inter = [];
		_.each(entries, (entry) => {
			const ts = moment(entry.ts);
			if (last) {
				let interval = moment.duration(last.diff(ts));
				if (interval.asMinutes() > 1) {
					inter.push({ interval: interval.humanize() });
				}
			}
			inter.push(entry);
			last = ts;
		});
		return inter;
	},

	'loading': function() {
		return !Template.instance().ready.get();
	},
});

Template.showLog.events({
	// Update the URI when the search-field was changed an loses focus
	'change .js-update-url': function(event, instance) {
		instance.updateUrl();
	},

	'keyup .js-tr-input': _.debounce(function(event, instance) {
		const filter = instance.filter;
		filter.disable('tr');

		const trStr = $('.js-tr-input').val().trim();
		if (trStr) filter.add('tr', trStr)

		filter.done();
	}, 200),

	'keyup .js-date-input': _.debounce(function(event, instance) {
		const filter = instance.filter;
		var dateStr = $('.js-date-input').val().trim();
		if (dateStr === '') {
			filter.disable('date').done();
		} else {
			filter.add('date', dateStr).done();
		}
	}, 200),

	'keyup .js-rel-input': _.debounce(function(event, instance) {
		const filter = instance.filter;
		filter.disable('rel');

		const relStr = $('.js-rel-input').val().trim();
		if (relStr) filter.add('rel', relStr)

		filter.done();
	}, 200),

	'click .js-tr': function(event, instance) {
		instance.filter.add('tr', ""+this)
		if (!event.shiftKey) {
			instance.filter.done();
			instance.updateUrl();
			window.scrollTo(0, 0);
		}
	},

	'click .js-date': function(event, instance) {
		var start = moment(this).toISOString();
		instance.filter.add('start', start)
		if (!event.shiftKey) {
			instance.filter.done();
			instance.updateUrl();
			window.scrollTo(0, 0);
		}
	},

	'click .js-rel-id': function(event, instance) {
		instance.filter.add('rel', ""+this);
		if (!event.shiftKey) {
			instance.filter.done();
			instance.updateUrl();
			window.scrollTo(0, 0);
		}
	},

	'click .js-more': function(event, instance) {
		var limit = instance.limit;
		limit.set(limit.get() + 100);
	}
});
<|endoftext|>


<commit_before>import {getSupport, currentBrowser, getVersionIndex} from 'caniuse-support'
import autoprefixer from 'autoprefixer'
import data from 'autoprefixer/data/prefixes'
import postcssJs from 'postcss-js'
import {dashify} from '../utils'

const browserQuery = `${currentBrowser.id} ${getVersionIndex(currentBrowser)}`
const ap = autoprefixer({browsers: browserQuery})
const prefixer = postcssJs.sync([ap])

const skipProperties = [
  // caniuse doesn't cover this property and spec might drop this: https://www.w3.org/TR/css-fonts-3/.
  'font-language-override',
  // Lack of caniuse data. See https://github.com/Fyrd/caniuse/issues/2116
  'font-variant-ligatures',
]

const isNotSupported = (o) =>
    o.level === 'none' ||
    // http://caniuse.com/#feat=object-fit
    o.property === 'object-position' && o.notes.indexOf(1) > -1 ||
    // http://caniuse.com/#feat=multicolumn
    // https://bugzilla.mozilla.org/show_bug.cgi?id=616436
    o.property === 'column-span' && currentBrowser.id === 'firefox' ||
    o.property === 'column-fill' && o.notes.indexOf(2) > -1 ||
    // http://caniuse.com/#feat=css-masks
    o.property.match(/^mask-/) && o.notes.indexOf(2) > -1 ||
    o.property.match(/^mask-border-/) && o.notes.indexOf(3) > -1 ||
    // http://caniuse.com/#feat=text-decoration
    o.property === 'text-decoration-skip' && o.notes.indexOf(4) > -1 ||
    o.property === 'text-decoration-style' && o.notes.indexOf(2) > -1

function generateFixture() {
  const fixture = {}
  Object.keys(data).
    // Filters autoprefixer data to include only property prefix related entries.
    filter(s => s.match(/^[^:@].*$/g)).
    filter(s => data[s].props === undefined).
    filter(s => skipProperties.indexOf(s) < 0).
    // TODO: Remove the following line when this is resolved: https://github.com/Fyrd/caniuse/issues/3070.
    filter(s => ['css3-cursors-grab', 'css-text-spacing'].indexOf(data[s].feature) < 0).
    map(s => ({property: s, feature: data[s].feature, ...getSupport(data[s].feature)})).
    // No support in caniuse db means no support for the spec, but
    // no support in css-vendor means no browser support at all for the particular property,
    // therefore we cannot test with the caniuse data for these cases.
    filter(o => !isNotSupported(o)).
    forEach(o => {
      fixture[o.property] = dashify(Object.keys(prefixer({[o.property]: ''}))[0])
    })
  return fixture
}

export default generateFixture()

<commit_msg>Exclude image-rendering when not supported<commit_after>import {getSupport, currentBrowser, getVersionIndex} from 'caniuse-support'
import autoprefixer from 'autoprefixer'
import data from 'autoprefixer/data/prefixes'
import postcssJs from 'postcss-js'
import {dashify} from '../utils'

const browserQuery = `${currentBrowser.id} ${getVersionIndex(currentBrowser)}`
const ap = autoprefixer({browsers: browserQuery})
const prefixer = postcssJs.sync([ap])

const skipProperties = [
  // caniuse doesn't cover this property and spec might drop this: https://www.w3.org/TR/css-fonts-3/.
  'font-language-override',
  // Lack of caniuse data. See https://github.com/Fyrd/caniuse/issues/2116
  'font-variant-ligatures',
]

const isNotSupported = (o) =>
    o.level === 'none' ||
    // http://caniuse.com/#feat=object-fit
    o.property === 'object-position' && o.notes.indexOf(1) > -1 ||
    // http://caniuse.com/#feat=multicolumn
    // https://bugzilla.mozilla.org/show_bug.cgi?id=616436
    o.property === 'column-span' && currentBrowser.id === 'firefox' ||
    o.property === 'column-fill' && o.notes.indexOf(2) > -1 ||
    // http://caniuse.com/#feat=css-masks
    o.property.match(/^mask-/) && o.notes.indexOf(2) > -1 ||
    o.property.match(/^mask-border-/) && o.notes.indexOf(3) > -1 ||
    // http://caniuse.com/#feat=text-decoration
    o.property === 'text-decoration-skip' && o.notes.indexOf(4) > -1 ||
    o.property === 'text-decoration-style' && o.notes.indexOf(2) > -1 ||
    // http://caniuse.com/#feat=css-crisp-edges
    o.property === 'image-rendering' && o.notes.indexOf(2) > -1

function generateFixture() {
  const fixture = {}
  Object.keys(data).
    // Filters autoprefixer data to include only property prefix related entries.
    filter(s => s.match(/^[^:@].*$/g)).
    filter(s => data[s].props === undefined).
    filter(s => skipProperties.indexOf(s) < 0).
    // TODO: Remove the following line when this is resolved: https://github.com/Fyrd/caniuse/issues/3070.
    filter(s => ['css3-cursors-grab', 'css-text-spacing'].indexOf(data[s].feature) < 0).
    map(s => ({property: s, feature: data[s].feature, ...getSupport(data[s].feature)})).
    // No support in caniuse db means no support for the spec, but
    // no support in css-vendor means no browser support at all for the particular property,
    // therefore we cannot test with the caniuse data for these cases.
    filter(o => !isNotSupported(o)).
    forEach(o => {
      fixture[o.property] = dashify(Object.keys(prefixer({[o.property]: ''}))[0])
    })
  return fixture
}

export default generateFixture()

<|endoftext|>


<commit_before>const Firebase = require('firebase');
const crypto = require('crypto');
const _ = require('lodash');
const mailer = require('./../mailer');
const config = require('./../config');

const fb = new Firebase(config.FB_DB);

const getDomainFromEmail = (email) => {
  const email_string_array = email.split("@");
  return email_string_array[email_string_array.length - 1];
};

const generateUniqueCode = () => {
  const chars = "ABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
  const howMany = 5;
  const rnd = crypto.randomBytes(howMany),
    value = new Array(howMany),
    len = chars.length;

  for (var i = 0; i < howMany; i++) {
    value[i] = chars[rnd[i] % len];
  }

  return value.join('');
};

const startProcess = (whiteListDomains) => {

  const domains = whiteListDomains.split(';');

  fb.authWithCustomToken(config.FB_MASTER_SECRET).then((authData) => {

    // listen for child_added event in the users
    fb.child('users').on('child_added', (snapShot) => {
      // check if we have a corresponding verification entry
      const uid = snapShot.val().uid;
      const email = snapShot.val().email;

      // verify if the supplied email/domain is in our white List
      if (_.includes(domains, getDomainFromEmail(email))) {
        fb.child(`meta/users/${uid}`).once('value').then((metaSnapShot) => {
          // if the node does not exists then create one
          if (metaSnapShot.val() === null) {
            const generatedCode = generateUniqueCode();
            // we ought to create it
            fb.child(`meta/users/${uid}`).set({
              verified: false,
              code: generatedCode
            }).then(() => mailer.sendEmailVerification(generatedCode, email));
          }
        });
      } else {
        // what should we do ?
        console.warn(`An email ${email} that is not whiteListed was used ..`);
      }
    });

    // listen for child_added event in code_verifier/users
    fb.child('code_verifier').on('child_added', (snapShot) => {
      // compare the code with the one that we sent out earlier
      const supplied_code_value = snapShot.val().code;
      const entryKey = snapShot.key();

      fb.child(`meta/users/${entryKey}`).once('value').then((metaSnapShot) => {
        const generated_code_value = metaSnapShot.val().code;
        if (supplied_code_value === generated_code_value) {
          // set verified to true
          fb.child(`meta/users/${entryKey}`).set({
            verified: true
          });
          // destroy the code_verifier node
          fb.child(`code_verifier/${entryKey}`).remove();
        }
      });
    });

  });

};

fb.authWithCustomToken(config.FB_MASTER_SECRET).then((authData) => {
  fb.child('meta/app').once('value').then((appSnapShot) => {
    const requireEmailVerification = appSnapShot.val().requireEmailVerification;

    if (requireEmailVerification) {
      console.info('Starting the worker ...');
      startProcess(appSnapShot.val().whiteListDomains);
    } else {
      // we do not need really need this worker
      console.info('Email verification is not required !');
      process.exit(0);
    }
  });
});
<commit_msg>fix(backend/firebase/jobs) - correct email comparison / make sure to set verification_in_progress / remove code_verifier node after invalid verification as well<commit_after>const Firebase = require('firebase');
const crypto = require('crypto');
const _ = require('lodash');
const mailer = require('./../mailer');
const config = require('./../config');

const fb = new Firebase(config.FB_DB);

const getDomainFromEmail = (email) => {
  const email_string_array = email.split("@");
  return '@' + email_string_array[email_string_array.length - 1];
};

const generateUniqueCode = () => {
  const chars = "ABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
  const howMany = 5;
  const rnd = crypto.randomBytes(howMany),
    value = new Array(howMany),
    len = chars.length;

  for (var i = 0; i < howMany; i++) {
    value[i] = chars[rnd[i] % len];
  }

  return value.join('');
};

const startProcess = (whiteListDomains) => {

  const domains = whiteListDomains.split(';');

  fb.authWithCustomToken(config.FB_MASTER_SECRET).then((authData) => {

    // listen for child_added event in the users
    fb.child('users').on('child_added', (snapShot) => {
      // check if we have a corresponding verification entry
      const uid = snapShot.val().uid;
      const email = snapShot.val().email;

      // verify if the supplied email/domain is in our white List
      if (_.includes(domains, getDomainFromEmail(email))) {
        fb.child(`meta/users/${uid}`).once('value').then((metaSnapShot) => {
          // if the node does not exists then create one
          if (metaSnapShot.val() === null) {
            const generatedCode = generateUniqueCode();
            // we ought to create it
            fb.child(`meta/users/${uid}`).set({
              verified: false,
              code: generatedCode
            }).then(() => mailer.sendEmailVerification(generatedCode, email));
          }
        });
      } else {
        // what should we do ?
        console.warn(`An email ${email} that is not whiteListed was used ..`);
      }
    });

    // listen for child_added event in code_verifier/users
    fb.child('code_verifier').on('child_added', (snapShot) => {
      // compare the code with the one that we sent out earlier
      const supplied_code_value = snapShot.val().code;
      const entryKey = snapShot.key();

      fb.child(`meta/users/${entryKey}`).once('value').then((metaSnapShot) => {
        const generated_code_value = metaSnapShot.val().code;
        if (supplied_code_value === generated_code_value) {

          // set verified to true
          fb.child(`meta/users/${entryKey}`).set({
              verified: true
            })
            .then(() => fb.child(`users/${entryKey}/verified`).set(true))
            .then(() => fb.child(`users/${entryKey}/verification_in_progress`).set(false));

          // destroy the code_verifier node
          fb.child(`code_verifier/${entryKey}`).remove();
        } else {
          // destroy the code_verifier node
          fb.child(`code_verifier/${entryKey}`).remove();
          // set the progress to false
          fb.child(`users/${entryKey}/verification_in_progress`).set(false);
        }
      });
    });

  });

};

fb.authWithCustomToken(config.FB_MASTER_SECRET).then((authData) => {
  fb.child('meta/app').once('value').then((appSnapShot) => {
    const requireEmailVerification = appSnapShot.val().requireEmailVerification;

    if (requireEmailVerification) {
      console.info('Starting the worker ...');
      startProcess(appSnapShot.val().whiteListDomains);
    } else {
      // we do not need really need this worker
      console.info('Email verification is not required !');
      process.exit(0);
    }
  });
});
<|endoftext|>