<commit_before>// this class is not really related to a sampleToc but can be used for any TOC

import API from 'src/util/api';
import Versioning from 'src/util/versioning';
import Color from 'src/util/color';

const SpectraConfigs = {
  IR: {
    tocFilter: (entry) => entry.value.nbIR && !entry.value.hidden,
    tocCallback: (entry) => {
      entry.value.nbSpectra = entry.value.nbIR;
    },
    getSpectra: (sample) => {
      if (
        sample &&
        sample.$content &&
        sample.$content.spectra &&
        Array.isArray(sample.$content.spectra.ir)
      ) {
        let spectra = sample.$content.spectra.ir;
        return spectra;
      } else {
        return [];
      }
    },
    chartPrefs: {
      xLabel: 'Wavelength [cm-1]',
      displayXAxis: [
        'display',
        'flip',
        'main',
        'sec'
      ]
    }
  },
  Raman: {
    tocFilter: (entry) => entry.value.nbRaman && !entry.value.hidden,
    tocCallback: (entry) => {
      entry.value.nbSpectra = entry.value.nbRaman;
    },
    getSpectra: (sample) => {
      if (
        sample &&
        sample.$content &&
        sample.$content.spectra &&
        Array.isArray(sample.$content.spectra.nbRaman)
      ) {
        let spectra = sample.$content.spectra.raman;
        return spectra;
      } else {
        return [];
      }
    },
    chartPrefs: {
      xLabel: 'Wavelength [cm-1]',
      displayXAxis: [
        'display',
        'flip',
        'main',
        'sec'
      ]
    }
  },
  '1H NMR': {
    tocFilter: (entry) => entry.value.nb1h && !entry.value.hidden,
    tocCallback: (entry) => {
      entry.value.nbSpectra = entry.value.nb1h;
    },
    getSpectra: (sample) => {
      if (
        sample &&
        sample.$content &&
        sample.$content.spectra &&
        Array.isArray(sample.$content.spectra.nmr)
      ) {
        let spectra = sample.$content.spectra.nmr;
        spectra = spectra.filter(
          (spectrum) => spectrum.dimension === 1 && spectrum.nucleus[0] === '1H'
        );
        spectra.forEach((spectrum) => {
          let info = [];
          if (spectrum.nucleus) info.push(spectrum.nucleus[0]);
          if (spectrum.experiment) info.push(spectrum.experiment);
          if (spectrum.solvent) info.push(spectrum.solvent);
          if (spectrum.frequency) info.push(spectrum.frequency.toFixed(0));
          spectrum.info = info.join(', ');
        });
        return spectra;
      } else {
        return [];
      }
    },
    chartPrefs: {
      xLabel: 'δ [ppm]',
      displayXAxis: [
        'display',
        'flip',
        'main',
        'sec'
      ]
    }
  },
  Chromatography: {
    tocFilter: (entry) => entry.value.mbChrom && !entry.value.hidden,
    tocCallback: (entry) => {
      entry.value.nbSpectra = entry.value.mbChrom;
    },
    getSpectra: (sample) => {
      if (
        sample &&
        sample.$content &&
        sample.$content.spectra &&
        Array.isArray(sample.$content.spectra.chromatogram)
      ) {
        let spectra = sample.$content.spectra.chromatogram;
        return spectra;
      } else {
        return [];
      }
    },
    chartPrefs: {
      xLabel: 'Time [s]',
      displayXAxis: [
        'display',
        'flip',
        'main',
        'sec'
      ]
    }
  }
};

class SpectraDataSet {
  constructor(roc, sampleToc, options = {}) {
    this.roc = roc;
    this.sampleToc = sampleToc;
    this.spectraConfig = undefined;
    this.defaultAttributes = options.defaultAttributes || {};
  }

  getChartPrefs() {
    return this.spectraConfig.chartPrefs;
  }

  /**
   * @param {object} [options={}]
   * @param {string} [options.varName='analysisKind'] contains the name of the variable containing the form value
   * @param {string} [options.schemaVarName='analysisKindSchema'] contains the name of the variable containing the form schema
   * @return {string} the form to select group}
   */
  async initializeAnalysis(options = {}) {
    const {
      schemaVarName = 'analysisKindSchema',
      varName = 'analysisKind',
      cookieName = 'eln-default-analysis-kind'
    } = options;

    var possibleAnalysis = Object.keys(SpectraConfigs);
    var defaultAnalysis = localStorage.getItem(cookieName);
    if (possibleAnalysis.indexOf(defaultAnalysis) === -1) {
      defaultAnalysis = possibleAnalysis[0];
    }
    var schema = {
      type: 'object',
      properties: {
        analysis: {
          type: 'string',
          enum: possibleAnalysis,
          default: defaultAnalysis,
          required: true
        }
      }
    };

    API.createData(schemaVarName, schema);

    let analysisKind = await API.createData(varName, {
      analysis: defaultAnalysis
    });

    this.spectraConfig = SpectraConfigs[defaultAnalysis];

    await this.refresh();

    let mainData = Versioning.getData();
    mainData.onChange((evt) => {
      if (evt.jpath[0] === varName) {
        localStorage.setItem(cookieName, analysisKind.analysis);
        this.spectraConfig = SpectraConfigs[String(analysisKind.analysis)];
        this.refresh();
      }
    });

    return analysisKind;
  }

  refresh() {
    this.sampleToc.options.filter = this.spectraConfig.tocFilter;
    this.sampleToc.options.callback = this.spectraConfig.tocCallback;
    this.sampleToc.refresh();
  }

  async processAction(action) {
    console.log({ action });
    switch (action.name) {
      case 'clickedSample':
        this.clickedSample(action.value);
        break;
      case 'refresh':
        this.refresh();
        break;
      case 'hideSpectra':
        this.hideSpectra();
        break;
      case 'forceRecolor': {
        let selectedSpectra = API.getData('selectedSpectra');
        selectedSpectra.forEach((spectrum) => spectrum.color = '');
        recolor(selectedSpectra);
        break;
      }
      case 'showSpectra':
        this.showSpectra();
        break;
      case 'clearSelectedSamples':
        {
          let selectedSpectra = API.getData('selectedSpectra');
          selectedSpectra.length = 0;
          selectedSpectra.triggerChange();
        }
        break;
      case 'addSelectedSamples':
        await this.addSelectedSamples(API.getData('tocSelected').resurrect());
        break;
      case 'addSample':
        await this.addSelectedSamples([action.value.resurrect()]);
        break;
      case 'addSpectrum':
        await this.addSpectrum(
          API.getData('tocClicked').resurrect(),
          action.value.resurrect()
        );
        break;
      default:
    }
  }

  async clickedSample(samples) {
    if (samples.length !== 1) {
      API.createData('spectra', []);
      return;
    }
    let uuid = String(samples[0].id);
    let data = await this.roc.document(uuid, { varName: 'linkedSample' });
    let spectra = this.spectraConfig.getSpectra(data);
    API.createData('spectra', spectra);
  }

  showSpectra() {
    let selectedSpectra = API.getData('selectedSpectra');
    let currentlySelectedSpectra = API.getData('currentlySelectedSpectra');
    for (let currentlySelectedSpectrum of currentlySelectedSpectra) {
      let spectrum = selectedSpectra.filter((spectrum) => String(spectrum.id) === String(currentlySelectedSpectrum.id))[0];
      spectrum.display = true;
    }
    API.getData('selectedSpectra').triggerChange();
  }

  hideSpectra() {
    let selectedSpectra = API.getData('selectedSpectra');
    let currentlySelectedSpectra = API.getData('currentlySelectedSpectra');
    for (let currentlySelectedSpectrum of currentlySelectedSpectra) {
      let spectrum = selectedSpectra.filter((spectrum) => String(spectrum.id) === String(currentlySelectedSpectrum.id))[0];
      spectrum.display = false;
    }
    API.getData('selectedSpectra').triggerChange();
  }

  addSpectrum(tocEntry, spectrum) {
    let selectedSpectra = API.getData('selectedSpectra');
    this.addSpectrumToSelected(spectrum, tocEntry, selectedSpectra);
    recolor(selectedSpectra);
    selectedSpectra.triggerChange();
  }

  async addSelectedSamples(tocSelected) {
    let selectedSpectra = API.getData('selectedSpectra');
    // count the number of sampleIDs to determine the number of colros
    let promises = [];
    for (let tocEntry of tocSelected) {
      promises.push(
        this.roc.document(tocEntry.id).then((sample) => {
          let spectra = this.spectraConfig.getSpectra(sample);
          for (let spectrum of spectra) {
            if (spectrum.jcamp && spectrum.jcamp.filename) {
              this.addSpectrumToSelected(spectrum, tocEntry, selectedSpectra);
            }
          }
        })
      );
    }
    await Promise.all(promises);
    recolor(selectedSpectra);
    selectedSpectra.triggerChange();
  }

  addSpectrumToSelected(spectrum, tocEntry, selectedSpectra) {
    if (spectrum.jcamp) {
      let spectrumID = String(tocEntry.id + spectrum.jcamp.filename);
      let sampleID = String(tocEntry.id);
      if (selectedSpectra.filter((spectrum) => String(spectrum.id) === spectrumID).length > 0) return;
      spectrum.sampleID = sampleID;
      spectrum.id = spectrumID;
      spectrum.display = true;
      for (let key in this.defaultAttributes) {
        spectrum[key] = this.defaultAttributes[key];
      }

      spectrum.deconvolutionReference = false;
      spectrum.sampleCode = tocEntry.key.slice(1).join('_');
      spectrum.toc = tocEntry;
      spectrum.category = spectrum.sampleCode;
      spectrum._highlight = spectrumID;
      selectedSpectra.push(spectrum);
    }
  }
}

function recolor(selectedSpectra) {
  // need to count the categories
  let categoryColors = {};
  let existingColors = 0;
  for (let spectrum of selectedSpectra) {
    let category = String(spectrum.category);
    if (categoryColors[category] === undefined) {
      if (spectrum.color) {
        categoryColors[String(spectrum.category)] = spectrum.color;
        existingColors++;
      } else {
        categoryColors[String(spectrum.category)] = '';
      }
    }
  }

  let nbColors = Math.max(
    8,
    1 << Math.ceil(Math.log2(Object.keys(categoryColors).length))
  );
  const colors = Color.getDistinctColorsAsString(nbColors);
  let i = existingColors;
  for (let key in categoryColors) {
    if (!categoryColors[key]) {
      categoryColors[key] = colors[i++];
    }
  }
  for (let spectrum of selectedSpectra) {
    if (!spectrum.color) {
      spectrum.color = categoryColors[String(spectrum.category)];
    }
  }
}

module.exports = SpectraDataSet;
<commit_msg>fix(SpectraDataSet): trigger change after recolor<commit_after>// this class is not really related to a sampleToc but can be used for any TOC

import API from 'src/util/api';
import Versioning from 'src/util/versioning';
import Color from 'src/util/color';

const SpectraConfigs = {
  IR: {
    tocFilter: (entry) => entry.value.nbIR && !entry.value.hidden,
    tocCallback: (entry) => {
      entry.value.nbSpectra = entry.value.nbIR;
    },
    getSpectra: (sample) => {
      if (
        sample &&
        sample.$content &&
        sample.$content.spectra &&
        Array.isArray(sample.$content.spectra.ir)
      ) {
        let spectra = sample.$content.spectra.ir;
        return spectra;
      } else {
        return [];
      }
    },
    chartPrefs: {
      xLabel: 'Wavelength [cm-1]',
      displayXAxis: [
        'display',
        'flip',
        'main',
        'sec'
      ]
    }
  },
  Raman: {
    tocFilter: (entry) => entry.value.nbRaman && !entry.value.hidden,
    tocCallback: (entry) => {
      entry.value.nbSpectra = entry.value.nbRaman;
    },
    getSpectra: (sample) => {
      if (
        sample &&
        sample.$content &&
        sample.$content.spectra &&
        Array.isArray(sample.$content.spectra.nbRaman)
      ) {
        let spectra = sample.$content.spectra.raman;
        return spectra;
      } else {
        return [];
      }
    },
    chartPrefs: {
      xLabel: 'Wavelength [cm-1]',
      displayXAxis: [
        'display',
        'flip',
        'main',
        'sec'
      ]
    }
  },
  '1H NMR': {
    tocFilter: (entry) => entry.value.nb1h && !entry.value.hidden,
    tocCallback: (entry) => {
      entry.value.nbSpectra = entry.value.nb1h;
    },
    getSpectra: (sample) => {
      if (
        sample &&
        sample.$content &&
        sample.$content.spectra &&
        Array.isArray(sample.$content.spectra.nmr)
      ) {
        let spectra = sample.$content.spectra.nmr;
        spectra = spectra.filter(
          (spectrum) => spectrum.dimension === 1 && spectrum.nucleus[0] === '1H'
        );
        spectra.forEach((spectrum) => {
          let info = [];
          if (spectrum.nucleus) info.push(spectrum.nucleus[0]);
          if (spectrum.experiment) info.push(spectrum.experiment);
          if (spectrum.solvent) info.push(spectrum.solvent);
          if (spectrum.frequency) info.push(spectrum.frequency.toFixed(0));
          spectrum.info = info.join(', ');
        });
        return spectra;
      } else {
        return [];
      }
    },
    chartPrefs: {
      xLabel: 'δ [ppm]',
      displayXAxis: [
        'display',
        'flip',
        'main',
        'sec'
      ]
    }
  },
  Chromatography: {
    tocFilter: (entry) => entry.value.mbChrom && !entry.value.hidden,
    tocCallback: (entry) => {
      entry.value.nbSpectra = entry.value.mbChrom;
    },
    getSpectra: (sample) => {
      if (
        sample &&
        sample.$content &&
        sample.$content.spectra &&
        Array.isArray(sample.$content.spectra.chromatogram)
      ) {
        let spectra = sample.$content.spectra.chromatogram;
        return spectra;
      } else {
        return [];
      }
    },
    chartPrefs: {
      xLabel: 'Time [s]',
      displayXAxis: [
        'display',
        'flip',
        'main',
        'sec'
      ]
    }
  }
};

class SpectraDataSet {
  constructor(roc, sampleToc, options = {}) {
    this.roc = roc;
    this.sampleToc = sampleToc;
    this.spectraConfig = undefined;
    this.defaultAttributes = options.defaultAttributes || {};
  }

  getChartPrefs() {
    return this.spectraConfig.chartPrefs;
  }

  /**
   * @param {object} [options={}]
   * @param {string} [options.varName='analysisKind'] contains the name of the variable containing the form value
   * @param {string} [options.schemaVarName='analysisKindSchema'] contains the name of the variable containing the form schema
   * @return {string} the form to select group}
   */
  async initializeAnalysis(options = {}) {
    const {
      schemaVarName = 'analysisKindSchema',
      varName = 'analysisKind',
      cookieName = 'eln-default-analysis-kind'
    } = options;

    var possibleAnalysis = Object.keys(SpectraConfigs);
    var defaultAnalysis = localStorage.getItem(cookieName);
    if (possibleAnalysis.indexOf(defaultAnalysis) === -1) {
      defaultAnalysis = possibleAnalysis[0];
    }
    var schema = {
      type: 'object',
      properties: {
        analysis: {
          type: 'string',
          enum: possibleAnalysis,
          default: defaultAnalysis,
          required: true
        }
      }
    };

    API.createData(schemaVarName, schema);

    let analysisKind = await API.createData(varName, {
      analysis: defaultAnalysis
    });

    this.spectraConfig = SpectraConfigs[defaultAnalysis];

    await this.refresh();

    let mainData = Versioning.getData();
    mainData.onChange((evt) => {
      if (evt.jpath[0] === varName) {
        localStorage.setItem(cookieName, analysisKind.analysis);
        this.spectraConfig = SpectraConfigs[String(analysisKind.analysis)];
        this.refresh();
      }
    });

    return analysisKind;
  }

  refresh() {
    this.sampleToc.options.filter = this.spectraConfig.tocFilter;
    this.sampleToc.options.callback = this.spectraConfig.tocCallback;
    this.sampleToc.refresh();
  }

  async processAction(action) {
    console.log({ action });
    switch (action.name) {
      case 'clickedSample':
        this.clickedSample(action.value);
        break;
      case 'refresh':
        this.refresh();
        break;
      case 'hideSpectra':
        this.hideSpectra();
        break;
      case 'forceRecolor': {
        let selectedSpectra = API.getData('selectedSpectra');
        selectedSpectra.forEach((spectrum) => spectrum.color = '');
        recolor(selectedSpectra);
        selectedSpectra.triggerChange();
        break;
      }
      case 'showSpectra':
        this.showSpectra();
        break;
      case 'clearSelectedSamples':
        {
          let selectedSpectra = API.getData('selectedSpectra');
          selectedSpectra.length = 0;
          selectedSpectra.triggerChange();
        }
        break;
      case 'addSelectedSamples':
        await this.addSelectedSamples(API.getData('tocSelected').resurrect());
        break;
      case 'addSample':
        await this.addSelectedSamples([action.value.resurrect()]);
        break;
      case 'addSpectrum':
        await this.addSpectrum(
          API.getData('tocClicked').resurrect(),
          action.value.resurrect()
        );
        break;
      default:
    }
  }

  async clickedSample(samples) {
    if (samples.length !== 1) {
      API.createData('spectra', []);
      return;
    }
    let uuid = String(samples[0].id);
    let data = await this.roc.document(uuid, { varName: 'linkedSample' });
    let spectra = this.spectraConfig.getSpectra(data);
    API.createData('spectra', spectra);
  }

  showSpectra() {
    let selectedSpectra = API.getData('selectedSpectra');
    let currentlySelectedSpectra = API.getData('currentlySelectedSpectra');
    for (let currentlySelectedSpectrum of currentlySelectedSpectra) {
      let spectrum = selectedSpectra.filter((spectrum) => String(spectrum.id) === String(currentlySelectedSpectrum.id))[0];
      spectrum.display = true;
    }
    API.getData('selectedSpectra').triggerChange();
  }

  hideSpectra() {
    let selectedSpectra = API.getData('selectedSpectra');
    let currentlySelectedSpectra = API.getData('currentlySelectedSpectra');
    for (let currentlySelectedSpectrum of currentlySelectedSpectra) {
      let spectrum = selectedSpectra.filter((spectrum) => String(spectrum.id) === String(currentlySelectedSpectrum.id))[0];
      spectrum.display = false;
    }
    API.getData('selectedSpectra').triggerChange();
  }

  addSpectrum(tocEntry, spectrum) {
    let selectedSpectra = API.getData('selectedSpectra');
    this.addSpectrumToSelected(spectrum, tocEntry, selectedSpectra);
    recolor(selectedSpectra);
    selectedSpectra.triggerChange();
  }

  async addSelectedSamples(tocSelected) {
    let selectedSpectra = API.getData('selectedSpectra');
    // count the number of sampleIDs to determine the number of colros
    let promises = [];
    for (let tocEntry of tocSelected) {
      promises.push(
        this.roc.document(tocEntry.id).then((sample) => {
          let spectra = this.spectraConfig.getSpectra(sample);
          for (let spectrum of spectra) {
            if (spectrum.jcamp && spectrum.jcamp.filename) {
              this.addSpectrumToSelected(spectrum, tocEntry, selectedSpectra);
            }
          }
        })
      );
    }
    await Promise.all(promises);
    recolor(selectedSpectra);
    selectedSpectra.triggerChange();
  }

  addSpectrumToSelected(spectrum, tocEntry, selectedSpectra) {
    if (spectrum.jcamp) {
      let spectrumID = String(tocEntry.id + spectrum.jcamp.filename);
      let sampleID = String(tocEntry.id);
      if (selectedSpectra.filter((spectrum) => String(spectrum.id) === spectrumID).length > 0) return;
      spectrum.sampleID = sampleID;
      spectrum.id = spectrumID;
      spectrum.display = true;
      for (let key in this.defaultAttributes) {
        spectrum[key] = this.defaultAttributes[key];
      }

      spectrum.deconvolutionReference = false;
      spectrum.sampleCode = tocEntry.key.slice(1).join('_');
      spectrum.toc = tocEntry;
      spectrum.category = spectrum.sampleCode;
      spectrum._highlight = spectrumID;
      selectedSpectra.push(spectrum);
    }
  }
}

function recolor(selectedSpectra) {
  // need to count the categories
  let categoryColors = {};
  let existingColors = 0;
  for (let spectrum of selectedSpectra) {
    let category = String(spectrum.category);
    if (categoryColors[category] === undefined) {
      if (spectrum.color) {
        categoryColors[String(spectrum.category)] = spectrum.color;
        existingColors++;
      } else {
        categoryColors[String(spectrum.category)] = '';
      }
    }
  }

  let nbColors = Math.max(
    8,
    1 << Math.ceil(Math.log2(Object.keys(categoryColors).length))
  );
  const colors = Color.getDistinctColorsAsString(nbColors);
  let i = existingColors;
  for (let key in categoryColors) {
    if (!categoryColors[key]) {
      categoryColors[key] = colors[i++];
    }
  }
  for (let spectrum of selectedSpectra) {
    if (!spectrum.color) {
      spectrum.color = categoryColors[String(spectrum.category)];
    }
  }
}

module.exports = SpectraDataSet;
<|endoftext|>


<commit_before>openerp.web_hw_collector = function(instance) {
    instance.web_hw_collector.HwCollector = instance.web.form.FieldChar.extend({
        template: "HwCollector",
        start: function() {
            var _this = this;
            this.render_value();
            self.$(".hw_collector_button").click(function() {
                _this.set_value('9');
                _this.render_value();
                _this.view.save();
            });
        },
    });

    instance.web.form.widgets.add("hw_collector", "instance.web_hw_collector.HwCollector");
}

<commit_msg>Get information from server and contact weight server.<commit_after>openerp.web_hw_collector = function(instance) {
    instance.web_hw_collector.HwCollector = instance.web.form.FieldChar.extend({
        template: "HwCollector",
        start: function() {
            var _this = this;
            this.render_value();

            var createCORSRequest = function(method, url) {
                var xhr = new XMLHttpRequest();
                if ("withCredentials" in xhr) {
                    xhr.open(method, url, true);
                } else if (typeof XDomainRequest != "undefined") {
                    xhr = new XDomainRequest();
                    xhr.open(method, url);
                } else {
                    xhr = null;
                }
                return xhr;
            };

            var corsCall = function(url, callback){
                var xhr = createCORSRequest('GET', url);
                xhr.onreadystatechange = function() {
                    if (xhr.status >= 200 && xhr.status < 400) {
                        var responseText = xhr.responseText;
                        callback(responseText);
                        // alert('CORS call completed at \'' + url + '\' returning: ' + responseText);
                    } else {
                        alert('Error while calling CORS at ' + url);
                    }
                };
                xhr.send();
            };

            self.$(".hw_collector_button").click(function() {
                var model = new instance.web.Model("ir.config_parameter");
                model.call("get_param", ['hw.proxy'], {context: new instance.web.CompoundContext()}).then(function(url) {
                    corsCall(url, function(value){
                        _this.set_value(value);
                        _this.render_value();
                        _this.view.save();
                    });
                });
            });
        },
    });

    instance.web.form.widgets.add("hw_collector", "instance.web_hw_collector.HwCollector");
}

<|endoftext|>


<commit_before>'use strict';
var Geometry = require('famous-webgl-geometries');

/**
 * The Mesh class is responsible for providing the API for how
 * a RenderNode will interact with the WebGL API by adding
 * a set of commands to the renderer.
 *
 * @class Mesh
 * @constructor
 * @renderable
 * @param {LocalDispatch} dispatch LocalDispatch to be retrieved
 * @param {object} Options Optional params for configuring Mesh
 */
function Mesh (node, options) {
    this._node = node;
    this._changeQueue = [];
    this._initialized = false;
    this._requestingUpdate = false;
    this._inDraw = false;
    this.value = {
        drawOptions: {},
        color: null,
        expressions: {},
        geometry: null,
        flatShading: false
    }

    if (options) this.setDrawOptions(options);
    this._id = node.addComponent(this);
}

/**
 * Pass custom options to Mesh, such as a 3 element map
 * which displaces the position of each vertex in world space.
 *
 * @method setDrawOptions
 * @chainable
 *
 * @param {Object} Options
 * @chainable
 */
Mesh.prototype.setDrawOptions = function setOptions (options) {
    if (this.value.drawOptions.blendMode) {
        this.value.drawOptions.blendMode = options.blendMode;
        this._changeQueue.push('GL_SET_DRAW_OPTIONS');
        this._changeQueue.push(options);
    }
    return this;
};

/**
 * Get the mesh's custom options.
 *
 * @method getDrawOptions
 * @returns {Object} Options
 */
Mesh.prototype.getDrawOptions = function getDrawOptions () {
    return this.value.drawOptions;
};

/**
 * Set the geometry of a mesh.
 *
 * @method setGeometry
 * @chainable
 *
 * @param {Geometry} geometry instance to be associated with the mesh
 * @param {Object} Options Various configurations for geometries.
 * @chainable
 */
Mesh.prototype.setGeometry = function setGeometry (geometry, options) {
    if (typeof geometry === 'string') {
        if (!Geometry[geometry]) throw 'Invalid geometry: "' + geometry + '".';
        else geometry = new Geometry[geometry](options);
    }

    if (this.value.geometry !== geometry || this._inDraw) {
        if (this._initialized) {
            this._changeQueue.push('GL_SET_GEOMETRY');
            this._changeQueue.push(geometry.id);
            this._changeQueue.push(geometry.spec.type);
            this._changeQueue.push(geometry.spec.dynamic);
        }
        this._requestUpdate();
        this.value.geometry = geometry;
    }

    return this;
};

/**
 * Get the geometry of a mesh.
 *
 * @method getGeometry
 * @returns {Geometry} geometry Geometry of mesh
 */
Mesh.prototype.getGeometry = function getGeometry () {
    return this.value.geometry;
};

/**
* Changes the color of Mesh, passing either a material expression or
* color using the 'Color' utility component.
*
* @method setBaseColor
* @param {Object|Color} Material, image, vec3, or Color instance
* @chainable
*/
Mesh.prototype.setBaseColor = function setBaseColor (color) {
    var uniformValue;
    if (color._compile) {
        this.value.expressions.baseColor = color;
        uniformValue = color._compile();
    } else if (color.getNormalizedRGB) {
        this.value.expressions.baseColor = null;
        this.value.color = color;
        uniformValue = color.getNormalizedRGB();
    }

    if (this._initialized) {
        // If a material expression
        if (color._compile) {
            this._changeQueue.push('MATERIAL_INPUT');
        }

        // If a color component
        else if (color.getNormalizedRGB) {
            this._changeQueue.push('GL_UNIFORMS');
        }
        console.log(1)
        this._changeQueue.push('baseColor');
        this._changeQueue.push(uniformValue);
    }

    this._requestUpdate();

    return this;
};

/**
 * Returns either the material expression or the color instance of Mesh.
 *
 * @method getBaseColor
 * @returns {MaterialExpress|Color}
 */
Mesh.prototype.getBaseColor = function getBaseColor () {
    return this.value.expressions.baseColor || this.value.color;
};

/**
 * Change whether the Mesh is affected by light. Default is true.
 *
 * @method setFlatShading
 * @param {boolean} Boolean
 * @chainable
 */
Mesh.prototype.setFlatShading = function setFlatShading (bool) {
    if (this._inDraw || this.value.flatShading !== bool) {
        this.value.flatShading = bool;
        if (this._initialized) {
            this._changeQueue.push('GL_UNIFORMS');
            this._changeQueue.push('u_FlatShading');
            this._changeQueue.push(bool ? 1 : 0);
        }
        this._requestUpdate();
    }

    return this;
};

/**
 * Returns a boolean for whether Mesh is affected by light.
 *
 * @method getFlatShading
 * @returns {Boolean} Boolean
 */
Mesh.prototype.getFlatShading = function getFlatShading () {
    return this.value.flatShading;
};

/**
 * Defines a 3-element map which is used to provide significant physical
 * detail to the surface by perturbing the facing direction of each individual
 * pixel.
 *
 * @method normal
 * @chainable
 *
 * @param {Object|Array} Material, Image or vec3
 * @return {Element} current Mesh
 */
Mesh.prototype.setNormals = function setNormals (materialExpression) {
    if (materialExpression._compile) {
        this.value.expressions.normals = materialExpression;
        materialExpression = materialExpression._compile();
    }

    if (this._initialized) {
        this._changeQueue.push(typeof materialExpression === 'number' ? 'UNIFORM_INPUT' : 'MATERIAL_INPUT');
        this._changeQueue.push('normal');
        this._changeQueue.push(materialExpression);
    }

    this._requestUpdate();

    return this;
};

/**
 * Returns the Normals expression of Mesh
 *
 * @method getNormals
 * @returns The normals expression for Mesh
 */
Mesh.prototype.getNormals = function getNormals (materialExpression) {
    return this.value.expressions.normals;
};

/**
 * Defines the glossiness of the mesh from either a material expression or a
 * scalar value
 *
 * @method setGlossiness
 * @param {MaterialExpression|Number}
 * @param {Object} Optional tweening parameter
 * @param {Function} Callback
 * @chainable
 */
Mesh.prototype.setGlossiness = function setGlossiness (materialExpression, transition, cb) {
    var glossiness;

    if (materialExpression._compile) {
        this.value.expressions.glossiness = materialExpression;
        glossiness = materialExpression._compile();
    }
    else {
        this.value.expressions.glossiness = null;
        this.value.glossiness = materialExpression;
        glossiness = this.value.glossiness;
    }

    if (this._initialized) {
        this._changeQueue.push(materialExpression._compile ? 'GL_UNIFORMS' : 'MATERIAL_INPUT');
        this._changeQueue.push('glossiness');
        this._changeQueue.push(glossiness);
    }

    this._requestUpdate();

    return this;
};

/**
 * Returns material expression or scalar value for glossiness.
 *
 * @method getGlossiness
 * @returns {MaterialExpress|Number}
 */
Mesh.prototype.getGlossiness = function getGlossiness () {
    return this.value.expressions.glossiness || this.value.glossiness;
};

/**
 * Defines 3 element map which displaces the position of each vertex in world
 * space.
 *
 * @method setPositionOffset
 * @chainable
 *
 * @param {MaterialExpression|Array}
 * @param {Object} Optional tweening parameter
 * @param {Function} Callback
 * @chainable
 */
Mesh.prototype.setPositionOffset = function positionOffset (materialExpression, transition, cb) {
    var uniformValue;

    if (materialExpression._compile) {
        this.value.expressions.positionOffset = materialExpression;
        uniformValue = materialExpression._compile();
    }
    else {
        this.value.expressions.positionOffset = null;
        this.value.positionOffset = materialExpression;
        uniformValue = this.value.positionOffset;
    }

    if (this._initialized) {
        this._changeQueue.push(materialExpression._compile ? 'MATERIAL_INPUT' : 'GL_UNIFORMS');
        this._changeQueue.push('positionOffset');
        this._changeQueue.push(uniformValue);
    }

    this._requestUpdate();

    return this;
};

/**
 * Returns position offset.
 *
 * @method getPositionOffset
 * @returns {MaterialExpress|Number}
 */
Mesh.prototype.getPositionOffset = function getPositionOffset (materialExpression) {
    return this.value.expressions.positionOffset || this.value.positionOffset;
};

/**
 * Get the mesh's custom options.
 *
 * @method getDrawOptions
 * @returns {Object} Options
 */
Mesh.prototype.getMaterialExpressions = function getMaterialExpressions () {
    return this.value.expressions;
};

Mesh.prototype.getValue = function getValue () {
    return this.value;
};

Mesh.prototype._pushInvalidations = function pushInvalidations (expressionName) {
    var uniformKey;
    var expression = this.value.expressions[expressionName];
    if (expression) {
        var i = expression.invalidations.length;
        while (i--) {
            uniformKey = expression.invalidations.pop();
            this._node.sendDrawCommand('GL_UNIFORMS');
            this._node.sendDrawCommand(uniformKey);
            this._node.sendDrawCommand(expression.uniforms[uniformKey]);
        }
    }
};

/**
* Sends draw commands to the renderer
*
* @private
* @method onUpdate
*/
Mesh.prototype.onUpdate = function onUpdate () {
    var node = this._node;
    var queue = this._changeQueue;

    if (node) {
        node.sendDrawCommand('WITH');
        node.sendDrawCommand(node.getLocation());

        if (this.value.geometry) {
        i = this.value.geometry.spec.invalidations.length;
            while (i--) {
                var bufferIndex = this.value.geometry.spec.invalidations.pop();
                node.sendDrawCommand('GL_BUFFER_DATA');
                node.sendDrawCommand(this.value.geometry.id);
                node.sendDrawCommand(this.value.geometry.spec.bufferNames[i]);
                node.sendDrawCommand(this.value.geometry.spec.bufferValues[i]);
                node.sendDrawCommand(this.value.geometry.spec.bufferSpacings[i]);
            }
        }

        // If any invalidations exist, push them into the queue
        if (this.value.color && this.value.color.isActive()) {
            this._node.sendDrawCommand('GL_UNIFORMS');
            this._node.sendDrawCommand('baseColor');
            this._node.sendDrawCommand(this.value.color.getNormalizedRGB());
            this._node.requestUpdateOnNextTick(this._id);
        } else {
            this._requestingUpdate = false;
        }

        // If any invalidations exist, push them into the queue
        this._pushInvalidations('baseColor');
        this._pushInvalidations('positionOffset');

        for (var i = 0; i < queue.length; i++) {
            node.sendDrawCommand(queue[i]);
        }

        queue.length = 0;
    }

};

Mesh.prototype.onMount = function onMount (node, id) {
    this._node = node;
    this._id = id;

    this.draw();
};

Mesh.prototype.onDismount = function onDismount () {
    this._initialized = false;
    this.onHide();
};

Mesh.prototype.onShow = function onShow () {
    //TODO
};

Mesh.prototype.onHide = function onHide () {
    //TODO
};

/**
 * Receives transform change updates from the scene graph.
 *
 * @private
 */
Mesh.prototype.onTransformChange = function onTransformChange (transform) {
    if (this._initialized) {
        this._changeQueue.push('GL_UNIFORMS');
        this._changeQueue.push('transform');
        this._changeQueue.push(transform);
    }

    this._requestUpdate();
};

/**
 * Receives size change updates from the scene graph.
 *
 * @private
 */
Mesh.prototype.onSizeChange = function onSizeChange (size) {
    if (this._initialized) {
        this._changeQueue.push('GL_UNIFORMS');
        this._changeQueue.push('size');
        this._changeQueue.push(size);
    }

    this._requestUpdate();
};

/**
 * Receives opacity change updates from the scene graph.
 *
 * @private
 */
Mesh.prototype.onOpacityChange = function onOpacityChange (opacity) {
    if (this._initialized) {
        this._changeQueue.push('GL_UNIFORMS');
        this._changeQueue.push('opacity');
        this._changeQueue.push(opacity);
    }

    this._requestUpdate();
};

Mesh.prototype.onAddUIEvent = function onAddUIEvent (UIEvent, methods, properties) {
    //TODO
};

Mesh.prototype._requestUpdate = function _requestUpdate () {
    if (!this._requestingUpdate) {
        this._node.requestUpdate(this._id);
        this._requestingUpdate = true;
    }
};

Mesh.prototype.init = function init () {
    this._initialized = true;
    this.onTransformChange(this._node.getTransform());
    this.onSizeChange(this._node.getSize());
    this.onOpacityChange(this._node.getOpacity());
    this._requestUpdate();
};

Mesh.prototype.draw = function draw () {
    var key;
    var i;
    var len;

    this._inDraw = true;

    this.init();

    var value = this.getValue();
    if (value.geometry != null) this.setGeometry(value.geometry);
    if (value.color != null) this.setBaseColor(value.color);
    if (value.drawOptions != null) this.setDrawOptions(value.drawOptions);
    if (value.flatShading != null) this.setFlatShading(value.flatShading);
    if (value.expressions.normals != null) this.setNormals(value.expressions.normals);
    if (value.expressions.baseColor != null) this.setBaseColor(value.expressions.baseColor);
    if (value.expressions.glossiness != null) this.setGlossiness(value.expressions.glossiness);
    if (value.expressions.positionOffset != null) this.setPositionOffset(value.expressions.positionOffset);

    this._inDraw = false;
};

module.exports = Mesh;
<commit_msg>fix: remove log<commit_after>'use strict';
var Geometry = require('famous-webgl-geometries');

/**
 * The Mesh class is responsible for providing the API for how
 * a RenderNode will interact with the WebGL API by adding
 * a set of commands to the renderer.
 *
 * @class Mesh
 * @constructor
 * @renderable
 * @param {LocalDispatch} dispatch LocalDispatch to be retrieved
 * @param {object} Options Optional params for configuring Mesh
 */
function Mesh (node, options) {
    this._node = node;
    this._changeQueue = [];
    this._initialized = false;
    this._requestingUpdate = false;
    this._inDraw = false;
    this.value = {
        drawOptions: {},
        color: null,
        expressions: {},
        geometry: null,
        flatShading: false
    }

    if (options) this.setDrawOptions(options);
    this._id = node.addComponent(this);
}

/**
 * Pass custom options to Mesh, such as a 3 element map
 * which displaces the position of each vertex in world space.
 *
 * @method setDrawOptions
 * @chainable
 *
 * @param {Object} Options
 * @chainable
 */
Mesh.prototype.setDrawOptions = function setOptions (options) {
    if (this.value.drawOptions.blendMode) {
        this.value.drawOptions.blendMode = options.blendMode;
        this._changeQueue.push('GL_SET_DRAW_OPTIONS');
        this._changeQueue.push(options);
    }
    return this;
};

/**
 * Get the mesh's custom options.
 *
 * @method getDrawOptions
 * @returns {Object} Options
 */
Mesh.prototype.getDrawOptions = function getDrawOptions () {
    return this.value.drawOptions;
};

/**
 * Set the geometry of a mesh.
 *
 * @method setGeometry
 * @chainable
 *
 * @param {Geometry} geometry instance to be associated with the mesh
 * @param {Object} Options Various configurations for geometries.
 * @chainable
 */
Mesh.prototype.setGeometry = function setGeometry (geometry, options) {
    if (typeof geometry === 'string') {
        if (!Geometry[geometry]) throw 'Invalid geometry: "' + geometry + '".';
        else geometry = new Geometry[geometry](options);
    }

    if (this.value.geometry !== geometry || this._inDraw) {
        if (this._initialized) {
            this._changeQueue.push('GL_SET_GEOMETRY');
            this._changeQueue.push(geometry.id);
            this._changeQueue.push(geometry.spec.type);
            this._changeQueue.push(geometry.spec.dynamic);
        }
        this._requestUpdate();
        this.value.geometry = geometry;
    }

    return this;
};

/**
 * Get the geometry of a mesh.
 *
 * @method getGeometry
 * @returns {Geometry} geometry Geometry of mesh
 */
Mesh.prototype.getGeometry = function getGeometry () {
    return this.value.geometry;
};

/**
* Changes the color of Mesh, passing either a material expression or
* color using the 'Color' utility component.
*
* @method setBaseColor
* @param {Object|Color} Material, image, vec3, or Color instance
* @chainable
*/
Mesh.prototype.setBaseColor = function setBaseColor (color) {
    var uniformValue;
    if (color._compile) {
        this.value.expressions.baseColor = color;
        uniformValue = color._compile();
    } else if (color.getNormalizedRGB) {
        this.value.expressions.baseColor = null;
        this.value.color = color;
        uniformValue = color.getNormalizedRGB();
    }

    if (this._initialized) {
        // If a material expression
        if (color._compile) {
            this._changeQueue.push('MATERIAL_INPUT');
        }

        // If a color component
        else if (color.getNormalizedRGB) {
            this._changeQueue.push('GL_UNIFORMS');
        }
        this._changeQueue.push('baseColor');
        this._changeQueue.push(uniformValue);
    }

    this._requestUpdate();

    return this;
};

/**
 * Returns either the material expression or the color instance of Mesh.
 *
 * @method getBaseColor
 * @returns {MaterialExpress|Color}
 */
Mesh.prototype.getBaseColor = function getBaseColor () {
    return this.value.expressions.baseColor || this.value.color;
};

/**
 * Change whether the Mesh is affected by light. Default is true.
 *
 * @method setFlatShading
 * @param {boolean} Boolean
 * @chainable
 */
Mesh.prototype.setFlatShading = function setFlatShading (bool) {
    if (this._inDraw || this.value.flatShading !== bool) {
        this.value.flatShading = bool;
        if (this._initialized) {
            this._changeQueue.push('GL_UNIFORMS');
            this._changeQueue.push('u_FlatShading');
            this._changeQueue.push(bool ? 1 : 0);
        }
        this._requestUpdate();
    }

    return this;
};

/**
 * Returns a boolean for whether Mesh is affected by light.
 *
 * @method getFlatShading
 * @returns {Boolean} Boolean
 */
Mesh.prototype.getFlatShading = function getFlatShading () {
    return this.value.flatShading;
};

/**
 * Defines a 3-element map which is used to provide significant physical
 * detail to the surface by perturbing the facing direction of each individual
 * pixel.
 *
 * @method normal
 * @chainable
 *
 * @param {Object|Array} Material, Image or vec3
 * @return {Element} current Mesh
 */
Mesh.prototype.setNormals = function setNormals (materialExpression) {
    if (materialExpression._compile) {
        this.value.expressions.normals = materialExpression;
        materialExpression = materialExpression._compile();
    }

    if (this._initialized) {
        this._changeQueue.push(typeof materialExpression === 'number' ? 'UNIFORM_INPUT' : 'MATERIAL_INPUT');
        this._changeQueue.push('normal');
        this._changeQueue.push(materialExpression);
    }

    this._requestUpdate();

    return this;
};

/**
 * Returns the Normals expression of Mesh
 *
 * @method getNormals
 * @returns The normals expression for Mesh
 */
Mesh.prototype.getNormals = function getNormals (materialExpression) {
    return this.value.expressions.normals;
};

/**
 * Defines the glossiness of the mesh from either a material expression or a
 * scalar value
 *
 * @method setGlossiness
 * @param {MaterialExpression|Number}
 * @param {Object} Optional tweening parameter
 * @param {Function} Callback
 * @chainable
 */
Mesh.prototype.setGlossiness = function setGlossiness (materialExpression, transition, cb) {
    var glossiness;

    if (materialExpression._compile) {
        this.value.expressions.glossiness = materialExpression;
        glossiness = materialExpression._compile();
    }
    else {
        this.value.expressions.glossiness = null;
        this.value.glossiness = materialExpression;
        glossiness = this.value.glossiness;
    }

    if (this._initialized) {
        this._changeQueue.push(materialExpression._compile ? 'GL_UNIFORMS' : 'MATERIAL_INPUT');
        this._changeQueue.push('glossiness');
        this._changeQueue.push(glossiness);
    }

    this._requestUpdate();

    return this;
};

/**
 * Returns material expression or scalar value for glossiness.
 *
 * @method getGlossiness
 * @returns {MaterialExpress|Number}
 */
Mesh.prototype.getGlossiness = function getGlossiness () {
    return this.value.expressions.glossiness || this.value.glossiness;
};

/**
 * Defines 3 element map which displaces the position of each vertex in world
 * space.
 *
 * @method setPositionOffset
 * @chainable
 *
 * @param {MaterialExpression|Array}
 * @param {Object} Optional tweening parameter
 * @param {Function} Callback
 * @chainable
 */
Mesh.prototype.setPositionOffset = function positionOffset (materialExpression, transition, cb) {
    var uniformValue;

    if (materialExpression._compile) {
        this.value.expressions.positionOffset = materialExpression;
        uniformValue = materialExpression._compile();
    }
    else {
        this.value.expressions.positionOffset = null;
        this.value.positionOffset = materialExpression;
        uniformValue = this.value.positionOffset;
    }

    if (this._initialized) {
        this._changeQueue.push(materialExpression._compile ? 'MATERIAL_INPUT' : 'GL_UNIFORMS');
        this._changeQueue.push('positionOffset');
        this._changeQueue.push(uniformValue);
    }

    this._requestUpdate();

    return this;
};

/**
 * Returns position offset.
 *
 * @method getPositionOffset
 * @returns {MaterialExpress|Number}
 */
Mesh.prototype.getPositionOffset = function getPositionOffset (materialExpression) {
    return this.value.expressions.positionOffset || this.value.positionOffset;
};

/**
 * Get the mesh's custom options.
 *
 * @method getDrawOptions
 * @returns {Object} Options
 */
Mesh.prototype.getMaterialExpressions = function getMaterialExpressions () {
    return this.value.expressions;
};

Mesh.prototype.getValue = function getValue () {
    return this.value;
};

Mesh.prototype._pushInvalidations = function pushInvalidations (expressionName) {
    var uniformKey;
    var expression = this.value.expressions[expressionName];
    if (expression) {
        var i = expression.invalidations.length;
        while (i--) {
            uniformKey = expression.invalidations.pop();
            this._node.sendDrawCommand('GL_UNIFORMS');
            this._node.sendDrawCommand(uniformKey);
            this._node.sendDrawCommand(expression.uniforms[uniformKey]);
        }
    }
};

/**
* Sends draw commands to the renderer
*
* @private
* @method onUpdate
*/
Mesh.prototype.onUpdate = function onUpdate () {
    var node = this._node;
    var queue = this._changeQueue;

    if (node) {
        node.sendDrawCommand('WITH');
        node.sendDrawCommand(node.getLocation());

        if (this.value.geometry) {
        i = this.value.geometry.spec.invalidations.length;
            while (i--) {
                var bufferIndex = this.value.geometry.spec.invalidations.pop();
                node.sendDrawCommand('GL_BUFFER_DATA');
                node.sendDrawCommand(this.value.geometry.id);
                node.sendDrawCommand(this.value.geometry.spec.bufferNames[i]);
                node.sendDrawCommand(this.value.geometry.spec.bufferValues[i]);
                node.sendDrawCommand(this.value.geometry.spec.bufferSpacings[i]);
            }
        }

        // If any invalidations exist, push them into the queue
        if (this.value.color && this.value.color.isActive()) {
            this._node.sendDrawCommand('GL_UNIFORMS');
            this._node.sendDrawCommand('baseColor');
            this._node.sendDrawCommand(this.value.color.getNormalizedRGB());
            this._node.requestUpdateOnNextTick(this._id);
        } else {
            this._requestingUpdate = false;
        }

        // If any invalidations exist, push them into the queue
        this._pushInvalidations('baseColor');
        this._pushInvalidations('positionOffset');

        for (var i = 0; i < queue.length; i++) {
            node.sendDrawCommand(queue[i]);
        }

        queue.length = 0;
    }

};

Mesh.prototype.onMount = function onMount (node, id) {
    this._node = node;
    this._id = id;

    this.draw();
};

Mesh.prototype.onDismount = function onDismount () {
    this._initialized = false;
    this.onHide();
};

Mesh.prototype.onShow = function onShow () {
    this._changeQueue.push('GL_HIDE_MESH');
};

Mesh.prototype.onHide = function onHide () {
    this._changeQueue.push('GL_HIDE_MESH');
};

/**
 * Receives transform change updates from the scene graph.
 *
 * @private
 */
Mesh.prototype.onTransformChange = function onTransformChange (transform) {
    if (this._initialized) {
        this._changeQueue.push('GL_UNIFORMS');
        this._changeQueue.push('transform');
        this._changeQueue.push(transform);
    }

    this._requestUpdate();
};

/**
 * Receives size change updates from the scene graph.
 *
 * @private
 */
Mesh.prototype.onSizeChange = function onSizeChange (size) {
    if (this._initialized) {
        this._changeQueue.push('GL_UNIFORMS');
        this._changeQueue.push('size');
        this._changeQueue.push(size);
    }

    this._requestUpdate();
};

/**
 * Receives opacity change updates from the scene graph.
 *
 * @private
 */
Mesh.prototype.onOpacityChange = function onOpacityChange (opacity) {
    if (this._initialized) {
        this._changeQueue.push('GL_UNIFORMS');
        this._changeQueue.push('opacity');
        this._changeQueue.push(opacity);
    }

    this._requestUpdate();
};

Mesh.prototype.onAddUIEvent = function onAddUIEvent (UIEvent, methods, properties) {
    //TODO
};

Mesh.prototype._requestUpdate = function _requestUpdate () {
    if (!this._requestingUpdate) {
        this._node.requestUpdate(this._id);
        this._requestingUpdate = true;
    }
};

Mesh.prototype.init = function init () {
    this._initialized = true;
    this.onTransformChange(this._node.getTransform());
    this.onSizeChange(this._node.getSize());
    this.onOpacityChange(this._node.getOpacity());
    this._requestUpdate();
};

Mesh.prototype.draw = function draw () {
    var key;
    var i;
    var len;

    this._inDraw = true;

    this.init();

    var value = this.getValue();
    if (value.geometry != null) this.setGeometry(value.geometry);
    if (value.color != null) this.setBaseColor(value.color);
    if (value.drawOptions != null) this.setDrawOptions(value.drawOptions);
    if (value.flatShading != null) this.setFlatShading(value.flatShading);
    if (value.expressions.normals != null) this.setNormals(value.expressions.normals);
    if (value.expressions.baseColor != null) this.setBaseColor(value.expressions.baseColor);
    if (value.expressions.glossiness != null) this.setGlossiness(value.expressions.glossiness);
    if (value.expressions.positionOffset != null) this.setPositionOffset(value.expressions.positionOffset);

    this._inDraw = false;
};

module.exports = Mesh;
<|endoftext|>


<commit_before>import { Page } from '../src/page';

function setCurrentScope(scope) {
  document.body.dataset.page = scope;
}

QUnit.module('Page', {
  beforeEach: function() {
    this.page = new Page();
  }
});

QUnit.test('runs the initializer block for the given scope', function(assert) {
  this.page.at('a-scope', () => assert.ok(true));

  setCurrentScope('a-scope');
  this.page.dispatch();
});

QUnit.test('sends the current scope as an argument', function(assert) {
  this.page.at('the-scope', (scope) => assert.equal('the-scope', scope));

  setCurrentScope('the-scope');
  this.page.dispatch();
});

QUnit.test('always run the before and after block', function(assert) {
  this.page.at(':before', () => assert.ok(true));
  this.page.at(':after', () => assert.ok(true));

  setCurrentScope('scope-without-blocks');
  this.page.dispatch();
});

QUnit.test('runs multiple blocks for the given scope', function(assert) {
  this.page.at('multiple', () => assert.ok(true));
  this.page.at('multiple', () => assert.ok(true));

  setCurrentScope('multiple');
  this.page.dispatch();
  expect(2);
});

QUnit.test('runs blocks that does not have variants and the ones with specific variants', function(assert) {
  this.page.at('a-scope', () => assert.ok(true));
  this.page.at('a-scope+variant', () => assert.ok(true));
  this.page.at('a-scope+another-variant', () => assert.ok(false));

  setCurrentScope('a-scope+variant');
  this.page.dispatch();
});

QUnit.test('runs blocks with the exact multiple variants', function(assert) {
  this.page.at('a-scope+one+two', () => assert.ok(true));
  this.page.at('a-scope+two+one', () => assert.ok(true));
  this.page.at('a-scope+one+two+three', () => assert.ok(false));

  setCurrentScope('a-scope+one+two');
  this.page.dispatch();
});

QUnit.test('halts the chain if a block returns false', function(assert) {
  this.page.at('halting', () => false);
  this.page.at('halting', () => assert.ok(false));

  setCurrentScope('halting');
  this.page.dispatch();

  expect(0);
});

QUnit.test("runs the chain on the following order: 'before', initializers, and 'after'", function(assert) {
  var sequence = [];
  this.page.at('chain',   () => sequence.push('initializer'));
  this.page.at(':before', () => sequence.push(':before'));
  this.page.at(':after', () => sequence.push(':after'));

  this.page.at(':after',  () => assert.deepEqual(sequence, [':before', 'initializer', ':after']));

  setCurrentScope('chain');
  this.page.dispatch();
});

QUnit.test('stores the same block for more than one scope', function(assert) {
  this.page.at('one two', () => assert.ok(true));
  setCurrentScope('one');
  this.page.dispatch();

  setCurrentScope('two');
  this.page.dispatch();

  expect(2);
});
<commit_msg>QUnit equality checks are "actual, expected" and not "expected, actual".<commit_after>import { Page } from '../src/page';

function setCurrentScope(scope) {
  document.body.dataset.page = scope;
}

QUnit.module('Page', {
  beforeEach: function() {
    this.page = new Page();
  }
});

QUnit.test('runs the initializer block for the given scope', function(assert) {
  this.page.at('a-scope', () => assert.ok(true));

  setCurrentScope('a-scope');
  this.page.dispatch();
});

QUnit.test('sends the current scope as an argument', function(assert) {
  this.page.at('the-scope', (scope) => assert.equal(scope, 'the-scope'));

  setCurrentScope('the-scope');
  this.page.dispatch();
});

QUnit.test('always run the before and after block', function(assert) {
  this.page.at(':before', () => assert.ok(true));
  this.page.at(':after', () => assert.ok(true));

  setCurrentScope('scope-without-blocks');
  this.page.dispatch();
});

QUnit.test('runs multiple blocks for the given scope', function(assert) {
  this.page.at('multiple', () => assert.ok(true));
  this.page.at('multiple', () => assert.ok(true));

  setCurrentScope('multiple');
  this.page.dispatch();
  expect(2);
});

QUnit.test('runs blocks that does not have variants and the ones with specific variants', function(assert) {
  this.page.at('a-scope', () => assert.ok(true));
  this.page.at('a-scope+variant', () => assert.ok(true));
  this.page.at('a-scope+another-variant', () => assert.ok(false));

  setCurrentScope('a-scope+variant');
  this.page.dispatch();
});

QUnit.test('runs blocks with the exact multiple variants', function(assert) {
  this.page.at('a-scope+one+two', () => assert.ok(true));
  this.page.at('a-scope+two+one', () => assert.ok(true));
  this.page.at('a-scope+one+two+three', () => assert.ok(false));

  setCurrentScope('a-scope+one+two');
  this.page.dispatch();
});

QUnit.test('halts the chain if a block returns false', function(assert) {
  this.page.at('halting', () => false);
  this.page.at('halting', () => assert.ok(false));

  setCurrentScope('halting');
  this.page.dispatch();

  expect(0);
});

QUnit.test("runs the chain on the following order: 'before', initializers, and 'after'", function(assert) {
  var sequence = [];
  this.page.at('chain',   () => sequence.push('initializer'));
  this.page.at(':before', () => sequence.push(':before'));
  this.page.at(':after', () => sequence.push(':after'));

  this.page.at(':after',  () => assert.deepEqual([':before', 'initializer', ':after'], sequence));

  setCurrentScope('chain');
  this.page.dispatch();
});

QUnit.test('stores the same block for more than one scope', function(assert) {
  this.page.at('one two', () => assert.ok(true));
  setCurrentScope('one');
  this.page.dispatch();

  setCurrentScope('two');
  this.page.dispatch();

  expect(2);
});
<|endoftext|>


<commit_before>/*
 * Convert jpg to svg to gcode.
 *
 * d3000 - hello@3000d.be
 */

var path = require('path'),
  fs = require('fs'),
  root = require('../root'),
  exec = require('child_process').exec,
  osc = new (require(root.communication + '/osc')),
  util = require('util'),

  Communication = require(root.communication + '/communication'),
  GcodeConverter = require(root.process + '/GcodeConverter'),
  Watcher = require(root.common + '/Watcher');
  WebServer = require(root.web + '/web');

var drawbot = new Communication();
var gcodeConverter = new GcodeConverter({feedrate: 6});
var webServer = new WebServer(drawbot);
webServer.startServer();

var gcodeFiles = [];
var processedGcodeFiles = [];
var currentGcodeFile;

var isProcessStarted = false;

var bmpWatcher = new Watcher({
  folder: path.resolve(root.data_bmp),
  extensions: ['bmp', 'BMP']
});

var jsonWatcher = new Watcher({
  folder: path.resolve(root.data_json),
  extensions: ['json']
});

drawbot.getSerialPortList(function(ports) {
  try {
    drawbot.connect(process.argv[2] || ports[0].comName);
  } catch(e) {}

  drawbot.on('connected', function() {
  });

  //processGcodeFile();

  bmpWatcher.on('fileAdded', function(evt) {
    var fileName = evt.path.split('/');
    fileName = fileName[fileName.length-1].split('.');
    fileName = fileName[fileName.length-2];
    var jsonFileName = fileName + '.json';

    // potrace -i -b geojson -k 0.4 -t 60 -o outputXXX.json bitmapXXX.BMP
    var cmd = 'potrace -i -b geojson -k 0.4 -t 60 -o ' + (root.data_json + '/' + jsonFileName) + ' ' + evt.path;

    exec(cmd, function(error, stdout, stderr) {
      if(error && error !== 'null') {
        drawbot.Log.error(error);
        return;
      }
      if(stderr) {
        drawbot.Log.error(error);
        return;
      }
      //drawbot.log('-- Json file created: ' + jsonFileName);
    });
  });

  jsonWatcher.on('fileAdded', function(evt) {
    try {
      var json = require(evt.path);
      var gcode = gcodeConverter.convert(json);

      var fileName = evt.path.split('/');
      fileName = fileName[fileName.length-1].split('.');
      fileName = fileName[fileName.length-2];
      var gcodeFileName = fileName + '.gcode';

      fs.writeFile(root.data_gcode + '/' + gcodeFileName, gcode, function(err) {
        if(err) {
          drawbot.Log.error('Could not save to gcode');
        } else {
          drawbot.Log.('-- GCode: ' + gcodeFileName);
          gcodeFiles.push(gcodeFileName);

          if(!isProcessStarted) {
            processGcodeFile();
            isProcessStarted = true;
          }
        }
      });
    } catch(e) {
      drawbot.Log.error('could not convert json to gcode');
    }
  });

  drawbot.on('drawStarted', function() {
    drawbot.log('-- DRAW STARTED');
    osc.sendSOD();
  });

  drawbot.on('drawFinished', function() {
    drawbot.log('-- DRAW FINISHED');
    osc.sendEOD();
    processGcodeFile(true);
  });
});

var processGcodeFile = function(removeLast) {
  if(removeLast && currentGcodeFile) {
    for(var i = 0; i < gcodeFiles.length; i++) {
      if(gcodeFiles[i] === currentGcodeFile) {
        gcodeFiles.splice(i, 1);
      }
    }
    moveGcodeFile(currentGcodeFile);
  }
  var gcode, gcodeFile;
  if(gcodeFiles.length) {
    gcodeFile = gcodeFiles[gcodeFiles.length - 1];
    currentGcodeFile = gcodeFile;

    gcode = fs.readFileSync(root.data_gcode + '/' + gcodeFile, 'utf8');
    if(gcode) drawbot.Log.debug('[PROCESS] DRAW NEW : ' + gcodeFile);
  } else {
    var randIndex = Math.floor(Math.random() * processedGcodeFiles.length);
    gcodeFile = processedGcodeFiles[randIndex];
    gcode = fs.readFileSync(root.data_gcode_processed + '/' + processedGcodeFiles[randIndex]);
    currentGcodeFile = null;
    if(gcode) drawbot.Log.debug('[PROCESS] DRAW OLD : ' + gcodeFile);
  }

  if(gcode) {
    // start debug code
    //drawbot.isDrawing = true;
    //drawbot.emit('drawStarted');
    //setTimeout(function() {
    //  drawbot.isDrawing = false;
    //  drawbot.emit('drawFinished');
    //}, 5000);
    // end debug code

    drawbot.batch(gcode);
  }
};

//var getGcodeFile = function() {
//  if(!gcodeFiles.length) {
//    var gcodesInFolder = fs.readdirSync(root.data_gcode);
//    for(var i = 0; i < gcodesInFolder.length; i++) {
//      var fileName = gcodesInFolder[i].split('.');
//
//      if(fileName[fileName.length-1] === 'gcode') {
//        gcodeFiles.push(gcodesInFolder[i]);
//      }
//    }
//  }
//
//  if(gcodeFiles.length) {
//    return gcodeFiles[gcodeFiles.length - 1];
//  } else {
//    return null;
//  }
//};

var moveGcodeFile = function(gcodeFileName) {
  fs.renameSync(root.data_gcode + '/' + gcodeFileName, root.data_gcode_processed + '/' + gcodeFileName);
  processedGcodeFiles.push(gcodeFileName);
};<commit_msg>bugfix process<commit_after>/*
 * Convert jpg to svg to gcode.
 *
 * d3000 - hello@3000d.be
 */

var path = require('path'),
  fs = require('fs'),
  root = require('../root'),
  exec = require('child_process').exec,
  osc = new (require(root.communication + '/osc')),
  util = require('util'),

  Communication = require(root.communication + '/communication'),
  GcodeConverter = require(root.process + '/GcodeConverter'),
  Watcher = require(root.common + '/Watcher');
  WebServer = require(root.web + '/web');

var drawbot = new Communication();
var gcodeConverter = new GcodeConverter({feedrate: 6});
var webServer = new WebServer(drawbot);
webServer.startServer();

var gcodeFiles = [];
var processedGcodeFiles = [];
var currentGcodeFile;

var isProcessStarted = false;

var bmpWatcher = new Watcher({
  folder: path.resolve(root.data_bmp),
  extensions: ['bmp', 'BMP']
});

var jsonWatcher = new Watcher({
  folder: path.resolve(root.data_json),
  extensions: ['json']
});

drawbot.getSerialPortList(function(ports) {
  try {
    drawbot.connect(process.argv[2] || ports[0].comName);
  } catch(e) {}

  drawbot.on('connected', function() {
  });

  //processGcodeFile();

  bmpWatcher.on('fileAdded', function(evt) {
    var fileName = evt.path.split('/');
    fileName = fileName[fileName.length-1].split('.');
    fileName = fileName[fileName.length-2];
    var jsonFileName = fileName + '.json';

    // potrace -i -b geojson -k 0.4 -t 60 -o outputXXX.json bitmapXXX.BMP
    var cmd = 'potrace -i -b geojson -k 0.4 -t 60 -o ' + (root.data_json + '/' + jsonFileName) + ' ' + evt.path;

    exec(cmd, function(error, stdout, stderr) {
      if(error && error !== 'null') {
        drawbot.Log.error(error);
        return;
      }
      if(stderr) {
        drawbot.Log.error(error);
        return;
      }
      //drawbot.log('-- Json file created: ' + jsonFileName);
    });
  });

  jsonWatcher.on('fileAdded', function(evt) {
    try {
      var json = require(evt.path);
      var gcode = gcodeConverter.convert(json);

      var fileName = evt.path.split('/');
      fileName = fileName[fileName.length-1].split('.');
      fileName = fileName[fileName.length-2];
      var gcodeFileName = fileName + '.gcode';

      fs.writeFile(root.data_gcode + '/' + gcodeFileName, gcode, function(err) {
        if(err) {
          drawbot.Log.error('Could not save to gcode');
        } else {
          drawbot.Log.debug('-- GCode: ' + gcodeFileName);
          gcodeFiles.push(gcodeFileName);

          if(!isProcessStarted) {
            processGcodeFile();
            isProcessStarted = true;
          }
        }
      });
    } catch(e) {
      drawbot.Log.error('could not convert json to gcode');
    }
  });

  drawbot.on('drawStarted', function() {
    drawbot.log('-- DRAW STARTED');
    osc.sendSOD();
  });

  drawbot.on('drawFinished', function() {
    drawbot.log('-- DRAW FINISHED');
    osc.sendEOD();
    processGcodeFile(true);
  });
});

var processGcodeFile = function(removeLast) {
  if(removeLast && currentGcodeFile) {
    for(var i = 0; i < gcodeFiles.length; i++) {
      if(gcodeFiles[i] === currentGcodeFile) {
        gcodeFiles.splice(i, 1);
      }
    }
    moveGcodeFile(currentGcodeFile);
  }
  var gcode, gcodeFile;
  if(gcodeFiles.length) {
    gcodeFile = gcodeFiles[gcodeFiles.length - 1];
    currentGcodeFile = gcodeFile;

    gcode = fs.readFileSync(root.data_gcode + '/' + gcodeFile, 'utf8');
    if(gcode) drawbot.Log.debug('[PROCESS] DRAW NEW : ' + gcodeFile);
  } else {
    var randIndex = Math.floor(Math.random() * processedGcodeFiles.length);
    gcodeFile = processedGcodeFiles[randIndex];
    gcode = fs.readFileSync(root.data_gcode_processed + '/' + processedGcodeFiles[randIndex]);
    currentGcodeFile = null;
    if(gcode) drawbot.Log.debug('[PROCESS] DRAW OLD : ' + gcodeFile);
  }

  if(gcode) {
    // start debug code
    //drawbot.isDrawing = true;
    //drawbot.emit('drawStarted');
    //setTimeout(function() {
    //  drawbot.isDrawing = false;
    //  drawbot.emit('drawFinished');
    //}, 5000);
    // end debug code

    drawbot.batch(gcode);
  }
};

//var getGcodeFile = function() {
//  if(!gcodeFiles.length) {
//    var gcodesInFolder = fs.readdirSync(root.data_gcode);
//    for(var i = 0; i < gcodesInFolder.length; i++) {
//      var fileName = gcodesInFolder[i].split('.');
//
//      if(fileName[fileName.length-1] === 'gcode') {
//        gcodeFiles.push(gcodesInFolder[i]);
//      }
//    }
//  }
//
//  if(gcodeFiles.length) {
//    return gcodeFiles[gcodeFiles.length - 1];
//  } else {
//    return null;
//  }
//};

var moveGcodeFile = function(gcodeFileName) {
  fs.renameSync(root.data_gcode + '/' + gcodeFileName, root.data_gcode_processed + '/' + gcodeFileName);
  processedGcodeFiles.push(gcodeFileName);
};<|endoftext|>


<commit_before>import babel from '@rollup/plugin-babel';
import replace from '@rollup/plugin-replace';
import bundleSize from '@atomico/rollup-plugin-sizes';
import { terser } from 'rollup-plugin-terser';
import visualizer from 'rollup-plugin-visualizer';
import license from 'rollup-plugin-license';
import flowEntry from 'rollup-plugin-flow-entry';
import compiler from '@ampproject/rollup-plugin-closure-compiler';
import pkg from '../package.json';

const getFileName = (input) => input.split('/')[1].split('.')[0];

const inputs = ['src/popper.js', 'src/popper-lite.js', 'src/popper-base.js'];
const bundles = [
  { inputs, format: 'umd', dir: 'dist', minify: true, flow: true },
  { inputs, format: 'umd', dir: 'dist' },
  { inputs, format: 'cjs', dir: 'dist', flow: true },
];

const configs = bundles
  .map(({ inputs, dir, format, minify, flow }) =>
    inputs.map((input) => ({
      input,
      plugins: [
        format === 'umd' &&
          replace({
            __DEV__: minify ? 'false' : 'true',
          }),
        babel({ babelHelpers: 'bundled' }),
        // The two minifiers together seem to procude a smaller bundle 🤷♂
        minify && compiler(),
        minify && terser(),
        license({ banner: `@popperjs/core v${pkg.version} - MIT License` }),
        flow && flowEntry({ types: `lib/${getFileName(input)}.js` }),
        bundleSize(),
        visualizer({
          sourcemap: true,
          filename: `stats/${getFileName(input)}${minify ? '-min' : ''}.html`,
        }),
      ].filter(Boolean),
      output: {
        name: 'Popper',
        file: `${dir}/${format}/${getFileName(input)}${
          minify ? '.min' : ''
        }.js`,
        format,
        sourcemap: true,
      },
    }))
  )
  .flat();

export default configs;
<commit_msg>feat: expose enums.js from UMD and CJS builds<commit_after>import babel from '@rollup/plugin-babel';
import replace from '@rollup/plugin-replace';
import bundleSize from '@atomico/rollup-plugin-sizes';
import { terser } from 'rollup-plugin-terser';
import visualizer from 'rollup-plugin-visualizer';
import license from 'rollup-plugin-license';
import flowEntry from 'rollup-plugin-flow-entry';
import compiler from '@ampproject/rollup-plugin-closure-compiler';
import pkg from '../package.json';

const getFileName = (input) => input.split('/')[1].split('.')[0];

const inputs = ['src/popper.js', 'src/popper-lite.js', 'src/popper-base.js', 'src/enums.js'];
const bundles = [
  { inputs, format: 'umd', dir: 'dist', minify: true, flow: true },
  { inputs, format: 'umd', dir: 'dist' },
  { inputs, format: 'cjs', dir: 'dist', flow: true },
];

const configs = bundles
  .map(({ inputs, dir, format, minify, flow }) =>
    inputs.map((input) => ({
      input,
      plugins: [
        format === 'umd' &&
          replace({
            __DEV__: minify ? 'false' : 'true',
          }),
        babel({ babelHelpers: 'bundled' }),
        // The two minifiers together seem to procude a smaller bundle 🤷♂
        minify && compiler(),
        minify && terser(),
        license({ banner: `@popperjs/core v${pkg.version} - MIT License` }),
        flow && flowEntry({ types: `lib/${getFileName(input)}.js` }),
        bundleSize(),
        visualizer({
          sourcemap: true,
          filename: `stats/${getFileName(input)}${minify ? '-min' : ''}.html`,
        }),
      ].filter(Boolean),
      output: {
        name: 'Popper',
        file: `${dir}/${format}/${getFileName(input)}${
          minify ? '.min' : ''
        }.js`,
        format,
        sourcemap: true,
      },
    }))
  )
  .flat();

export default configs;
<|endoftext|>


<commit_before>var parser = require("./main");

describe("Performance tests", function() {
  var code = [
    "<?php",
    "class foo extends bar {",
    "  const A = 1, B = 2, C = 3;",
    "  protected $foo = null;",
    "  public function __construct($a, $b, $c, array $d = []) {",
    '    echo $a . $b . $c . implode(";", $d);',
    "  }",
    "  static public function bar(): foo {",
    "    return new self(1, 2, 3);",
    "  }",
    "}"
  ].join("\n");

  it("tokenizer", function() {
    var reader = new parser();
    var tokSize = reader.tokenGetAll(code).length;
    var hrTime = process.hrtime();
    var iter = 500;
    var start = hrTime[0] * 1000000 + hrTime[1] / 1000;
    for (var i = 0; i < iter; i++) {
      reader.tokenGetAll(code);
    }
    hrTime = process.hrtime();
    var end = hrTime[0] * 1000000 + hrTime[1] / 1000;
    var duration = (end - start) / 1000; // in MS
    var speed = 1000 / duration * (tokSize * iter);
    // speed.should.be.greaterThan(10e5 * 0.8);

    if (speed > 1000) {
      speed = speed / 1000;
      if (speed > 1000) {
        speed = speed / 1000;
        speed = Math.round(speed * 100) / 100 + "M";
      } else {
        speed = Math.round(speed * 100) / 100 + "K";
      }
    }
    console.log("    + Tokens speed  => " + speed + "/sec");

    speed = 1000 / duration * (code.length * iter);
    // speed.should.be.greaterThan(10e5 * 2 * 0.8);

    if (speed > 1024) {
      speed = speed / 1024;
      if (speed > 1024) {
        speed = speed / 1024;
        speed = Math.round(speed * 100) / 100 + "M";
      } else {
        speed = Math.round(speed * 100) / 100 + "K";
      }
    }
    console.log("    + Reading speed => " + speed + "/sec");
  });

  it("parser", function() {
    var reader = new parser();
    var nodeSize = 0;
    var countNode = function(node) {
      nodeSize++;
      for (var k in node) {
        if (node[k]) {
          if (node[k].kind) {
            countNode(node[k]);
          } else if (Array.isArray(node[k])) {
            for (var i = 0; i < node[k].length; i++) {
              if (node[k][i].kind) {
                countNode(node[k][i]);
              }
            }
          }
        }
      }
    };
    countNode(reader.parseCode(code));

    var hrTime = process.hrtime();
    var iter = 500;
    var start = hrTime[0] * 1000000 + hrTime[1] / 1000;
    for (var i = 0; i < iter; i++) {
      reader.parseCode(code);
    }
    hrTime = process.hrtime();
    var end = hrTime[0] * 1000000 + hrTime[1] / 1000;
    var duration = (end - start) / 1000; // in MS
    var speed = 1000 / duration * (nodeSize * iter);
    // speed.should.be.greaterThan(10e4);

    if (speed > 1000) {
      speed = speed / 1000;
      if (speed > 1000) {
        speed = speed / 1000;
        speed = Math.round(speed * 100) / 100 + "M";
      } else {
        speed = Math.round(speed * 100) / 100 + "K";
      }
    }
    console.log("    + Nodes speed  => " + speed + "/sec");

    speed = 1000 / duration * (code.length * iter);
    // speed.should.be.greaterThan(10e5 * 1 * 0.8);

    if (speed > 1024) {
      speed = speed / 1024;
      if (speed > 1024) {
        speed = speed / 1024;
        speed = Math.round(speed * 100) / 100 + "M";
      } else {
        speed = Math.round(speed * 100) / 100 + "K";
      }
    }
    console.log("    + Overall speed => " + speed + "/sec");
  });
});
<commit_msg>reduce iteration to pass tests on low backends<commit_after>var parser = require("./main");

describe("Performance tests", function() {
  var code = [
    "<?php",
    "class foo extends bar {",
    "  const A = 1, B = 2, C = 3;",
    "  protected $foo = null;",
    "  public function __construct($a, $b, $c, array $d = []) {",
    '    echo $a . $b . $c . implode(";", $d);',
    "  }",
    "  static public function bar(): foo {",
    "    return new self(1, 2, 3);",
    "  }",
    "}"
  ].join("\n");

  it("tokenizer", function() {
    var reader = new parser();
    var tokSize = reader.tokenGetAll(code).length;
    var hrTime = process.hrtime();
    var iter = 100;
    var start = hrTime[0] * 1000000 + hrTime[1] / 1000;
    for (var i = 0; i < iter; i++) {
      reader.tokenGetAll(code);
    }
    hrTime = process.hrtime();
    var end = hrTime[0] * 1000000 + hrTime[1] / 1000;
    var duration = (end - start) / 1000; // in MS
    var speed = 1000 / duration * (tokSize * iter);
    // speed.should.be.greaterThan(10e5 * 0.8);

    if (speed > 1000) {
      speed = speed / 1000;
      if (speed > 1000) {
        speed = speed / 1000;
        speed = Math.round(speed * 100) / 100 + "M";
      } else {
        speed = Math.round(speed * 100) / 100 + "K";
      }
    }
    console.log("    + Tokens speed  => " + speed + "/sec");

    speed = 1000 / duration * (code.length * iter);
    // speed.should.be.greaterThan(10e5 * 2 * 0.8);

    if (speed > 1024) {
      speed = speed / 1024;
      if (speed > 1024) {
        speed = speed / 1024;
        speed = Math.round(speed * 100) / 100 + "M";
      } else {
        speed = Math.round(speed * 100) / 100 + "K";
      }
    }
    console.log("    + Reading speed => " + speed + "/sec");
  });

  it("parser", function() {
    var reader = new parser();
    var nodeSize = 0;
    var countNode = function(node) {
      nodeSize++;
      for (var k in node) {
        if (node[k]) {
          if (node[k].kind) {
            countNode(node[k]);
          } else if (Array.isArray(node[k])) {
            for (var i = 0; i < node[k].length; i++) {
              if (node[k][i].kind) {
                countNode(node[k][i]);
              }
            }
          }
        }
      }
    };
    countNode(reader.parseCode(code));

    var hrTime = process.hrtime();
    var iter = 100;
    var start = hrTime[0] * 1000000 + hrTime[1] / 1000;
    for (var i = 0; i < iter; i++) {
      reader.parseCode(code);
    }
    hrTime = process.hrtime();
    var end = hrTime[0] * 1000000 + hrTime[1] / 1000;
    var duration = (end - start) / 1000; // in MS
    var speed = 1000 / duration * (nodeSize * iter);
    // speed.should.be.greaterThan(10e4);

    if (speed > 1000) {
      speed = speed / 1000;
      if (speed > 1000) {
        speed = speed / 1000;
        speed = Math.round(speed * 100) / 100 + "M";
      } else {
        speed = Math.round(speed * 100) / 100 + "K";
      }
    }
    console.log("    + Nodes speed  => " + speed + "/sec");

    speed = 1000 / duration * (code.length * iter);
    // speed.should.be.greaterThan(10e5 * 1 * 0.8);

    if (speed > 1024) {
      speed = speed / 1024;
      if (speed > 1024) {
        speed = speed / 1024;
        speed = Math.round(speed * 100) / 100 + "M";
      } else {
        speed = Math.round(speed * 100) / 100 + "K";
      }
    }
    console.log("    + Overall speed => " + speed + "/sec");
  });
});
<|endoftext|>


<commit_before>import 'es6-shim';
import 'reflect-metadata';
import { TranslatePipe, TranslateService } from '../lib';
import { test } from 'ava';

test('#transform should delegate the translation to the service with empty arguments if there is no', function(t) {
  const service = new TranslateService({ nested: { key: 'value%s' } });
  const pipe = new TranslatePipe(service);

  t.is(pipe.transform('nested.key', [5]), 'value');
});

test('#transform should delegate the translation to the service', function(t) {
  const service = new TranslateService({ nested: { key: 'value' } });
  const pipe = new TranslatePipe(service);

  t.is(pipe.transform('nested.key'), 'value');
});

<commit_msg>test(pipe): fix descriptions<commit_after>import 'es6-shim';
import 'reflect-metadata';
import { TranslatePipe, TranslateService } from '../lib';
import { test } from 'ava';

test('#transform should delegate the translation to the service', function(t) {
  const service = new TranslateService({ nested: { key: 'value%s' } });
  const pipe = new TranslatePipe(service);

  t.is(pipe.transform('nested.key', [5]), 'value5');
});

test('#transform should delegate the translation to the service with empty arguments if there is no', function(t) {
  const service = new TranslateService({ nested: { key: 'value' } });
  const pipe = new TranslatePipe(service);

  t.is(pipe.transform('nested.key'), 'value');
});

<|endoftext|>


<commit_before>var PJV = window.PJV;

function getPackageJson(extra) {
    var out = {
        "name": "test-package",
        "version": "0.5.0",
        "author": "Nick Sullivan <nick@sullivanflock.com>"
    };
    if (extra) {
        for (var name in extra) {
            out[name] = extra[name];
        }
    }
    return out;
}

QUnit.test("Input types", function() {
    QUnit.ok(PJV.validate("string").critical, "string");
    QUnit.ok(PJV.validate("{").critical, "malformed object");
    QUnit.ok(PJV.validate("[]").critical, "array");
    QUnit.ok(PJV.validate('"malformed"').critical, "quoted string");
    QUnit.ok(PJV.validate("42").critical, "number");
    QUnit.ok(PJV.validate("null").critical, "null");
    QUnit.ok(PJV.validate("true").critical, "true");
    QUnit.ok(PJV.validate("false").critical, "false");
    QUnit.ok(PJV.validate({}).critical, "literal object");
});

QUnit.test("NPM required fields", function() {
    var json = getPackageJson();
    var result = PJV.validate(JSON.stringify(json), "npm", {warnings: false, recommendations: false});
    QUnit.equal(result.valid, true, JSON.stringify(result));
    QUnit.equal(result.critical, undefined, JSON.stringify(result));

    ["name", "author", "version"].forEach(function(field) {
        json = getPackageJson();
        delete json[field];
        result = PJV.validate(JSON.stringify(json), "npm", {warnings: false, recommendations: false});
        QUnit.equal(result.valid, false, JSON.stringify(result));
        QUnit.equal(result.warnings, undefined, JSON.stringify(result));
    });
});

QUnit.test("NPM warning fields", function() {
    var warningFields = {
        description : "This is my description",
        keywords : ["keyword1", "keyword2", "keyword3"],
        bugs : "http://example.com/bugs",
        repository : { "type": "git", "url": "git@github.com:gorillamania/package.json-validator.git"},
        licenses : [{ "type": "MIT", "url": "http://example.com/license"}],
        contributors: ["Nick Sullivan <nick@sullivanflock.com>"]
    };
    var json = getPackageJson(warningFields);
    var result = PJV.validate(JSON.stringify(json), "npm", {warnings: true, recommendations: false});
    QUnit.equal(result.valid, true, JSON.stringify(result));
    QUnit.equal(result.critical, undefined, JSON.stringify(result));

    for (var field in warningFields) {
        json = getPackageJson(warningFields);
        delete json[field];
        result = PJV.validate(JSON.stringify(json), "npm", {warnings: true, recommendations: false});
        QUnit.equal(result.valid, true, JSON.stringify(result));
        QUnit.equal(result.warnings && result.warnings.length, 1, JSON.stringify(result));
    }
});

QUnit.test("NPM recommended fields", function() {
    var recommendedFields = {
        homepage : "http://example.com",
        engines : { "node" : ">=0.10.3 <0.12" },
        dependencies : { "package-json-validator" : "*" }
    };
    var json = getPackageJson(recommendedFields);
    var result = PJV.validate(JSON.stringify(json), "npm", {warnings: false, recommendations: true});
    QUnit.equal(result.valid, true, JSON.stringify(result));
    QUnit.equal(result.critical, undefined, JSON.stringify(result));

    for (var field in recommendedFields) {
        json = getPackageJson(recommendedFields);
        delete json[field];
        result = PJV.validate(JSON.stringify(json), "npm", {warnings: false, recommendations: true});
        QUnit.equal(result.valid, true, JSON.stringify(result));
        QUnit.equal(result.recommendations && result.recommendations.length, 1, JSON.stringify(result));
    }
});
<commit_msg>Failing unit test for issue #4<commit_after>var PJV = window.PJV;

function getPackageJson(extra) {
    var out = {
        "name": "test-package",
        "version": "0.5.0",
        "author": "Nick Sullivan <nick@sullivanflock.com>"
    };
    if (extra) {
        for (var name in extra) {
            out[name] = extra[name];
        }
    }
    return out;
}
var npmWarningFields = {
    description : "This is my description",
    keywords : ["keyword1", "keyword2", "keyword3"],
    bugs : "http://example.com/bugs",
    repository : { "type": "git", "url": "git@github.com:gorillamania/package.json-validator.git"},
    licenses : [{ "type": "MIT", "url": "http://example.com/license"}],
    contributors: ["Nick Sullivan <nick@sullivanflock.com>"]
};

QUnit.module("Basic");

QUnit.test("Input types", function() {
    QUnit.ok(PJV.validate("string").critical, "string");
    QUnit.ok(PJV.validate("{").critical, "malformed object");
    QUnit.ok(PJV.validate("[]").critical, "array");
    QUnit.ok(PJV.validate('"malformed"').critical, "quoted string");
    QUnit.ok(PJV.validate("42").critical, "number");
    QUnit.ok(PJV.validate("null").critical, "null");
    QUnit.ok(PJV.validate("true").critical, "true");
    QUnit.ok(PJV.validate("false").critical, "false");
    QUnit.ok(PJV.validate({}).critical, "literal object");
});

QUnit.module("NPM");

QUnit.test("Required fields", function() {
    var json = getPackageJson();
    var result = PJV.validate(JSON.stringify(json), "npm", {warnings: false, recommendations: false});
    QUnit.equal(result.valid, true, JSON.stringify(result));
    QUnit.equal(result.critical, undefined, JSON.stringify(result));

    ["name", "author", "version"].forEach(function(field) {
        json = getPackageJson();
        delete json[field];
        result = PJV.validate(JSON.stringify(json), "npm", {warnings: false, recommendations: false});
        QUnit.equal(result.valid, false, JSON.stringify(result));
        QUnit.equal(result.warnings, undefined, JSON.stringify(result));
    });
});

QUnit.test("Warning fields", function() {
   var json = getPackageJson(npmWarningFields);
    var result = PJV.validate(JSON.stringify(json), "npm", {warnings: true, recommendations: false});
    QUnit.equal(result.valid, true, JSON.stringify(result));
    QUnit.equal(result.critical, undefined, JSON.stringify(result));

    for (var field in npmWarningFields) {
        json = getPackageJson(npmWarningFields);
        delete json[field];
        result = PJV.validate(JSON.stringify(json), "npm", {warnings: true, recommendations: false});
        QUnit.equal(result.valid, true, JSON.stringify(result));
        QUnit.equal(result.warnings && result.warnings.length, 1, JSON.stringify(result));
    }
});

QUnit.test("Recommended fields", function() {
    var recommendedFields = {
        homepage : "http://example.com",
        engines : { "node" : ">=0.10.3 <0.12" },
        dependencies : { "package-json-validator" : "*" }
    };
    var json = getPackageJson(recommendedFields);
    var result = PJV.validate(JSON.stringify(json), "npm", {warnings: false, recommendations: true});
    QUnit.equal(result.valid, true, JSON.stringify(result));
    QUnit.equal(result.critical, undefined, JSON.stringify(result));

    for (var field in recommendedFields) {
        json = getPackageJson(recommendedFields);
        delete json[field];
        result = PJV.validate(JSON.stringify(json), "npm", {warnings: false, recommendations: true});
        QUnit.equal(result.valid, true, JSON.stringify(result));
        QUnit.equal(result.recommendations && result.recommendations.length, 1, JSON.stringify(result));
    }
});

QUnit.test("Licenses", function() {
    // https://npmjs.org/doc/json.html#license

    // licenses as an array
    var json = getPackageJson(npmWarningFields);
    var result = PJV.validate(JSON.stringify(json), "npm", {warnings: true, recommendations: false});
    QUnit.equal(result.valid, true, JSON.stringify(result));
    QUnit.equal(result.critical, undefined, JSON.stringify(result));
    QUnit.equal(result.warnings, undefined, JSON.stringify(result));

    // licenses as a single type
    json = getPackageJson(npmWarningFields);
    delete json.licenses;
    json.license = "MIT";
    result = PJV.validate(JSON.stringify(json), "npm", {warnings: true, recommendations: false});
    QUnit.equal(result.valid, true, JSON.stringify(result));
    QUnit.equal(result.critical, undefined, JSON.stringify(result));
    QUnit.equal(result.warnings, undefined, JSON.stringify(result));
});
<|endoftext|>


<commit_before>var nt     = require('..');
var vows   = require('vows');
var assert = require('assert');
var path   = require('path');
var fs     = require('fs');
var url    = require('url');
var nock   = require('nock');

var file2 = path.join(__dirname,'torrents', 'click.jpg.torrent');
var file3 = path.join(__dirname, 'torrents', 'virtualbox.torrent');
var remotefile3 = 'http://www.mininova.org/get/2886852';
var file4 = path.join(__dirname, 'torrents', 'chipcheezum.torrent');

// Mock request to remote file.
var parsedUrl = url.parse(remotefile3);
nock('http://' + parsedUrl.host)
  .get(parsedUrl.pathname)
  .replyWithFile(200, file3);

vows.describe('Read')
  .addBatch({
    // This torrent was created with mktorrent.
    'Read a local file': {
      'made by mktorrent': {
        topic: function() {
          nt.read(file2, this.callback);
        },

        'Info hash matches': function(result) {
          assert.isObject(result.metadata);
          assert.equal(result.infoHash(),
              '2fff646b166f37f4fd131778123b25a01639e0b3');
        },
        'Announce URL is correct': function(result) {
          assert.isObject(result.metadata);
          assert.include(result.metadata, 'announce');
          assert.equal(result.metadata.announce, 'http://hello.2u');
        },
        'Single file mode': function(result) {
          assert.isObject(result.metadata);
          assert.include(result.metadata, 'info');
          assert.include(result.metadata.info, 'name');
          assert.equal(result.metadata.info.name, 'click.jpg');
          assert.isUndefined(result.metadata.info.files);
          assert.include(result.metadata.info, 'length');
          assert.equal(result.metadata.info.length, 87582);
        },
        '256 KB piece length': function(result) {
          assert.isObject(result.metadata);
          assert.include(result.metadata, 'info');
          assert.include(result.metadata.info, 'piece length');
          assert.equal(result.metadata.info['piece length'], 262144);
        },
        'Private torrent': function(result) {
          assert.isObject(result.metadata);
          assert.include(result.metadata, 'info');
          assert.include(result.metadata.info, 'private');
          assert.equal(result.metadata.info.private, 1);
        }
      },

      'that holds a big video file': {
        topic: function() {
          nt.read(file4, this.callback);
        },

        'Info hash matches': function(result) {
          assert.isObject(result.metadata);
          assert.equal(result.infoHash(),
              'a51cbb0e3b4d6430ca0d1da70c1c7b0bb94304f4');
        }
      }
    },

    'Read a stream': {
      'that holds a big video file': {
        topic: function() {
          nt.read(fs.createReadStream(file4), this.callback);
        },

        'Info hash matches': function(result) {
          assert.isObject(result.metadata);
          assert.equal(result.infoHash(),
              'a51cbb0e3b4d6430ca0d1da70c1c7b0bb94304f4');
        }
      }
    },

    'Download a torrent and read it': {
      topic: function() {
        nt.read(remotefile3, this.callback);
      },

      'Info hash matches': function(result) {
        assert.isObject(result.metadata);
        assert.equal(result.infoHash(),
            '6a7eb42ab3b9781eba2d9ff3545d9758f27ec239');
      },
      'Announce URL is correct': function(result) {
        assert.isObject(result.metadata);
        assert.include(result.metadata, 'announce');
        assert.equal(result.metadata.announce, 'http://tracker.mininova.org/announce');
      },
      'Multi file mode': function(result) {
        assert.isObject(result.metadata);
        assert.include(result.metadata, 'info');
        assert.include(result.metadata.info, 'name');
        assert.equal(result.metadata.info.name,
                     'VirtualBox - CentOS 4.8 i386 Desktop Virtual Disk Image' +
                     ' - [VirtualBoxImages.com]');
        assert.include(result.metadata.info, 'files');
        assert.deepEqual(result.metadata.info.files, [
          {
            length: 291,
            path: [ 'Distributed by Mininova.txt' ]
          },
          {
            length: 917356457,
            path: [ 'VirtualBox_-_CentOS-4.8-Desktop-i386_VDI-[VirtualBoxImages.com].rar' ]
          }
        ]);
      },
      '1 MB piece length': function(result) {
        assert.isObject(result.metadata);
        assert.include(result.metadata, 'info');
        assert.include(result.metadata.info, 'piece length');
        assert.equal(result.metadata.info['piece length'], 1048576);
      }
    }
  })
  .export(module);
<commit_msg>move nock to test function<commit_after>var nt     = require('..');
var vows   = require('vows');
var assert = require('assert');
var path   = require('path');
var fs     = require('fs');
var url    = require('url');
var nock   = require('nock');

var file2 = path.join(__dirname,'torrents', 'click.jpg.torrent');
var file3 = path.join(__dirname, 'torrents', 'virtualbox.torrent');
var remotefile3 = 'http://www.mininova.org/get/2886852';
var file4 = path.join(__dirname, 'torrents', 'chipcheezum.torrent');

vows.describe('Read')
  .addBatch({
    // This torrent was created with mktorrent.
    'Read a local file': {
      'made by mktorrent': {
        topic: function() {
          nt.read(file2, this.callback);
        },

        'Info hash matches': function(result) {
          assert.isObject(result.metadata);
          assert.equal(result.infoHash(),
              '2fff646b166f37f4fd131778123b25a01639e0b3');
        },
        'Announce URL is correct': function(result) {
          assert.isObject(result.metadata);
          assert.include(result.metadata, 'announce');
          assert.equal(result.metadata.announce, 'http://hello.2u');
        },
        'Single file mode': function(result) {
          assert.isObject(result.metadata);
          assert.include(result.metadata, 'info');
          assert.include(result.metadata.info, 'name');
          assert.equal(result.metadata.info.name, 'click.jpg');
          assert.isUndefined(result.metadata.info.files);
          assert.include(result.metadata.info, 'length');
          assert.equal(result.metadata.info.length, 87582);
        },
        '256 KB piece length': function(result) {
          assert.isObject(result.metadata);
          assert.include(result.metadata, 'info');
          assert.include(result.metadata.info, 'piece length');
          assert.equal(result.metadata.info['piece length'], 262144);
        },
        'Private torrent': function(result) {
          assert.isObject(result.metadata);
          assert.include(result.metadata, 'info');
          assert.include(result.metadata.info, 'private');
          assert.equal(result.metadata.info.private, 1);
        }
      },

      'that holds a big video file': {
        topic: function() {
          nt.read(file4, this.callback);
        },

        'Info hash matches': function(result) {
          assert.isObject(result.metadata);
          assert.equal(result.infoHash(),
              'a51cbb0e3b4d6430ca0d1da70c1c7b0bb94304f4');
        }
      }
    },

    'Read a stream': {
      'that holds a big video file': {
        topic: function() {
          nt.read(fs.createReadStream(file4), this.callback);
        },

        'Info hash matches': function(result) {
          assert.isObject(result.metadata);
          assert.equal(result.infoHash(),
              'a51cbb0e3b4d6430ca0d1da70c1c7b0bb94304f4');
        }
      }
    },

    'Download a torrent and read it': {
      topic: function() {
        // Mock request to remote file.
        var parsedUrl = url.parse(remotefile3);
        nock('http://' + parsedUrl.host)
          .get(parsedUrl.pathname)
          .replyWithFile(200, file3);

        nt.read(remotefile3, this.callback);
      },

      'Info hash matches': function(result) {
        assert.isObject(result.metadata);
        assert.equal(result.infoHash(),
            '6a7eb42ab3b9781eba2d9ff3545d9758f27ec239');
      },
      'Announce URL is correct': function(result) {
        assert.isObject(result.metadata);
        assert.include(result.metadata, 'announce');
        assert.equal(result.metadata.announce, 'http://tracker.mininova.org/announce');
      },
      'Multi file mode': function(result) {
        assert.isObject(result.metadata);
        assert.include(result.metadata, 'info');
        assert.include(result.metadata.info, 'name');
        assert.equal(result.metadata.info.name,
                     'VirtualBox - CentOS 4.8 i386 Desktop Virtual Disk Image' +
                     ' - [VirtualBoxImages.com]');
        assert.include(result.metadata.info, 'files');
        assert.deepEqual(result.metadata.info.files, [
          {
            length: 291,
            path: [ 'Distributed by Mininova.txt' ]
          },
          {
            length: 917356457,
            path: [ 'VirtualBox_-_CentOS-4.8-Desktop-i386_VDI-[VirtualBoxImages.com].rar' ]
          }
        ]);
      },
      '1 MB piece length': function(result) {
        assert.isObject(result.metadata);
        assert.include(result.metadata, 'info');
        assert.include(result.metadata.info, 'piece length');
        assert.equal(result.metadata.info['piece length'], 1048576);
      }
    }
  })
  .export(module);
<|endoftext|>


<commit_before>var assert = require('assert')
var fs = require('fs')
var path = require('path')
var fse = require('../')
var testutil = require('testutil')

/* global afterEach, beforeEach, describe, it */

var TEST_DIR = ''

describe('read', function () {
  beforeEach(function () {
    TEST_DIR = testutil.createTestDir('fs-extra')
  })

  afterEach(function (done) {
    fse.remove(TEST_DIR, done)
  })

  describe('+ readJSON', function () {
    it('should read a file and parse the json', function (done) {
      var obj1 = {
        firstName: 'JP',
        lastName: 'Richardson'
      }

      var file = path.join(TEST_DIR, 'file.json')
      fs.writeFileSync(file, JSON.stringify(obj1))
      fse.readJSON(file, function (err, obj2) {
        assert.ifError(err)
        assert.strictEqual(obj1.firstName, obj2.firstName)
        assert.strictEqual(obj1.lastName, obj2.lastName)

        done()
      })
    })

    it('should error if it cant parse the json', function (done) {
      var file = path.join(TEST_DIR, 'file2.json')
      fs.writeFileSync(file, '%asdfasdff444')
      fse.readJSON(file, function (err, obj) {
        assert(err)
        assert(!obj)
        done()
      })
    })
  })
})
<commit_msg>test/read: removed testutil<commit_after>var assert = require('assert')
var fs = require('fs')
var path = require('path')
var os = require('os')
var fse = require('../')

/* global afterEach, beforeEach, describe, it */

describe('read', function () {
  var TEST_DIR

  beforeEach(function (done) {
    TEST_DIR = path.join(os.tmpdir(), 'fs-extra', 'read-json')
    fse.emptyDir(TEST_DIR, done)
  })

  afterEach(function (done) {
    fse.remove(TEST_DIR, done)
  })

  describe('+ readJSON', function () {
    it('should read a file and parse the json', function (done) {
      var obj1 = {
        firstName: 'JP',
        lastName: 'Richardson'
      }

      var file = path.join(TEST_DIR, 'file.json')
      fs.writeFileSync(file, JSON.stringify(obj1))
      fse.readJSON(file, function (err, obj2) {
        assert.ifError(err)
        assert.strictEqual(obj1.firstName, obj2.firstName)
        assert.strictEqual(obj1.lastName, obj2.lastName)

        done()
      })
    })

    it('should error if it cant parse the json', function (done) {
      var file = path.join(TEST_DIR, 'file2.json')
      fs.writeFileSync(file, '%asdfasdff444')
      fse.readJSON(file, function (err, obj) {
        assert(err)
        assert(!obj)
        done()
      })
    })
  })
})
<|endoftext|>