<commit_before>'use babel'

/* @flow */

import { CompositeDisposable, Emitter, Disposable } from 'atom'
import { getMessageClass } from './helpers'
import { getElement as getGutterElement } from './elements/gutter'
import type { TextEditor, TextBuffer, TextEditorMarker } from 'atom'
import type { Linter$Message } from './types'
import type Editor from './editor'

export default class Buffer {
  emitter: Emitter;
  markers: Object; // Object<string, TextEditorMarker>
  textBuffer: TextBuffer;
  textEditors: Set<TextEditor>;
  subscriptions: CompositeDisposable;

  constructor(textBuffer: TextBuffer) {
    this.emitter = new Emitter()
    this.markers = { }
    this.textBuffer = textBuffer
    this.textEditors = new Set()
    this.subscriptions = new CompositeDisposable()

    this.subscriptions.add(this.emitter)
    this.subscriptions.add(textBuffer.onDidDestroy(() => {
      this.dispose()
    }))
  }
  getBuffer(): TextBuffer {
    return this.textBuffer
  }
  attachEditor(editor: Editor) {
    this.textEditors.add(editor)
    this.subscriptions.add(editor)
    editor.onDidDestroy(() => {
      this.subscriptions.remove(editor)
      this.textEditors.delete(editor)
    })
  }
  apply(added: Array<Linter$Message>, removed: Array<Linter$Message>) {
    for (const message of removed) {
      const marker = this.markers[message.id]
      if (marker) {
        marker.destroy()
        this.markers[message.id] = null
      }
    }

    for (const message of added) {
      const marker = this.textBuffer.markRange(message.range, {
        invalidate: 'never',
        persistent: false
      })
      this.markers[message.id] = marker
      const messageClass = getMessageClass(message)
      for (const editor of this.textEditors) {
        editor.textEditor.decorateMarker(marker, {
          type: 'highlight',
          class: `linter-highlight ${messageClass}`
        })
        if (editor.gutter) {
          editor.gutter.decorateMarker(marker, {
            class: 'linter-row',
            item: getGutterElement(messageClass)
          })
        }
      }
    }
  }
  onDidDestroy(callback: Function): Disposable {
    return this.emitter.on('did-destroy', callback)
  }
  dispose() {
    this.emitter.emit('did-destroy')
    this.subscriptions.dispose()

    for (const key in this.markers) {
      const value = this.markers[key]
      if (value) {
        value.destroy()
      }
    }
    this.markers = { }
  }
}
<commit_msg>:new: Store per buffer messages They are going to be helpful when showing inline bubble<commit_after>'use babel'

/* @flow */

import { CompositeDisposable, Emitter, Disposable } from 'atom'
import { getMessageClass } from './helpers'
import { getElement as getGutterElement } from './elements/gutter'
import type { TextEditor, TextBuffer, TextEditorMarker } from 'atom'
import type { Linter$Message } from './types'
import type Editor from './editor'

export default class Buffer {
  emitter: Emitter;
  markers: Object; // Object<string, TextEditorMarker>
  messages: Set<Linter$Message>;
  textBuffer: TextBuffer;
  textEditors: Set<TextEditor>;
  subscriptions: CompositeDisposable;

  constructor(textBuffer: TextBuffer) {
    this.emitter = new Emitter()
    this.markers = { }
    this.messages = new Set()
    this.textBuffer = textBuffer
    this.textEditors = new Set()
    this.subscriptions = new CompositeDisposable()

    this.subscriptions.add(this.emitter)
    this.subscriptions.add(textBuffer.onDidDestroy(() => {
      this.dispose()
    }))
  }
  getBuffer(): TextBuffer {
    return this.textBuffer
  }
  attachEditor(editor: Editor) {
    this.textEditors.add(editor)
    this.subscriptions.add(editor)
    editor.onDidDestroy(() => {
      this.subscriptions.remove(editor)
      this.textEditors.delete(editor)
    })
  }
  apply(added: Array<Linter$Message>, removed: Array<Linter$Message>) {
    for (const message of removed) {
      const marker = this.markers[message.id]
      if (marker) {
        marker.destroy()
        this.markers[message.id] = null
      }
      this.messages.delete(message)
    }

    for (const message of added) {
      const marker = this.textBuffer.markRange(message.range, {
        invalidate: 'never',
        persistent: false
      })
      this.markers[message.id] = marker
      this.messages.add(message)
      const messageClass = getMessageClass(message)
      for (const editor of this.textEditors) {
        editor.textEditor.decorateMarker(marker, {
          type: 'highlight',
          class: `linter-highlight ${messageClass}`
        })
        if (editor.gutter) {
          editor.gutter.decorateMarker(marker, {
            class: 'linter-row',
            item: getGutterElement(messageClass)
          })
        }
      }
    }
  }
  onDidDestroy(callback: Function): Disposable {
    return this.emitter.on('did-destroy', callback)
  }
  dispose() {
    this.emitter.emit('did-destroy')
    this.subscriptions.dispose()

    for (const key in this.markers) {
      const value = this.markers[key]
      if (value) {
        value.destroy()
      }
    }
    this.markers = { }
  }
}
<|endoftext|>


<commit_before>'use strict';

var fs = require('fs'),
    Path = require('path'),
    Promise = require('bluebird');

var eachAsync = exports.eachAsync = function (array, iterator, done) {
  return new Promise(function (resolve,reject) {
    var i = 0, len = array.length, next;
    next = function(e) {
      if (e != null || i === len)
        return e ? reject(e) : resolve();
      iterator(array[i++], next);
    };
    next(null);
  }).nodeify(done);
};

['Array', 'String'].forEach(function (e) {
  exports['is'+e] = function (arg) {
    return Object.prototype.toString.call(arg) === '[object ' + e + ']';
  };
});

var camelize = exports.camelize = function (str) {
  return str.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');});
};

var __slice = exports.slice = Array.prototype.slice;

// Deprecate: use object-assign instead.
var extend = exports.extend = function () {
  var o, a, b, p, i;
  a = arguments[0], b = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
  for (i = 0; i < b.length; i++) {
    if ((o = b[i]) == null) continue;
    for (p in o) a[p] = o[p];
  }
  return a;
};

exports.exts = ['.js','.coffee'];

exports.resolveFile = function (dir, name, suffix, exts) {
  dir = Path.resolve(dir);
  var f, i, p;
  suffix = suffix || '-controller';
  name = name.toLowerCase();

  p = [name+suffix,camelize(name+suffix)];

  for (i = 0; i < p.length; i++) {
    f = Path.join(dir,p[i]);
    f = exports.resolveExt(f,exts);
    if (f) return f;
  }

};

exports.resolveExt = function(fileName, exts) {
  var f, i;
  if (exts == null) exts = exports.exts;

  for (i = 0; i < exts.length; i++) {
    f = fileName + exts[i];
    if (fs.existsSync(f)) {
      return f;
    }
  }
  return null;
};

// TODO: Handle sub directories.
var requireDir = exports.requireDir = function (path, cb, exts, recursive) {
  recursive = recursive || false;

  var readdir = Promise.promisify(fs.readdir);
  var stat = Promise.promisify(fs.stat);

  exts = exts || exports.exts;

  return readdir(path).then(function (files) {
    return eachAsync(files.sort(), function (file, next) {
      var fp = Path.join(path, file), mod;
      if (file[0] === '.') return next();

      fs.stat(fp, function (err, stats) {
        if (err) return done(err);

        if (stats.isDirectory()) {
          if (!recursive) return next();

          requireDir(fp,cb,exts,true).then(function () {
            next();
          },next);

        } else if (stats.isFile()) {
          // if the file starts with '.' or doesn't has an extension.
          if (exts.indexOf(Path.extname(file)) == -1)
            return next();

          try {
            mod = requireFile(fp);
          } catch (e) {
            return next(e);
          }
          cb(mod, fp, next);

        } else {
          next();
        }

      });

    });
  });

};

function requireFile (file) {
  ext = Path.extname(file);

  if (ext === '.json') {
    return require(file);
  } else if (ext === '.js') {
    return require(file);
  } else if (ext === '.coffee') {
    var coffee = require('coffee-script');
    if (coffee.Register)
      coffee.Register();
    return require(file);
  } else if (ext === '.cson') {
    var cson = require('cson');
    return cson.parseFileSync(file);
  } else if (ext === '.yaml') {

  }
  throw new Error('No parser found')
}
<commit_msg>added support for more file types in utils.requireDir<commit_after>'use strict';

var fs = require('fs'),
    Path = require('path'),
    Promise = require('bluebird');

var eachAsync = exports.eachAsync = function (array, iterator, done) {
  return new Promise(function (resolve,reject) {
    var i = 0, len = array.length, next;
    next = function(e) {
      if (e != null || i === len)
        return e ? reject(e) : resolve();
      iterator(array[i++], next);
    };
    next(null);
  }).nodeify(done);
};

['Array', 'String'].forEach(function (e) {
  exports['is'+e] = function (arg) {
    return Object.prototype.toString.call(arg) === '[object ' + e + ']';
  };
});

var camelize = exports.camelize = function (str) {
  return str.replace(/(\-[a-z])/g, function($1){return $1.toUpperCase().replace('-','');});
};

var __slice = exports.slice = Array.prototype.slice;

// Deprecate: use object-assign instead.
var extend = exports.extend = function () {
  var o, a, b, p, i;
  a = arguments[0], b = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
  for (i = 0; i < b.length; i++) {
    if ((o = b[i]) == null) continue;
    for (p in o) a[p] = o[p];
  }
  return a;
};

exports.exts = ['.js','.coffee'];

exports.resolveFile = function (dir, name, suffix, exts) {
  dir = Path.resolve(dir);
  var f, i, p;
  suffix = suffix || '-controller';
  name = name.toLowerCase();

  p = [name+suffix,camelize(name+suffix)];

  for (i = 0; i < p.length; i++) {
    f = Path.join(dir,p[i]);
    f = exports.resolveExt(f,exts);
    if (f) return f;
  }

};

exports.resolveExt = function(fileName, exts) {
  var f, i;
  if (exts == null) exts = exports.exts;

  for (i = 0; i < exts.length; i++) {
    f = fileName + exts[i];
    if (fs.existsSync(f)) {
      return f;
    }
  }
  return null;
};

// TODO: Handle sub directories.
var requireDir = exports.requireDir = function (path, cb, exts, recursive) {
  recursive = recursive || false;

  var readdir = Promise.promisify(fs.readdir);
  var stat = Promise.promisify(fs.stat);

  exts = exts || exports.exts;

  return readdir(path).then(function (files) {
    return eachAsync(files.sort(), function (file, next) {
      var fp = Path.join(path, file), mod;
      if (file[0] === '.') return next();

      fs.stat(fp, function (err, stats) {
        if (err) return done(err);

        if (stats.isDirectory()) {
          if (!recursive) return next();

          requireDir(fp,cb,exts,true).then(function () {
            next();
          },next);

        } else if (stats.isFile()) {
          // if the file starts with '.' or doesn't has an extension.
          if (exts.indexOf(Path.extname(file)) == -1)
            return next();

          try {
            mod = requireFile(fp);
          } catch (e) {
            return next(e);
          }
          cb(mod, fp, next);

        } else {
          next();
        }

      });

    });
  });

};

function requireFile (file) {
  var ext = Path.extname(file);

  if (ext === '.json') {
    return require(file);
  } else if (ext === '.js') {
    return require(file);
  } else if (ext === '.coffee') {
    var coffee = require('coffee-script');
    if (coffee.Register)
      coffee.Register();
    return require(file);
  } else if (ext === '.cson') {
    var cson = require('cson');
    return cson.parseFileSync(file);
  } else if (ext === '.yaml') {

  }
  throw new Error('No parser found')
}
<|endoftext|>


<commit_before>'use strict';

var debug = require('debug')('copress:component:sycle');
var path = require('path');
var _ = require('lodash');
var sycle = require('sycle');
var delegate = require('delegates');
var configup = require('configup');

var pathRe = /^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[\\\/])/;

module.exports = function (app, options, done) {
  var c = app.compound || app.copress;
  options = options || {};

  var loadBuiltinModels = options.loadBuiltinModels !== false;
  var sapp = sycle({loadBuiltinModels: loadBuiltinModels});
  var root = sapp.root = c.root;
  var env = app.get('env');
  app.sapp = sapp;
  sapp.app = app;

  delegate(app, 'sapp')
    .method('rekuest')
    .method('model')
    .access('models');

  delegate(sapp, 'app')
    .method('set');

  // load models
  debug('loading models ...');
  var models = options.models || [path.resolve(root, 'config')];
  if (!Array.isArray(models)) models = [models];
  _.forEach(models, function (m) {
    var x = pathRe.test(m) ? path.resolve(root, 'config', m) : m;
    debug('loading models from ', x);
    sapp.phase(sycle.boot.models(x));
  });

  // enable auth
  if (options.auth) {
    debug('enable auth');
    sapp.enableAuth();
  }

  // load database settings
  debug('loading databases ...');
  var databasesConfigFile = path.resolve(root, 'config/databases');
  if (!configup.hasConfigFiles(databasesConfigFile, env)) {
    console.log('Could not load config/databases.json');
    throw new Error('Could not load config/databases.json');
  }
  var settings = configup.loadDeepMerge(databasesConfigFile, env);
  sapp.phase(sycle.boot.database(settings));

  // boot sycle app
  debug('booting ...');
  sapp.boot(done);
};
<commit_msg>delegate request, model and models to compound instance<commit_after>'use strict';

var debug = require('debug')('copress:component:sycle');
var path = require('path');
var _ = require('lodash');
var sycle = require('sycle');
var delegate = require('delegates');
var configup = require('configup');

var pathRe = /^(?:\.\.?(?:\/|$)|\/|([A-Za-z]:)?[\\\/])/;

module.exports = function (app, options, done) {
  var c = app.compound || app.copress;
  options = options || {};

  var loadBuiltinModels = options.loadBuiltinModels !== false;
  var sapp = sycle({loadBuiltinModels: loadBuiltinModels});

  var root = sapp.root = c.root;

  c.sapp = app.sapp = sapp;
  sapp.app = app;

  // delegates
  delegate(c, 'sapp')
    .method('request')
    .method('model')
    .access('models');

  delegate(app, 'sapp')
    .method('request')
    .method('model')
    .access('models');

  delegate(sapp, 'app')
    .method('set');

  var env = app.get('env');

  // load models
  debug('loading models ...');
  var models = options.models || [path.resolve(root, 'config')];
  if (!Array.isArray(models)) models = [models];
  _.forEach(models, function (m) {
    var x = pathRe.test(m) ? path.resolve(root, 'config', m) : m;
    debug('loading models from ', x);
    sapp.phase(sycle.boot.models(x));
  });

  // enable auth
  if (options.auth) {
    debug('enable auth');
    sapp.enableAuth();
  }

  // load database settings
  debug('loading databases ...');
  var databasesConfigFile = path.resolve(root, 'config/databases');
  if (!configup.hasConfigFiles(databasesConfigFile, env)) {
    console.log('Could not load config/databases.json');
    throw new Error('Could not load config/databases.json');
  }
  var settings = configup.loadDeepMerge(databasesConfigFile, env);
  sapp.phase(sycle.boot.database(settings));

  // boot sycle app
  debug('booting ...');
  sapp.boot(done);
};
<|endoftext|>


<commit_before>/* eslint-disable no-var,prefer-arrow-callback,vars-on-top */

require('babel-register');

var IgnorePlugin = require('webpack').IgnorePlugin;
var REACT013 = require('./src/version').REACT013;

module.exports = function karma(config) {
  config.set({
    basePath: '.',

    plugins: [
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-mocha',
      'karma-webpack',
      'karma-sourcemap-loader',
    ],

    customLaunchers: {
      Chrome_travis: {
        base: 'Chrome',
        flags: ['--no-sandbox'],
      },
    },

    frameworks: ['mocha'],

    reporters: ['dots'],

    files: [
      'test/*.{jsx,js}',
    ],

    exclude: [
      'test/_*.{jsx,js}',
    ],

    browsers: [
      process.env.TRAVIS ? 'Chrome_travis' : 'Chrome',
      'Firefox',
    ],

    preprocessors: {
      'test/*.{jsx,js}': ['webpack', 'sourcemap'],
    },

    webpack: {
      devtool: 'inline-source-map',
      resolve: {
        extensions: ['', '.js', '.jsx', '.json'],
        alias: {
          // dynamic require calls in sinon confuse webpack so we ignore it
          sinon: 'sinon/pkg/sinon',
        },
      },
      module: {
        noParse: [
          // dynamic require calls in sinon confuse webpack so we ignore it
          /node_modules\/sinon\//,
        ],
        loaders: [
          {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
          },
          {
            test: /\.json$/,
            loader: 'json-loader',
          },
        ],
      },
      plugins: [
        /*
        this list of conditional IgnorePlugins mirrors the conditional
        requires in src/react-compat.js and exists to avoid error
        output from the webpack compilation
        */
        !REACT013 && new IgnorePlugin(/react\/lib\/ExecutionEnvironment/),
        !REACT013 && new IgnorePlugin(/react\/lib\/ReactContext/),
        !REACT013 && new IgnorePlugin(/react\/addons/),
        REACT013 && new IgnorePlugin(/react-dom/),
        REACT013 && new IgnorePlugin(/react-addons-test-utils/),
      ].filter(function filterPlugins(plugin) { return plugin !== false; }),
    },

    webpackServer: {
      noInfo: true,
    },
  });
};
<commit_msg>Update karma cofig to be compatible with react@15.5<commit_after>/* eslint-disable no-var,prefer-arrow-callback,vars-on-top */

require('babel-register');

var IgnorePlugin = require('webpack').IgnorePlugin;
var REACT013 = require('./src/version').REACT013;
var REACT155 = require('./src/version').REACT155;

function getPlugins() {
  var plugins = [];

  /*
  this list of conditional IgnorePlugins mirrors the conditional
  requires in src/react-compat.js and exists to avoid error
  output from the webpack compilation
  */

  if (!REACT013) {
    plugins.push(new IgnorePlugin(/react\/lib\/ExecutionEnvironment/));
    plugins.push(new IgnorePlugin(/react\/lib\/ReactContext/));
    plugins.push(new IgnorePlugin(/react\/addons/));
  }
  if (REACT013) {
    plugins.push(new IgnorePlugin(/react-dom/));
  }
  if (REACT013 || REACT155) {
    plugins.push(new IgnorePlugin(/react-addons-test-utils/));
  }
  if (!REACT155) {
    plugins.push(new IgnorePlugin(/react-test-renderer/));
    plugins.push(new IgnorePlugin(/react-dom\/test-utils/));
    plugins.push(new IgnorePlugin(/create-react-class/));
  }

  return plugins
}

module.exports = function karma(config) {
  config.set({
    basePath: '.',

    plugins: [
      'karma-chrome-launcher',
      'karma-firefox-launcher',
      'karma-mocha',
      'karma-webpack',
      'karma-sourcemap-loader',
    ],

    customLaunchers: {
      Chrome_travis: {
        base: 'Chrome',
        flags: ['--no-sandbox'],
      },
    },

    frameworks: ['mocha'],

    reporters: ['dots'],

    files: [
      'test/*-spec.{jsx,js}',
    ],

    browsers: [
      process.env.TRAVIS ? 'Chrome_travis' : 'Chrome',
      'Firefox',
    ],

    preprocessors: {
      'test/*.{jsx,js}': ['webpack', 'sourcemap'],
    },

    webpack: {
      devtool: 'inline-source-map',
      resolve: {
        extensions: ['', '.js', '.jsx', '.json'],
        alias: {
          // dynamic require calls in sinon confuse webpack so we ignore it
          sinon: 'sinon/pkg/sinon',
        },
      },
      module: {
        noParse: [
          // dynamic require calls in sinon confuse webpack so we ignore it
          /node_modules\/sinon\//,
        ],
        loaders: [
          {
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel-loader',
          },
          {
            test: /\.json$/,
            loader: 'json-loader',
          },
        ],
      },
      plugins: getPlugins(),
    },

    webpackServer: {
      noInfo: true,
    },
  });
};
<|endoftext|>


<commit_before>/* 28aug13abu
 * (c) Software Lab. Alexander Burger
 */

function drawCanvas(id, dly) {
   var req = new XMLHttpRequest();

   try {
      req.open("POST",
         document.getElementsByTagName("BASE")[0].href + SesId +
         "!jsDraw?" + id + "&+" + dly);
      req.responseType = "arraybuffer";
   }
   catch (e) {return true;}
   req.onload = function() {
      var lst = plio(new Uint8Array(req.response));
      var cmd, i, j;

      if (lst) {
         var ctx = document.getElementById(id).getContext("2d");

         for (i = 0; i < lst.length; ++i) {
            switch ((cmd = lst[i])[0]) {  // In sync with "@lib/canvas.l"
            /*** Functions ***/
            case 1:
               ctx.fillText(cmd[1], cmd[2], cmd[3]);
               break;
            case 2:
               ctx.beginPath();
               ctx.moveTo(cmd[1], cmd[2]);
               ctx.lineTo(cmd[3], cmd[4]);
               ctx.closePath();
               ctx.stroke();
               break;
            case 3:
               ctx.clearRect(cmd[1], cmd[2], cmd[3], cmd[4]);
               break;
            case 4:
               ctx.strokeRect(cmd[1], cmd[2], cmd[3], cmd[4]);
               break;
            case 5:
               ctx.fillRect(cmd[1], cmd[2], cmd[3], cmd[4]);
               break;
            case 6:
               ctx.beginPath();
               break;
            case 7:
               ctx.closePath();
               break;
            case 8:
               ctx.moveTo(cmd[1], cmd[2]);
               break;
            case 9:
               ctx.lineTo(cmd[1], cmd[2]);
               break;
            case 10:
               ctx.bezierCurveTo(cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6]);
               break;
            case 11:
               ctx.moveTo(cmd[1], cmd[2]);
               ctx.lineTo(cmd[3], cmd[4]);
               break;
            case 12:
               ctx.rect(cmd[1], cmd[2], cmd[3], cmd[4]);
               break;
            case 13:
               ctx.arc(cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6]);
               break;
            case 14:
               ctx.stroke();
               break;
            case 15:
               ctx.fill();
               break;
            case 16:
               ctx.clip();
               break;
            case 17:
               if (cmd[3])
                  for (j = 0; j < cmd[3].length; j += 2)
                     ctx.fillRect(cmd[3][j], cmd[3][j+1], cmd[1], cmd[2]);
               break;
            case 18:
               ctx.drawImage(cmd[1], cmd[2], cmd[3]);
               break;
            case 19:
               ctx.translate(cmd[1], cmd[2]);
               break;
            case 20:
               ctx.rotate(cmd[1]);
               break;
            case 21:
               ctx.scale(cmd[1], cmd[2]);
               break;
            case 22:
               ctx.save();
               break;
            case 23:
               ctx.restore();
               break;
            /*** Variables ***/
            case 24:
               ctx.fillStyle = cmd[1];
               break;
            case 25:
               ctx.strokeStyle = cmd[1];
               break;
            case 26:
               ctx.globalAlpha = cmd[1];
               break;
            case 27:
               ctx.lineWidth = cmd[1];
               break;
            case 28:
               ctx.lineCap = cmd[1];
               break;
            case 29:
               ctx.lineJoin = cmd[1];
               break;
            case 30:
               ctx.miterLimit = cmd[1];
               break;
            case 31:
               ctx.globalCompositeOperation = cmd[1];
               break;
            }
         }
      }
      if (dly >= 0)
         setTimeout(function() {drawCanvas(id, dly)}, dly);
   }
   try {req.send(null);}
   catch (e) {
      req.abort();
      return true;
   }
   return false;
}
<commit_msg>Comment 'requestAnimationFrame'<commit_after>/* 30aug13abu
 * (c) Software Lab. Alexander Burger
 */

function drawCanvas(id, dly) {
   var req = new XMLHttpRequest();

   try {
      req.open("POST",
         document.getElementsByTagName("BASE")[0].href + SesId +
         "!jsDraw?" + id + "&+" + dly);
      req.responseType = "arraybuffer";
   }
   catch (e) {return true;}
   req.onload = function() {
      var lst = plio(new Uint8Array(req.response));
      var cmd, i, j;

      if (lst) {
         var ctx = document.getElementById(id).getContext("2d");

         for (i = 0; i < lst.length; ++i) {
            switch ((cmd = lst[i])[0]) {  // In sync with "@lib/canvas.l"
            /*** Functions ***/
            case 1:
               ctx.fillText(cmd[1], cmd[2], cmd[3]);
               break;
            case 2:
               ctx.beginPath();
               ctx.moveTo(cmd[1], cmd[2]);
               ctx.lineTo(cmd[3], cmd[4]);
               ctx.closePath();
               ctx.stroke();
               break;
            case 3:
               ctx.clearRect(cmd[1], cmd[2], cmd[3], cmd[4]);
               break;
            case 4:
               ctx.strokeRect(cmd[1], cmd[2], cmd[3], cmd[4]);
               break;
            case 5:
               ctx.fillRect(cmd[1], cmd[2], cmd[3], cmd[4]);
               break;
            case 6:
               ctx.beginPath();
               break;
            case 7:
               ctx.closePath();
               break;
            case 8:
               ctx.moveTo(cmd[1], cmd[2]);
               break;
            case 9:
               ctx.lineTo(cmd[1], cmd[2]);
               break;
            case 10:
               ctx.bezierCurveTo(cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6]);
               break;
            case 11:
               ctx.moveTo(cmd[1], cmd[2]);
               ctx.lineTo(cmd[3], cmd[4]);
               break;
            case 12:
               ctx.rect(cmd[1], cmd[2], cmd[3], cmd[4]);
               break;
            case 13:
               ctx.arc(cmd[1], cmd[2], cmd[3], cmd[4], cmd[5], cmd[6]);
               break;
            case 14:
               ctx.stroke();
               break;
            case 15:
               ctx.fill();
               break;
            case 16:
               ctx.clip();
               break;
            case 17:
               if (cmd[3])
                  for (j = 0; j < cmd[3].length; j += 2)
                     ctx.fillRect(cmd[3][j], cmd[3][j+1], cmd[1], cmd[2]);
               break;
            case 18:
               ctx.drawImage(cmd[1], cmd[2], cmd[3]);
               break;
            case 19:
               ctx.translate(cmd[1], cmd[2]);
               break;
            case 20:
               ctx.rotate(cmd[1]);
               break;
            case 21:
               ctx.scale(cmd[1], cmd[2]);
               break;
            case 22:
               ctx.save();
               break;
            case 23:
               ctx.restore();
               break;
            /*** Variables ***/
            case 24:
               ctx.fillStyle = cmd[1];
               break;
            case 25:
               ctx.strokeStyle = cmd[1];
               break;
            case 26:
               ctx.globalAlpha = cmd[1];
               break;
            case 27:
               ctx.lineWidth = cmd[1];
               break;
            case 28:
               ctx.lineCap = cmd[1];
               break;
            case 29:
               ctx.lineJoin = cmd[1];
               break;
            case 30:
               ctx.miterLimit = cmd[1];
               break;
            case 31:
               ctx.globalCompositeOperation = cmd[1];
               break;
            }
         }
      }
      // if (dly == 0)
      //    requestAnimationFrame(function() {drawCanvas(id, dly)});
      // else if (dly > 0)
      //    setTimeout(function() {drawCanvas(id, dly)}, dly);
      if (dly >= 0)
         setTimeout(function() {drawCanvas(id, dly)}, dly);
   }
   try {req.send(null);}
   catch (e) {
      req.abort();
      return true;
   }
   return false;
}
<|endoftext|>


<commit_before>
/*!
 * Jade - Lexer
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Initialize `Lexer` with the given `str`.
 *
 * Options:
 *
 *   - `colons` allow colons for attr delimiters
 *
 * @param {String} str
 * @param {Object} options
 * @api private
 */

var Lexer = module.exports = function Lexer(str, options) {
  options = options || {};
  this.input = str.replace(/\r\n|\r/g, '\n');
  this.colons = options.colons;
  this.deferredTokens = [];
  this.lastIndents = 0;
  this.lineno = 1;
  this.stash = [];
  this.indentStack = [];
  this.indentRe = null;
  this.pipeless = false;
};

/**
 * Lexer prototype.
 */

Lexer.prototype = {

  /**
   * Construct a token with the given `type` and `val`.
   *
   * @param {String} type
   * @param {String} val
   * @return {Object}
   * @api private
   */

  tok: function(type, val){
    return {
        type: type
      , line: this.lineno
      , val: val
    }
  },

  /**
   * Consume the given `len` of input.
   *
   * @param {Number} len
   * @api private
   */

  consume: function(len){
    this.input = this.input.substr(len);
  },

  /**
   * Scan for `type` with the given `regexp`.
   *
   * @param {String} type
   * @param {RegExp} regexp
   * @return {Object}
   * @api private
   */

  scan: function(regexp, type){
    var captures;
    if (captures = regexp.exec(this.input)) {
      this.consume(captures[0].length);
      return this.tok(type, captures[1]);
    }
  },

  /**
   * Defer the given `tok`.
   *
   * @param {Object} tok
   * @api private
   */

  defer: function(tok){
    this.deferredTokens.push(tok);
  },

  /**
   * Lookahead `n` tokens.
   *
   * @param {Number} n
   * @return {Object}
   * @api private
   */

  lookahead: function(n){
    var fetch = n - this.stash.length;
    while (fetch-- > 0) this.stash.push(this.next());
    return this.stash[--n];
  },

  /**
   * Return the indexOf `start` / `end` delimiters.
   *
   * @param {String} start
   * @param {String} end
   * @return {Number}
   * @api private
   */

  indexOfDelimiters: function(start, end){
    var str = this.input
      , nstart = 0
      , nend = 0
      , pos = 0;
    for (var i = 0, len = str.length; i < len; ++i) {
      if (start == str[i]) {
        ++nstart;
      } else if (end == str[i]) {
        if (++nend == nstart) {
          pos = i;
          break;
        }
      }
    }
    return pos;
  },

  /**
   * Stashed token.
   */

  stashed: function() {
    return this.stash.length
      && this.stash.shift();
  },

  /**
   * Deferred token.
   */

  deferred: function() {
    return this.deferredTokens.length
      && this.deferredTokens.shift();
  },

  /**
   * end-of-source.
   */

  eos: function() {
    if (this.input.length) return;
    if (this.indentStack.length) {
      this.indentStack.shift();
      return this.tok('outdent');
    } else {
      return this.tok('eos');
    }
  },

  /**
   * Comment.
   */

  comment: function() {
    var captures;
    if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) {
      this.consume(captures[0].length);
      var tok = this.tok('comment', captures[2]);
      tok.buffer = '-' != captures[1];
      return tok;
    }
  },

  /**
   * Tag.
   */

  tag: function() {
    var captures;
    if (captures = /^(\w[-:\w]*)/.exec(this.input)) {
      this.consume(captures[0].length);
      var tok, name = captures[1];
      if (':' == name[name.length - 1]) {
        name = name.slice(0, -1);
        tok = this.tok('tag', name);
        this.defer(this.tok(':'));
        while (' ' == this.input[0]) this.input = this.input.substr(1);
      } else {
        tok = this.tok('tag', name);
      }
      return tok;
    }
  },

  /**
   * Filter.
   */

  filter: function() {
    return this.scan(/^:(\w+)/, 'filter');
  },

  /**
   * Doctype.
   */

  doctype: function() {
    return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype');
  },

  /**
   * Id.
   */

  id: function() {
    return this.scan(/^#([\w-]+)/, 'id');
  },

  /**
   * Class.
   */

  className: function() {
    return this.scan(/^\.([\w-]+)/, 'class');
  },

  /**
   * Text.
   */

  text: function() {
    return this.scan(/^(?:\| ?)?([^\n]+)/, 'text');
  },

  /**
   * Extends.
   */

  extends: function() {
    return this.scan(/^extends +([^\n]+)/, 'extends');
  },

  /**
   * Block.
   */

  block: function() {
    return this.scan(/^block +([^\n]+)/, 'block');
  },

  /**
   * Include.
   */

  include: function() {
    return this.scan(/^include +([^\n]+)/, 'include');
  },

  /**
   * Assignment.
   */

  assignment: function() {
    var captures;
    if (captures = /^(\w+) += *([^\n]+)/.exec(this.input)) {
      this.consume(captures[0].length);
      var name = captures[1]
        , val = captures[2];
      return this.tok('code', 'var ' + name + ' = (' + val + ')');
    }
  },

  /**
   * Mixin.
   */

  mixin: function(){
    var captures;
    if (captures = /^mixin +([-\w]+)(?:\(([^\)]+)\))?/.exec(this.input)) {
      this.consume(captures[0].length);
      var tok = this.tok('mixin', captures[1]);
      tok.args = captures[2];
      return tok;
    }
  },

  /**
   * Conditional.
   */

  conditional: function() {
    var captures;
    if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) {
      this.consume(captures[0].length);
      var type = captures[1]
        , js = captures[2];

      switch (type) {
        case 'if': js = 'if (' + js + ')'; break;
        case 'unless': js = 'if (!(' + js + '))'; break;
        case 'else if': js = 'else if (' + js + ')'; break;
        case 'else': js = 'else'; break;
      }

      return this.tok('code', js);
    }
  },

  /**
   * While.
   */

  while: function() {
    var captures;
    if (captures = /^while +([^\n]+)/.exec(this.input)) {
      this.consume(captures[0].length);
      return this.tok('code', 'while (' + captures[1] + ')');
    }
  },

  /**
   * Each.
   */

  each: function() {
    var captures;
    if (captures = /^(?:- *)?(?:each|for) +(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) {
      this.consume(captures[0].length);
      var tok = this.tok('each', captures[1]);
      tok.key = captures[2] || '$index';
      tok.code = captures[3];
      return tok;
    }
  },

  /**
   * Code.
   */

  code: function() {
    var captures;
    if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) {
      this.consume(captures[0].length);
      var flags = captures[1];
      captures[1] = captures[2];
      var tok = this.tok('code', captures[1]);
      tok.escape = flags[0] === '=';
      tok.buffer = flags[0] === '=' || flags[1] === '=';
      return tok;
    }
  },

  /**
   * Attributes.
   */

  attrs: function() {
    if ('(' == this.input[0]) {
      var index = this.indexOfDelimiters('(', ')')
        , str = this.input.substr(1, index-1)
        , tok = this.tok('attrs')
        , len = str.length
        , colons = this.colons
        , states = ['key']
        , key = ''
        , val = ''
        , quote
        , c;

      function state(){
        return states[states.length - 1];
      }

      function interpolate(attr) {
        return attr.replace(/#\{([^}]+)\}/g, function(_, expr){
          return quote + " + (" + expr + ") + " + quote;
        });
      }

      this.consume(index + 1);
      tok.attrs = {};

      function parse(c) {
        var real = c;
        // TODO: remove when people fix ":"
        if (colons && ':' == c) c = '=';
        switch (c) {
          case ',':
          case '\n':
            switch (state()) {
              case 'expr':
              case 'array':
              case 'string':
              case 'object':
                val += c;
                break;
              default:
                states.push('key');
                val = val.trim();
                key = key.trim();
                if ('' == key) return;
                tok.attrs[key.replace(/^['"]|['"]$/g, '')] = '' == val
                  ? true
                  : interpolate(val);
                key = val = '';
            }
            break;
          case '=':
            switch (state()) {
              case 'key char':
                key += real;
                break;
              case 'val':
              case 'expr':
              case 'array':
              case 'string':
              case 'object':
                val += real;
                break;
              default:
                states.push('val');
            }
            break;
          case '(':
            if ('val' == state()) states.push('expr');
            val += c;
            break;
          case ')':
            if ('expr' == state()) states.pop();
            val += c;
            break;
          case '{':
            if ('val' == state()) states.push('object');
            val += c;
            break;
          case '}':
            if ('object' == state()) states.pop();
            val += c;
            break;
          case '[':
            if ('val' == state()) states.push('array');
            val += c;
            break;
          case ']':
            if ('array' == state()) states.pop();
            val += c;
            break;
          case '"':
          case "'":
            switch (state()) {
              case 'key':
                states.push('key char');
                break;
              case 'key char':
                states.pop();
                break;
              case 'string':
                if (c == quote) states.pop();
                val += c;
                break;
              default:
                states.push('string');
                val += c;
                quote = c;
            }
            break;
          case '':
            break;
          default:
            switch (state()) {
              case 'key':
              case 'key char':
                key += c;
                break;
              default:
                val += c;
            }
        }
      }

      for (var i = 0; i < len; ++i) {
        parse(str[i]);
      }

      parse(',');

      return tok;
    }
  },

  /**
   * Indent | Outdent | Newline.
   */

  indent: function() {
    var captures, re;

    // established regexp
    if (this.indentRe) {
      captures = this.indentRe.exec(this.input);
    // determine regexp
    } else {
      // tabs
      re = /^\n(\t*) */;
      captures = re.exec(this.input);

      // spaces
      if (captures && !captures[1].length) {
        re = /^\n( *)/;
        captures = re.exec(this.input);
      }

      // established
      if (captures && captures[1].length) this.indentRe = re;
    }

    if (captures) {
      var tok
        , indents = captures[1].length;

      ++this.lineno;
      this.consume(indents + 1);

      if (' ' == this.input[0] || '\t' == this.input[0]) {
        throw new Error('Invalid indentation, you can use tabs or spaces but not both');
      }

      // blank line
      if ('\n' == this.input[0]) return this.tok('newline');

      // outdent
      if (this.indentStack.length && indents < this.indentStack[0]) {
        while (this.indentStack.length && this.indentStack[0] > indents) {
          this.stash.push(this.tok('outdent'));
          this.indentStack.shift();
        }
        tok = this.stash.pop();
      // indent
      } else if (indents && indents != this.indentStack[0]) {
        this.indentStack.unshift(indents);
        tok = this.tok('indent', indents);
      // newline
      } else {
        tok = this.tok('newline');
      }

      return tok;
    }
  },

  /**
   * Pipe-less text consumed only when
   * pipeless is true;
   */

  pipelessText: function() {
    if (this.pipeless) {
      if ('\n' == this.input[0]) return;
      var i = this.input.indexOf('\n');
      if (-1 == i) i = this.input.length;
      var str = this.input.substr(0, i);
      this.consume(str.length);
      return this.tok('text', str);
    }
  },

  /**
   * ':'
   */

  colon: function() {
    return this.scan(/^: */, ':');
  },

  /**
   * Return the next token object, or those
   * previously stashed by lookahead.
   *
   * @return {Object}
   * @api private
   */

  advance: function(){
    return this.stashed()
      || this.next();
  },

  /**
   * Return the next token object.
   *
   * @return {Object}
   * @api private
   */

  next: function() {
    return this.deferred()
      || this.eos()
      || this.pipelessText()
      || this.doctype()
      || this.extends()
      || this.block()
      || this.include()
      || this.mixin()
      || this.conditional()
      || this.each()
      || this.while()
      || this.assignment()
      || this.tag()
      || this.filter()
      || this.code()
      || this.id()
      || this.className()
      || this.attrs()
      || this.indent()
      || this.comment()
      || this.colon()
      || this.text();
  }
};
<commit_msg>debug<commit_after>
/*!
 * Jade - Lexer
 * Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Initialize `Lexer` with the given `str`.
 *
 * Options:
 *
 *   - `colons` allow colons for attr delimiters
 *
 * @param {String} str
 * @param {Object} options
 * @api private
 */

var Lexer = module.exports = function Lexer(str, options) {
  options = options || {};
  this.input = str.replace(/\r\n|\r/g, '\n');
  this.colons = options.colons;
  this.deferredTokens = [];
  this.lastIndents = 0;
  this.lineno = 1;
  this.stash = [];
  this.indentStack = [];
  this.indentRe = null;
  this.pipeless = false;
};

/**
 * Lexer prototype.
 */

Lexer.prototype = {

  /**
   * Construct a token with the given `type` and `val`.
   *
   * @param {String} type
   * @param {String} val
   * @return {Object}
   * @api private
   */

  tok: function(type, val){
    return {
        type: type
      , line: this.lineno
      , val: val
    }
  },

  /**
   * Consume the given `len` of input.
   *
   * @param {Number} len
   * @api private
   */

  consume: function(len){
    this.input = this.input.substr(len);
  },

  /**
   * Scan for `type` with the given `regexp`.
   *
   * @param {String} type
   * @param {RegExp} regexp
   * @return {Object}
   * @api private
   */

  scan: function(regexp, type){
    var captures;
    if (captures = regexp.exec(this.input)) {
      this.consume(captures[0].length);
      return this.tok(type, captures[1]);
    }
  },

  /**
   * Defer the given `tok`.
   *
   * @param {Object} tok
   * @api private
   */

  defer: function(tok){
    this.deferredTokens.push(tok);
  },

  /**
   * Lookahead `n` tokens.
   *
   * @param {Number} n
   * @return {Object}
   * @api private
   */

  lookahead: function(n){
    var fetch = n - this.stash.length;
    while (fetch-- > 0) this.stash.push(this.next());
    return this.stash[--n];
  },

  /**
   * Return the indexOf `start` / `end` delimiters.
   *
   * @param {String} start
   * @param {String} end
   * @return {Number}
   * @api private
   */

  indexOfDelimiters: function(start, end){
    var str = this.input
      , nstart = 0
      , nend = 0
      , pos = 0;
    for (var i = 0, len = str.length; i < len; ++i) {
      if (start == str[i]) {
        ++nstart;
      } else if (end == str[i]) {
        if (++nend == nstart) {
          pos = i;
          break;
        }
      }
    }
    return pos;
  },

  /**
   * Stashed token.
   */

  stashed: function() {
    return this.stash.length
      && this.stash.shift();
  },

  /**
   * Deferred token.
   */

  deferred: function() {
    return this.deferredTokens.length
      && this.deferredTokens.shift();
  },

  /**
   * end-of-source.
   */

  eos: function() {
    if (this.input.length) return;
    if (this.indentStack.length) {
      this.indentStack.shift();
      return this.tok('outdent');
    } else {
      return this.tok('eos');
    }
  },

  /**
   * Comment.
   */

  comment: function() {
    var captures;
    if (captures = /^ *\/\/(-)?([^\n]*)/.exec(this.input)) {
      this.consume(captures[0].length);
      var tok = this.tok('comment', captures[2]);
      tok.buffer = '-' != captures[1];
      return tok;
    }
  },

  /**
   * Tag.
   */

  tag: function() {
    var captures;
    if (captures = /^(\w[-:\w]*)/.exec(this.input)) {
      this.consume(captures[0].length);
      var tok, name = captures[1];
      if (':' == name[name.length - 1]) {
        name = name.slice(0, -1);
        tok = this.tok('tag', name);
        this.defer(this.tok(':'));
        while (' ' == this.input[0]) this.input = this.input.substr(1);
      } else {
        tok = this.tok('tag', name);
      }
      return tok;
    }
  },

  /**
   * Filter.
   */

  filter: function() {
    return this.scan(/^:(\w+)/, 'filter');
  },

  /**
   * Doctype.
   */

  doctype: function() {
    return this.scan(/^(?:!!!|doctype) *([^\n]+)?/, 'doctype');
  },

  /**
   * Id.
   */

  id: function() {
    return this.scan(/^#([\w-]+)/, 'id');
  },

  /**
   * Class.
   */

  className: function() {
    return this.scan(/^\.([\w-]+)/, 'class');
  },

  /**
   * Text.
   */

  text: function() {
    return this.scan(/^(?:\| ?)?([^\n]+)/, 'text');
  },

  /**
   * Extends.
   */

  extends: function() {
    return this.scan(/^extends +([^\n]+)/, 'extends');
  },

  /**
   * Block.
   */

  block: function() {
    return this.scan(/^block +([^\n]+)/, 'block');
  },

  /**
   * Include.
   */

  include: function() {
    return this.scan(/^include +([^\n]+)/, 'include');
  },

  /**
   * Assignment.
   */

  assignment: function() {
    var captures;
    if (captures = /^(\w+) += *([^\n]+)/.exec(this.input)) {
      this.consume(captures[0].length);
      var name = captures[1]
        , val = captures[2];
      return this.tok('code', 'var ' + name + ' = (' + val + ')');
    }
  },

  /**
   * Mixin.
   */

  mixin: function(){
    var captures;
    if (captures = /^mixin +([-\w]+)(?:\(([^\)]+)\))?/.exec(this.input)) {
      this.consume(captures[0].length);
      var tok = this.tok('mixin', captures[1]);
      tok.args = captures[2];
      return tok;
    }
  },

  /**
   * Conditional.
   */

  conditional: function() {
    var captures;
    if (captures = /^(if|unless|else if|else)\b([^\n]*)/.exec(this.input)) {
      this.consume(captures[0].length);
      var type = captures[1]
        , js = captures[2];

      switch (type) {
        case 'if': js = 'if (' + js + ')'; break;
        case 'unless': js = 'if (!(' + js + '))'; break;
        case 'else if': js = 'else if (' + js + ')'; break;
        case 'else': js = 'else'; break;
      }

      return this.tok('code', js);
    }
  },

  /**
   * While.
   */

  while: function() {
    var captures;
    if (captures = /^while +([^\n]+)/.exec(this.input)) {
      this.consume(captures[0].length);
      return this.tok('code', 'while (' + captures[1] + ')');
    }
  },

  /**
   * Each.
   */

  each: function() {
    var captures;
    if (captures = /^(?:- *)?(?:each|for) +(\w+)(?: *, *(\w+))? * in *([^\n]+)/.exec(this.input)) {
      this.consume(captures[0].length);
      var tok = this.tok('each', captures[1]);
      tok.key = captures[2] || '$index';
      tok.code = captures[3];
      return tok;
    }
  },

  /**
   * Code.
   */

  code: function() {
    var captures;
    if (captures = /^(!?=|-)([^\n]+)/.exec(this.input)) {
      this.consume(captures[0].length);
      var flags = captures[1];
      captures[1] = captures[2];
      var tok = this.tok('code', captures[1]);
      tok.escape = flags[0] === '=';
      tok.buffer = flags[0] === '=' || flags[1] === '=';
      return tok;
    }
  },

  /**
   * Attributes.
   */

  attrs: function() {
    if ('(' == this.input[0]) {
      var index = this.indexOfDelimiters('(', ')')
        , str = this.input.substr(1, index-1)
        , tok = this.tok('attrs')
        , len = str.length
        , colons = this.colons
        , states = ['key']
        , key = ''
        , val = ''
        , quote
        , c;

      function state(){
        return states[states.length - 1];
      }

      function interpolate(attr) {
        return attr.replace(/#\{([^}]+)\}/g, function(_, expr){
          return quote + " + (" + expr + ") + " + quote;
        });
      }

      this.consume(index + 1);
      tok.attrs = {};

      function parse(c) {
        var real = c;
        // TODO: remove when people fix ":"
        if (colons && ':' == c) c = '=';
        // console.log('', c, state());
        switch (c) {
          case ',':
          case '\n':
            switch (state()) {
              case 'expr':
              case 'array':
              case 'string':
              case 'object':
                val += c;
                break;
              default:
                states.push('key');
                val = val.trim();
                key = key.trim();
                if ('' == key) return;
                tok.attrs[key.replace(/^['"]|['"]$/g, '')] = '' == val
                  ? true
                  : interpolate(val);
                key = val = '';
            }
            break;
          case '=':
            switch (state()) {
              case 'key char':
                key += real;
                break;
              case 'val':
              case 'expr':
              case 'array':
              case 'string':
              case 'object':
                val += real;
                break;
              default:
                states.push('val');
            }
            break;
          case '(':
            if ('val' == state()) states.push('expr');
            val += c;
            break;
          case ')':
            if ('expr' == state()) states.pop();
            val += c;
            break;
          case '{':
            if ('val' == state()) states.push('object');
            val += c;
            break;
          case '}':
            if ('object' == state()) states.pop();
            val += c;
            break;
          case '[':
            if ('val' == state()) states.push('array');
            val += c;
            break;
          case ']':
            if ('array' == state()) states.pop();
            val += c;
            break;
          case '"':
          case "'":
            switch (state()) {
              case 'key':
                states.push('key char');
                break;
              case 'key char':
                states.pop();
                break;
              case 'string':
                if (c == quote) states.pop();
                val += c;
                break;
              default:
                states.push('string');
                val += c;
                quote = c;
            }
            break;
          case '':
            break;
          default:
            switch (state()) {
              case 'key':
              case 'key char':
                key += c;
                break;
              default:
                val += c;
            }
        }
      }

      for (var i = 0; i < len; ++i) {
        parse(str[i]);
      }

      parse(',');

      return tok;
    }
  },

  /**
   * Indent | Outdent | Newline.
   */

  indent: function() {
    var captures, re;

    // established regexp
    if (this.indentRe) {
      captures = this.indentRe.exec(this.input);
    // determine regexp
    } else {
      // tabs
      re = /^\n(\t*) */;
      captures = re.exec(this.input);

      // spaces
      if (captures && !captures[1].length) {
        re = /^\n( *)/;
        captures = re.exec(this.input);
      }

      // established
      if (captures && captures[1].length) this.indentRe = re;
    }

    if (captures) {
      var tok
        , indents = captures[1].length;

      ++this.lineno;
      this.consume(indents + 1);

      if (' ' == this.input[0] || '\t' == this.input[0]) {
        throw new Error('Invalid indentation, you can use tabs or spaces but not both');
      }

      // blank line
      if ('\n' == this.input[0]) return this.tok('newline');

      // outdent
      if (this.indentStack.length && indents < this.indentStack[0]) {
        while (this.indentStack.length && this.indentStack[0] > indents) {
          this.stash.push(this.tok('outdent'));
          this.indentStack.shift();
        }
        tok = this.stash.pop();
      // indent
      } else if (indents && indents != this.indentStack[0]) {
        this.indentStack.unshift(indents);
        tok = this.tok('indent', indents);
      // newline
      } else {
        tok = this.tok('newline');
      }

      return tok;
    }
  },

  /**
   * Pipe-less text consumed only when
   * pipeless is true;
   */

  pipelessText: function() {
    if (this.pipeless) {
      if ('\n' == this.input[0]) return;
      var i = this.input.indexOf('\n');
      if (-1 == i) i = this.input.length;
      var str = this.input.substr(0, i);
      this.consume(str.length);
      return this.tok('text', str);
    }
  },

  /**
   * ':'
   */

  colon: function() {
    return this.scan(/^: */, ':');
  },

  /**
   * Return the next token object, or those
   * previously stashed by lookahead.
   *
   * @return {Object}
   * @api private
   */

  advance: function(){
    return this.stashed()
      || this.next();
  },

  /**
   * Return the next token object.
   *
   * @return {Object}
   * @api private
   */

  next: function() {
    return this.deferred()
      || this.eos()
      || this.pipelessText()
      || this.doctype()
      || this.extends()
      || this.block()
      || this.include()
      || this.mixin()
      || this.conditional()
      || this.each()
      || this.while()
      || this.assignment()
      || this.tag()
      || this.filter()
      || this.code()
      || this.id()
      || this.className()
      || this.attrs()
      || this.indent()
      || this.comment()
      || this.colon()
      || this.text();
  }
};
<|endoftext|>


<commit_before>// Either supply the location of the config file in the argument or default to it being in the same folder as the script
// Consts
const CONFIG = require(process.argv[2] || './config.json');

// Dependencies
const fs = require('fs');
const path = require('path');
const modeljson = require(CONFIG.PATH_TO_MODELS_JSON);

let modelJSONEntities = modeljson.Entities;

console.log("\nOriginal entity length: ", modelJSONEntities.length, "\n");

// Map the entities to help entity lookup
let parentMap = {};
modelJSONEntities.forEach(ent => {
    parentMap[ent.id] = ent;
})

// Counters
let countNameBlackListGroup = 0;
let countNameWhiteListGroup = 0;
let countPatternMatchBlackListGroup = 0;
let countPatternMatchWhiteListGroup = 0;
let countTypeBlackListGroup = 0;
let countTypeWhiteListGroup = 0;
let countInBound = 0;
let countOutBound = 0;
let countParentInBound = 0;
let countParentOutBound = 0;
let countNoParentInDomain = 0;
let countRemainingKeeps = 0;

// Name black list
let nameBlackListGroup = CONFIG.nameBlackListGroup;
console.log("\nnameBlackListGroup: \n", nameBlackListGroup, "\n");

// Name white list
let nameWhiteListGroup = CONFIG.nameWhiteListGroup;
console.log("\nnameWhiteListGroup: \n", nameWhiteListGroup, "\n");

// Type black list
let typeBlackListGroup = CONFIG.typeBlackListGroup;
console.log("\ntypeBlackListGroup: \n", typeBlackListGroup, "\n");

// Type white list
let typeWhiteListGroup = CONFIG.typeWhiteListGroup;
console.log("\ntypeWhiteListGroup: \n", typeWhiteListGroup, "\n");

// Pattern match black list
let patternMatchBlackListGroup = CONFIG.patternMatchBlackListGroup;
console.log("\npatternMatchBlackListGroup: \n", patternMatchBlackListGroup, "\n");

// Pattern match white list
let patternMatchWhiteListGroup = CONFIG.patternMatchWhiteListGroup;
console.log("\npatternMatchWhiteListGroup: \n", patternMatchWhiteListGroup, "\n");

// Main entity filter
modelJSONEntities = modelJSONEntities.filter( ent => {

    // Name black list
    for (var i = 0; i < nameBlackListGroup.length; i++){
        if (ent.name && ent.name.toLowerCase() === nameBlackListGroup[i].toLowerCase()) {
            countNameBlackListGroup++;
            return false;
        }
    }
    // Name white list
    for (i = 0; i < nameWhiteListGroup.length; i++){
        if (ent.name && ent.name.toLowerCase() === nameWhiteListGroup[i].toLowerCase()) {
            countNameWhiteListGroup++;
            return true;
        }
    }

    // Pattern match black list
    for (i = 0; i < patternMatchBlackListGroup.length; i++){
        if (ent.name && ent.name.toLowerCase().indexOf(patternMatchBlackListGroup[i].toLowerCase()) > -1) {
            countPatternMatchBlackListGroup++;
            return false;
        }
    }
    // Pattern match white list
    for (i = 0; i < patternMatchWhiteListGroup.length; i++){
        if (ent.name && ent.name.toLowerCase().indexOf(patternMatchWhiteListGroup[i].toLowerCase()) > -1) {
            countPatternMatchWhiteListGroup++;
            return true;
        }
    }

    // Type black list
    for (var i = 0; i < typeBlackListGroup.length; i++){
        if (ent.type && ent.type.toLowerCase() === typeBlackListGroup[i].toLowerCase()) {
            countTypeBlackListGroup++;
            return false;
        }
    }
    // Type white list
    for (i = 0; i < typeWhiteListGroup.length; i++){
        if (ent.type.toLowerCase() === typeWhiteListGroup[i].toLowerCase()) {
            countTypeWhiteListGroup++;
            return true;
        }
    }

    // Entities with Parents
    if (ent.parentID) {
        let parentID = ent.parentID;
        let parent = parentMap[parentID];
        if (!parent) {
            countNoParentInDomain++;
            // Entity has a parentID, but there is no parent in the domain so delelte it
            return false;
        }
        if (parent.position) {
            // Delete anything with a parent that is in bounds
            if (
                (parent.position.x < CONFIG.MAX_X && parent.position.x > CONFIG.MIN_X) &&
                (parent.position.y < CONFIG.MAX_Y && parent.position.y > CONFIG.MIN_Y) &&
                (parent.position.z < CONFIG.MAX_Z && parent.position.z > CONFIG.MIN_Z)
            ) {
                countParentInBound++;
                return true;
            } else {
                countParentOutBound++;
                return false;
            }
        }
    } else if (ent.position) {
    // Entities without Parents

            // Delete anything with a parent that is in bounds
            if (
                (ent.position.x < CONFIG.MAX_X && ent.position.x > CONFIG.MIN_X) &&

                (ent.position.y < CONFIG.MAX_Y && ent.position.y > CONFIG.MIN_Y) &&
                (ent.position.z < CONFIG.MAX_Z && ent.position.z > CONFIG.MIN_Z)
            ) {
                countInBound++
                return true;
            } else {
                countOutBound++
                return false;
            }
    }

    // Otherwise keep the entity
    countRemainingKeeps++;
    return true;
})

// Stats
console.log("countNameBlackListGroup: ", countNameBlackListGroup);
console.log("countNameWhiteListGroup: ", countNameWhiteListGroup);
console.log("countPatternMatchBlackListGroup: ", countPatternMatchBlackListGroup);
console.log("countPatternMatchWhiteListGroup: ", countPatternMatchWhiteListGroup);
console.log("countTypeBlackListGroup: ", countTypeBlackListGroup);
console.log("countTypeWhiteListGroup: ", countTypeWhiteListGroup);
console.log("countInBound: ", countInBound);
console.log("countOutBound: ", countOutBound);
console.log("countParentInBound: ", countParentInBound);
console.log("countParentOutBound: ", countParentOutBound);
console.log("countNoParentInDomain: ", countNoParentInDomain);
console.log("countRemainingKeeps: ", countRemainingKeeps);
console.log("\nFinal ent Length: ", modelJSONEntities.length, "\n");

// Sum of deletes
var deletes = [countOutBound, countParentOutBound, countNameBlackListGroup, countTypeBlackListGroup, countNoParentInDomain, countPatternMatchBlackListGroup].reduce( (prev, curr) => {
    return prev += curr;
}, 0);
console.log("total Deletes: ", deletes);
// Sum of Keeps
var keeps = [countInBound, countParentInBound, countNameWhiteListGroup, countTypeWhiteListGroup, countPatternMatchWhiteListGroup, countRemainingKeeps].reduce( (prev, curr) => {
    return prev += curr;
}, 0);
console.log("total Keeps: ", keeps);

// Replace the filtered entities in the models.json
modeljson.Entities = modelJSONEntities;

// Write the new models json to disk with a new file name in case we need to run this again on the original list
let jsonToWrite = JSON.stringify(modeljson, null, 4);
fs.writeFileSync(path.join(__dirname, CONFIG.PATH_TO_WRITE_JSON), jsonToWrite);<commit_msg>Update usefulUtilities/modelJSONCleanup/modelJSONCleanup.js<commit_after>// Either supply the location of the config file in the argument or default to it being in the same folder as the script
// Consts
const CONFIG = require(process.argv[2] || './config.json');

// Dependencies
const fs = require('fs');
const path = require('path');
const modeljson = require(CONFIG.PATH_TO_MODELS_JSON);

let modelJSONEntities = modeljson.Entities;

console.log("\nOriginal entity length: ", modelJSONEntities.length, "\n");

// Map the entities to help entity lookup
let parentMap = {};
modelJSONEntities.forEach(ent => {
    parentMap[ent.id] = ent;
})

// Counters
let countNameBlackListGroup = 0;
let countNameWhiteListGroup = 0;
let countPatternMatchBlackListGroup = 0;
let countPatternMatchWhiteListGroup = 0;
let countTypeBlackListGroup = 0;
let countTypeWhiteListGroup = 0;
let countInBound = 0;
let countOutBound = 0;
let countParentInBound = 0;
let countParentOutBound = 0;
let countNoParentInDomain = 0;
let countRemainingKeeps = 0;

// Name black list
let nameBlackListGroup = CONFIG.nameBlackListGroup;
console.log("\nnameBlackListGroup: \n", nameBlackListGroup, "\n");

// Name white list
let nameWhiteListGroup = CONFIG.nameWhiteListGroup;
console.log("\nnameWhiteListGroup: \n", nameWhiteListGroup, "\n");

// Type black list
let typeBlackListGroup = CONFIG.typeBlackListGroup;
console.log("\ntypeBlackListGroup: \n", typeBlackListGroup, "\n");

// Type white list
let typeWhiteListGroup = CONFIG.typeWhiteListGroup;
console.log("\ntypeWhiteListGroup: \n", typeWhiteListGroup, "\n");

// Pattern match black list
let patternMatchBlackListGroup = CONFIG.patternMatchBlackListGroup;
console.log("\npatternMatchBlackListGroup: \n", patternMatchBlackListGroup, "\n");

// Pattern match white list
let patternMatchWhiteListGroup = CONFIG.patternMatchWhiteListGroup;
console.log("\npatternMatchWhiteListGroup: \n", patternMatchWhiteListGroup, "\n");

// Main entity filter
modelJSONEntities = modelJSONEntities.filter( ent => {

    // Name black list
    for (var i = 0; i < nameBlackListGroup.length; i++){
        if (ent.name && ent.name.toLowerCase() === nameBlackListGroup[i].toLowerCase()) {
            countNameBlackListGroup++;
            return false;
        }
    }
    // Name white list
    for (i = 0; i < nameWhiteListGroup.length; i++){
        if (ent.name && ent.name.toLowerCase() === nameWhiteListGroup[i].toLowerCase()) {
            countNameWhiteListGroup++;
            return true;
        }
    }

    // Pattern match black list
    for (i = 0; i < patternMatchBlackListGroup.length; i++){
        if (ent.name && ent.name.toLowerCase().indexOf(patternMatchBlackListGroup[i].toLowerCase()) > -1) {
            countPatternMatchBlackListGroup++;
            return false;
        }
    }
    // Pattern match white list
    for (i = 0; i < patternMatchWhiteListGroup.length; i++){
        if (ent.name && ent.name.toLowerCase().indexOf(patternMatchWhiteListGroup[i].toLowerCase()) > -1) {
            countPatternMatchWhiteListGroup++;
            return true;
        }
    }

    // Type black list
    for (var i = 0; i < typeBlackListGroup.length; i++){
        if (ent.type && ent.type.toLowerCase() === typeBlackListGroup[i].toLowerCase()) {
            countTypeBlackListGroup++;
            return false;
        }
    }
    // Type white list
    for (i = 0; i < typeWhiteListGroup.length; i++){
        if (ent.type.toLowerCase() === typeWhiteListGroup[i].toLowerCase()) {
            countTypeWhiteListGroup++;
            return true;
        }
    }

    // Entities with Parents
    if (ent.parentID) {
        let parentID = ent.parentID;
        let parent = parentMap[parentID];
        if (!parent) {
            countNoParentInDomain++;
            // Entity has a parentID, but there is no parent in the domain so delete it
            return false;
        }
        if (parent.position) {
            // Delete anything with a parent that is in bounds
            if (
                (parent.position.x < CONFIG.MAX_X && parent.position.x > CONFIG.MIN_X) &&
                (parent.position.y < CONFIG.MAX_Y && parent.position.y > CONFIG.MIN_Y) &&
                (parent.position.z < CONFIG.MAX_Z && parent.position.z > CONFIG.MIN_Z)
            ) {
                countParentInBound++;
                return true;
            } else {
                countParentOutBound++;
                return false;
            }
        }
    } else if (ent.position) {
    // Entities without Parents

            // Delete anything with a parent that is in bounds
            if (
                (ent.position.x < CONFIG.MAX_X && ent.position.x > CONFIG.MIN_X) &&

                (ent.position.y < CONFIG.MAX_Y && ent.position.y > CONFIG.MIN_Y) &&
                (ent.position.z < CONFIG.MAX_Z && ent.position.z > CONFIG.MIN_Z)
            ) {
                countInBound++
                return true;
            } else {
                countOutBound++
                return false;
            }
    }

    // Otherwise keep the entity
    countRemainingKeeps++;
    return true;
})

// Stats
console.log("countNameBlackListGroup: ", countNameBlackListGroup);
console.log("countNameWhiteListGroup: ", countNameWhiteListGroup);
console.log("countPatternMatchBlackListGroup: ", countPatternMatchBlackListGroup);
console.log("countPatternMatchWhiteListGroup: ", countPatternMatchWhiteListGroup);
console.log("countTypeBlackListGroup: ", countTypeBlackListGroup);
console.log("countTypeWhiteListGroup: ", countTypeWhiteListGroup);
console.log("countInBound: ", countInBound);
console.log("countOutBound: ", countOutBound);
console.log("countParentInBound: ", countParentInBound);
console.log("countParentOutBound: ", countParentOutBound);
console.log("countNoParentInDomain: ", countNoParentInDomain);
console.log("countRemainingKeeps: ", countRemainingKeeps);
console.log("\nFinal ent Length: ", modelJSONEntities.length, "\n");

// Sum of deletes
var deletes = [countOutBound, countParentOutBound, countNameBlackListGroup, countTypeBlackListGroup, countNoParentInDomain, countPatternMatchBlackListGroup].reduce( (prev, curr) => {
    return prev += curr;
}, 0);
console.log("total Deletes: ", deletes);
// Sum of Keeps
var keeps = [countInBound, countParentInBound, countNameWhiteListGroup, countTypeWhiteListGroup, countPatternMatchWhiteListGroup, countRemainingKeeps].reduce( (prev, curr) => {
    return prev += curr;
}, 0);
console.log("total Keeps: ", keeps);

// Replace the filtered entities in the models.json
modeljson.Entities = modelJSONEntities;

// Write the new models json to disk with a new file name in case we need to run this again on the original list
let jsonToWrite = JSON.stringify(modeljson, null, 4);
fs.writeFileSync(path.join(__dirname, CONFIG.PATH_TO_WRITE_JSON), jsonToWrite);
<|endoftext|>


<commit_before>var CookieGiveBoxProto = Object.create(HTMLInputElement.prototype);

CookieGiveBoxProto.createdCallback = function() {
  var self = this;

  self.style.position = 'fixed';
  self.style.bottom = '0em';
  self.style.right = '0em';
  self.style.backgroundColor = 'white';

  function flash(color) {
    self.style.backgroundColor = color;

    function setWhite() { self.style.backgroundColor = 'white'; }
    setTimeout(setWhite, 300);
  }

  function error(state) {
    if (state == true) {
      flash('red');
    }

    if (state == false) {
      flash('lime');
    }
  }

  function addCookies() {
    var n = self.value;
    if ( !isNaN(+n) ) {
      Game.Earn(+n);
      error(false);
    } else {
      error(true);
    }
  }

  self.addEventListener('change', addCookies);
};

var CookieGiveBox = document.registerElement('hacks-cookiegivebox', {
  prototype: CookieGiveBoxProto,
  extends: 'input'
});

document.body.appendChild(new CookieGiveBox());
<commit_msg>change to keypress-based status updates<commit_after>var CookieGiveBoxProto = Object.create(HTMLInputElement.prototype);

CookieGiveBoxProto.createdCallback = function() {
  var elm = this;

  elm.style.position = 'fixed';
  elm.style.bottom = '0em';
  elm.style.right = '0em';
  elm.style.backgroundColor = 'white';

  function status(color) {
    elm.style.backgroundColor = color;
  }

  function enter() {
    var n = +elm.value;
    function isValid(n) {
      if ( !isNaN(n) ) {
        return true;
      } else {
        return false;
      }
    }

    if ( isValid(n) ) {
      Game.Earn(n);
      status('lime');
    } else {
      status('red');
    }
  }

  function reset() {
    status('white');
  }

  function keyHandler(event) {
    var key = event.keyCode;
    if (key == 13) { //enter
      enter();
    }

    if (key == 8 || key == 46) { //backspace or delete
      reset();
    }
  }

  elm.addEventListener('keydown', keyHandler);
};

var CookieGiveBox = document.registerElement('hacks-cookiegivebox', {
  prototype: CookieGiveBoxProto,
  extends: 'input'
});

document.body.appendChild(new CookieGiveBox());
<|endoftext|>


<commit_before>var assert = require('assert'),
    polyline = require('../');

describe('polyline', function() {
    var example = [[38.5, -120.2], [40.7, -120.95], [43.252, -126.453]],
        // encoded value will enclude slashes -> tests escaping
        example_slashes = [[35.6,-82.55], [35.59985, -82.55015], [35.6,-82.55]],
        example_flipped = [[-120.2, 38.5], [-120.95, 40.7], [-126.453, 43.252]];
        geojson = { "type": "Feature",
            "geometry": {
                "type": "LineString",
                "coordinates": example_flipped
            },
            "properties": {}
        }

    describe('#decode()', function() {
        it('decodes an empty Array', function() {
            assert.deepEqual(polyline.decode(''), []);
        });

        it('decodes a String into an Array of lat/lon pairs', function() {
            assert.deepEqual(polyline.decode('_p~iF~ps|U_ulLnnqC_mqNvxq`@'), example);
        });

        it('decodes with a custom precision', function() {
            assert.deepEqual(polyline.decode('_izlhA~rlgdF_{geC~ywl@_kwzCn`{nI', 6), example);
        });
    });

    describe("#identity", function() {
      it('feed encode into decode and check if the result is the same as the input', function() {
        assert.deepEqual(polyline.decode(polyline.encode(example_slashes)), example_slashes);
      });

      it('feed decode into encode and check if the result is the same as the input', function() {
        assert.equal(polyline.encode(polyline.decode("_chxEn`zvN\\\\]]")), "_chxEn`zvN\\\\]]");
      });
    });

    describe('#encode()', function() {
        it('encodes an empty Array', function() {
            assert.equal(polyline.encode([]), '');
        });

        it('encodes an Array of lat/lon pairs into a String', function() {
            assert.equal(polyline.encode(example), '_p~iF~ps|U_ulLnnqC_mqNvxq`@');
        });

        it('encodes with a custom precision', function() {
            assert.equal(polyline.encode(example, 6), '_izlhA~rlgdF_{geC~ywl@_kwzCn`{nI');
        });
    });

    describe('#fromGeoJSON()', function() {
        it('throws for non linestrings', function() {
            assert.throws(function() {
                polyline.fromGeoJSON({});
            }, /Input must be a GeoJSON LineString/);
        });
        console.log(geojson.geometry);

        it('allows geojson geometries', function() {
            assert.equal(polyline.fromGeoJSON(geojson.geometry), '_p~iF~ps|U_ulLnnqC_mqNvxq`@')
        })

        it('flips coordinates and encodes', function() {
            assert.equal(polyline.fromGeoJSON(geojson), '_p~iF~ps|U_ulLnnqC_mqNvxq`@');
        });
    });

});
<commit_msg>Remove stray console.log<commit_after>var assert = require('assert'),
    polyline = require('../');

describe('polyline', function() {
    var example = [[38.5, -120.2], [40.7, -120.95], [43.252, -126.453]],
        // encoded value will enclude slashes -> tests escaping
        example_slashes = [[35.6,-82.55], [35.59985, -82.55015], [35.6,-82.55]],
        example_flipped = [[-120.2, 38.5], [-120.95, 40.7], [-126.453, 43.252]];
        geojson = { "type": "Feature",
            "geometry": {
                "type": "LineString",
                "coordinates": example_flipped
            },
            "properties": {}
        }

    describe('#decode()', function() {
        it('decodes an empty Array', function() {
            assert.deepEqual(polyline.decode(''), []);
        });

        it('decodes a String into an Array of lat/lon pairs', function() {
            assert.deepEqual(polyline.decode('_p~iF~ps|U_ulLnnqC_mqNvxq`@'), example);
        });

        it('decodes with a custom precision', function() {
            assert.deepEqual(polyline.decode('_izlhA~rlgdF_{geC~ywl@_kwzCn`{nI', 6), example);
        });
    });

    describe("#identity", function() {
      it('feed encode into decode and check if the result is the same as the input', function() {
        assert.deepEqual(polyline.decode(polyline.encode(example_slashes)), example_slashes);
      });

      it('feed decode into encode and check if the result is the same as the input', function() {
        assert.equal(polyline.encode(polyline.decode("_chxEn`zvN\\\\]]")), "_chxEn`zvN\\\\]]");
      });
    });

    describe('#encode()', function() {
        it('encodes an empty Array', function() {
            assert.equal(polyline.encode([]), '');
        });

        it('encodes an Array of lat/lon pairs into a String', function() {
            assert.equal(polyline.encode(example), '_p~iF~ps|U_ulLnnqC_mqNvxq`@');
        });

        it('encodes with a custom precision', function() {
            assert.equal(polyline.encode(example, 6), '_izlhA~rlgdF_{geC~ywl@_kwzCn`{nI');
        });
    });

    describe('#fromGeoJSON()', function() {
        it('throws for non linestrings', function() {
            assert.throws(function() {
                polyline.fromGeoJSON({});
            }, /Input must be a GeoJSON LineString/);
        });

        it('allows geojson geometries', function() {
            assert.equal(polyline.fromGeoJSON(geojson.geometry), '_p~iF~ps|U_ulLnnqC_mqNvxq`@')
        })

        it('flips coordinates and encodes', function() {
            assert.equal(polyline.fromGeoJSON(geojson), '_p~iF~ps|U_ulLnnqC_mqNvxq`@');
        });
    });

});
<|endoftext|>


<commit_before>'use babel';

/**
 * @author Titus Wormer
 * @copyright 2015 Titus Wormer
 * @license MIT
 * @module atom:linter-markdown
 * @fileoverview Linter.
 */

// eslint-disable-next-line import/no-extraneous-dependencies, import/extensions
import { CompositeDisposable } from 'atom';

const path = require('path');
const config = require('./config');

// Internal variables
let engine;
let processor;
let subscriptions;
const idleCallbacks = new Set();

// Settings
let scopes;
let detectIgnore;

const waitOnIdle = () =>
  new Promise((resolve) => {
    // Idle callbacks are done in FIFO order, so waiting on a newly queued idle
    // callback will ensure that the activation processes are completed
    const callbackID = window.requestIdleCallback(() => {
      idleCallbacks.delete(callbackID);
      resolve();
    });
    idleCallbacks.add(callbackID);
  });

async function lint(editor) {
  if (!processor) {
    await waitOnIdle();
  }

  return engine({
    processor,
    detectIgnore,
    rcName: '.remarkrc',
    rcPath: path.resolve(__dirname, 'config.js'),
    packageField: 'remarkConfig',
    ignoreName: '.remarkignore',
    presetPrefix: 'remark-preset',
    pluginPrefix: 'remark'
  })(editor);
}

/**
 * Linter-markdown.
 *
 * @return {LinterConfiguration}
 */
function provideLinter() {
  return {
    grammarScopes: scopes,
    name: 'remark-lint',
    scope: 'file',
    lintOnFly: true,
    lint
  };
}

function activate() {
  let callbackID;
  const installLinterMarkdownDeps = () => {
    idleCallbacks.delete(callbackID);

    // Install package dependencies
    if (!atom.inSpecMode()) {
      require('atom-package-deps').install('linter-markdown');
    }
    // Load required modules
    engine = require('unified-engine-atom');
    processor = require('remark');
  };

  // Defer this till an idle time as we don't need it immediately
  callbackID = window.requestIdleCallback(installLinterMarkdownDeps);
  idleCallbacks.add(callbackID);

  subscriptions = new CompositeDisposable();

  subscriptions.add(atom.config.observe('linter-markdown.scopes', (value) => {
    scopes = value;
  }));
  subscriptions.add(atom.config.observe('linter-markdown.detectIgnore', (value) => {
    detectIgnore = value;
  }));

  config.on();
}

function deactivate() {
  idleCallbacks.forEach(callbackID => window.cancleIdleCallback(callbackID));
  idleCallbacks.clear();
  subscriptions.dispose();

  config.off();
}

/*
 * Expose.
 */
module.exports = {
  activate,
  deactivate,
  provideLinter
};
<commit_msg>Require immediately if necessary<commit_after>'use babel';

/**
 * @author Titus Wormer
 * @copyright 2015 Titus Wormer
 * @license MIT
 * @module atom:linter-markdown
 * @fileoverview Linter.
 */

// eslint-disable-next-line import/no-extraneous-dependencies, import/extensions
import { CompositeDisposable } from 'atom';

const path = require('path');
const config = require('./config');

// Internal variables
let engine;
let processor;
let subscriptions;
const idleCallbacks = new Set();

// Settings
let scopes;
let detectIgnore;

function lint(editor) {
  // Load required modules if not already handled by init
  if (!engine) {
    engine = require('unified-engine-atom');
  }
  if (!processor) {
    processor = require('remark');
  }

  return engine({
    processor,
    detectIgnore,
    rcName: '.remarkrc',
    rcPath: path.resolve(__dirname, 'config.js'),
    packageField: 'remarkConfig',
    ignoreName: '.remarkignore',
    presetPrefix: 'remark-preset',
    pluginPrefix: 'remark'
  })(editor);
}

/**
 * Linter-markdown.
 *
 * @return {LinterConfiguration}
 */
function provideLinter() {
  return {
    grammarScopes: scopes,
    name: 'remark-lint',
    scope: 'file',
    lintOnFly: true,
    lint
  };
}

function activate() {
  let callbackID;
  const installLinterMarkdownDeps = () => {
    idleCallbacks.delete(callbackID);

    // Install package dependencies
    if (!atom.inSpecMode()) {
      require('atom-package-deps').install('linter-markdown');
    }
    // Load required modules
    if (!engine) {
      engine = require('unified-engine-atom');
    }
    if (!processor) {
      processor = require('remark');
    }
  };

  // Defer this till an idle time as we don't need it immediately
  callbackID = window.requestIdleCallback(installLinterMarkdownDeps);
  idleCallbacks.add(callbackID);

  subscriptions = new CompositeDisposable();

  subscriptions.add(atom.config.observe('linter-markdown.scopes', (value) => {
    scopes = value;
  }));
  subscriptions.add(atom.config.observe('linter-markdown.detectIgnore', (value) => {
    detectIgnore = value;
  }));

  config.on();
}

function deactivate() {
  idleCallbacks.forEach(callbackID => window.cancleIdleCallback(callbackID));
  idleCallbacks.clear();
  subscriptions.dispose();

  config.off();
}

/*
 * Expose.
 */
module.exports = {
  activate,
  deactivate,
  provideLinter
};
<|endoftext|>


<commit_before>/*
 * Cettia
 * http://cettia.io/projects/cettia-protocol/
 *
 * Copyright 2015 The Cettia Project
 * Licensed under the Apache License, Version 2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 */
var events = require("events");
var url = require("url");
var WebSocket = require("ws");
var createBaseTransport = require("./transport-base-transport");

// This function is exposed to the module's `transport` module's
// `createWebSocketTransport` as a factory to create a WebSocket transport.
// WebSocket is a protocol designed for a full-duplex communications over a TCP
// connection.
module.exports = function(uri, options) {
    var urlObj = url.parse(uri, true);
    // URI's protocol should be either `ws` or `wss`.
    if (urlObj.protocol === "ws:" || urlObj.protocol === "wss:") {
        // A transport object.
        var self = createBaseTransport(uri, options);
        var ws;
        self.connect = function() {
            // Simply delegates WebSocket's events to transport and transport's
            // behaviors to WebSocket.
            ws = new WebSocket(uri);
            ws.onopen = function() {
                self.emit("open");
            };
            ws.onmessage = function(event) {
                // `event.data` is a message. It is string if text frame is sent and
                // Buffer if binary frame is sent.
                if (typeof event.data === "string") {
                    self.emit("text", event.data);
                } else {
                    self.emit("binary", event.data);
                }
            };
            ws.onerror = function(error) {
                self.emit("error", error);
                // A transport should fire `close` event as well as `error`
                // event when a connection fails.
                // https://github.com/websockets/ws/issues/505
                if (ws.readyState === 0 && error.code === "ECONNREFUSED") {
                    self.emit("close");
                }
            };
            ws.onclose = function() {
                self.emit("close");
            };
        };
        self.write = function(data) {
            // If `data` is string, a text frame is sent, and if it's Buffer, a
            // binary frame is sent.
            ws.send(data);
        };
        self.close = function() {
            ws.close();
            return this;
        };
        return self;
    }
};<commit_msg>Use a ready state constant instead of its value #3<commit_after>/*
 * Cettia
 * http://cettia.io/projects/cettia-protocol/
 *
 * Copyright 2015 The Cettia Project
 * Licensed under the Apache License, Version 2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 */
var events = require("events");
var url = require("url");
var WebSocket = require("ws");
var createBaseTransport = require("./transport-base-transport");

// This function is exposed to the module's `transport` module's
// `createWebSocketTransport` as a factory to create a WebSocket transport.
// WebSocket is a protocol designed for a full-duplex communications over a TCP
// connection.
module.exports = function(uri, options) {
    var urlObj = url.parse(uri, true);
    // URI's protocol should be either `ws` or `wss`.
    if (urlObj.protocol === "ws:" || urlObj.protocol === "wss:") {
        // A transport object.
        var self = createBaseTransport(uri, options);
        var ws;
        self.connect = function() {
            // Simply delegates WebSocket's events to transport and transport's
            // behaviors to WebSocket.
            ws = new WebSocket(uri);
            ws.onopen = function() {
                self.emit("open");
            };
            ws.onmessage = function(event) {
                // `event.data` is a message. It is string if text frame is sent and
                // Buffer if binary frame is sent.
                if (typeof event.data === "string") {
                    self.emit("text", event.data);
                } else {
                    self.emit("binary", event.data);
                }
            };
            ws.onerror = function(error) {
                self.emit("error", error);
                // A transport should fire `close` event as well as `error`
                // event when a connection fails.
                // https://github.com/websockets/ws/issues/505
                if (ws.readyState === WebSocket.CONNECTING && error.code === "ECONNREFUSED") {
                    console.log(1)
                    self.emit("close");
                }
            };
            ws.onclose = function() {
                self.emit("close");
            };
        };
        self.write = function(data) {
            // If `data` is string, a text frame is sent, and if it's Buffer, a
            // binary frame is sent.
            ws.send(data);
        };
        self.close = function() {
            ws.close();
            return this;
        };
        return self;
    }
};<|endoftext|>


<commit_before>"use strict";

/**
 * Karma configuration.
 */

module.exports = function (config) {
  config.set({

    frameworks: ["mocha", "sinon"],

    files: [
      "test/**_test.js"
    ],

    preprocessors: {
      "test/**_test.js": ["webpack"]
    },

    reporters: ["progress"],

    browsers: ["Chrome"],

    webpack: require("./webpack.config"),

    plugins: [
      "karma-chrome-launcher",
      "karma-mocha",
      "karma-sinon",
      "karma-webpack"
    ]

  });
};
<commit_msg>[Fixed] Add Karma Firefox Runner for TravisCI<commit_after>"use strict";

/**
 * Karma configuration.
 */

module.exports = function (config) {
  config.set({

    frameworks: ["mocha", "sinon"],

    files: [
      "test/**_test.js"
    ],

    preprocessors: {
      "test/**_test.js": ["webpack"]
    },

    reporters: ["progress"],

    browsers: ["Chrome"],

    webpack: require("./webpack.config"),

    plugins: [
      "karma-chrome-launcher",
      "karma-firefox-launcher",
      "karma-mocha",
      "karma-sinon",
      "karma-webpack"
    ]

  });
};
<|endoftext|>


<commit_before>'use strict'

var miss = require('mississippi')
var Wreck = require('wreck')
var generateToken = require('../lib/generate-token')
var config = require('../config')
var token = generateToken({key: config.JWT_KEY, payload: {system: 'laurentius'}})
var wreckOptions = {
  json: true,
  headers: {
    Authorization: token
  }
}

var sendStatusMessage = miss.through(function (chunck, encoding, callback) {
  var item = JSON.parse(chunck)

  if (item.CALLBACK_STATUS_URL) {
    console.log(item._id + ': send-status-message')
    wreckOptions.payload = JSON.stringify({status: item.CALLBACK_STATUS_MESSAGE})
    Wreck.post(item.CALLBACK_STATUS_URL, wreckOptions, function (error, response, payload) {
      if (error) {
        return callback(error, null)
      } else {
        return callback(null, JSON.stringify(item))
      }
    })
  } else {
    console.log(item._id + ': send-status-message No message to send')
    return callback(null, JSON.stringify(item))
  }
})

module.exports = sendStatusMessage
<commit_msg>Added logging<commit_after>'use strict'

var miss = require('mississippi')
var Wreck = require('wreck')
var generateToken = require('../lib/generate-token')
var config = require('../config')
var token = generateToken({key: config.JWT_KEY, payload: {system: 'laurentius'}})
var wreckOptions = {
  json: true,
  headers: {
    Authorization: token
  }
}

var sendStatusMessage = miss.through(function (chunck, encoding, callback) {
  var item = JSON.parse(chunck)
  console.log(item)

  if (item.CALLBACK_STATUS_URL) {
    console.log(item._id + ': send-status-message')
    wreckOptions.payload = JSON.stringify({status: config.CALLBACK_STATUS_MESSAGE})
    Wreck.post(item.CALLBACK_STATUS_URL, wreckOptions, function (error, response, payload) {
      if (error) {
        return callback(error, null)
      } else {
        return callback(null, JSON.stringify(item))
      }
    })
  } else {
    console.log(item._id + ': send-status-message No message to send')
    return callback(null, JSON.stringify(item))
  }
})

module.exports = sendStatusMessage
<|endoftext|>


<commit_before>var lifecycleCVAPI = {
	setup: function() {
		initConstraintValidationAPI();
		$( 'form' ).forcesForms( 'validate' );
	},
	teardown: function() {
		initConstraintValidationAPI();
		$( 'form' ).forcesForms( 'validate' );
	}
};
<commit_msg>only need to rebind on setup (not teardown)<commit_after>var lifecycleCVAPI = {
	setup: function() {
		initConstraintValidationAPI();
		$( 'form' ).forcesForms( 'validate' );
	}
};
<|endoftext|>