<commit_before>import InfiniteTree from '../../src';
import renderer from './renderer';
import './index.styl';
import './animation.styl';
import { addEventListener, preventDefault, stopPropagation, quoteattr } from '../../src/helper';
import data from './data.json';

const updatePreview = (node) => {
    const el = document.querySelector('#classic [data-id="preview"]');
    if (node) {
        let o = {
            id: node.id,
            name: node.name,
            children: node.children ? node.children.length : 0,
            parent: node.parent ? node.parent.id : null,
            state: node.state
        };
        if (node.loadOnDemand !== undefined) {
            o.loadOnDemand = node.loadOnDemand;
        }
        el.innerHTML = JSON.stringify(o, null, 2).replace(/\n/g, '
').replace(/\s/g, ' ');
    } else {
        el.innerHTML = '';
    }
};

const tree = new InfiniteTree(document.querySelector('#classic [data-id="tree"]'), {
    autoOpen: true, // Defaults to false
    droppable: true, // Defaults to false
    loadNodes: (parentNode, done) => {
        const suffix = parentNode.id.replace(/(\w)+/, '');
        const nodes = [
            {
                id: 'node1' + suffix,
                name: 'Node 1'
            },
            {
                id: 'node2' + suffix,
                name: 'Node 2'
            }
        ];
        setTimeout(() => {
            done(null, nodes);
        }, 1000);
    },
    rowRenderer: renderer,
    selectable: true, // Defaults to true
    shouldSelectNode: (node) => { // Defaults to null
        if (!node || (node === tree.getSelectedNode())) {
            return false; // Prevent from deselecting the current node
        }
        return true;
    }
});

tree.on('contentWillUpdate', () => {
    console.log('contentWillUpdate');
});
tree.on('contentDidUpdate', () => {
    console.log('contentDidUpdate');
    const node = tree.getSelectedNode();
    updatePreview(node);
});
tree.on('openNode', (node) => {
    console.log('openNode', node);
});
tree.on('closeNode', (node) => {
    console.log('closeNode', node);
});
tree.on('dropNode', (node, e) => {
    console.log('dropNode', node);
    const source = e.dataTransfer.getData('text');
    const innerHTML = 'Dropped to ' + quoteattr(node.name) + '';
    document.querySelector('#classic [data-id="dropped-result"]').innerHTML = innerHTML;
});
tree.on('selectNode', (node) => {
    console.log('selectNode', node);
    updatePreview(node);
});

tree.loadData(data);

// Scroll Element
addEventListener(tree.scrollElement, 'scroll', (e) => {
    const progress = (tree.scrollElement.scrollTop / tree.contentElement.clientHeight) * 100 || 0;
    document.querySelector('#classic [data-id="scrolling-progress"]').style.width = progress + '%';
});

// Draggable Element
const draggableElement = document.querySelector('#classic [data-id="draggable-element"]');

// http://stackoverflow.com/questions/5500615/internet-explorer-9-drag-and-drop-dnd
addEventListener(draggableElement, 'selectstart', (e) => {
    preventDefault(e);
    stopPropagation(e);
    draggableElement.dragDrop();
    return false;
});

addEventListener(draggableElement, 'dragstart', (e) => {
    e.dataTransfer.effectAllowed = 'move';
    const target = e.target || e.srcElement;
    e.dataTransfer.setData('text', target.id);
    document.querySelector('#classic [data-id="dropped-result"]').innerHTML = '';
});

addEventListener(draggableElement, 'dragend', function(e) {
});

const load = () => {
    // Select the first node
    tree.selectNode(tree.getChildNodes()[0]);
};

export {
    load
}
<commit_msg>Update examples<commit_after>import InfiniteTree from '../../src';
import renderer from './renderer';
import './index.styl';
import './animation.styl';
import { addEventListener, preventDefault, stopPropagation, quoteattr } from '../../src/helper';
import data from './data.json';

const updatePreview = (node) => {
    const el = document.querySelector('#classic [data-id="preview"]');
    if (node) {
        let o = {
            id: node.id,
            name: node.name,
            children: node.children ? node.children.length : 0,
            parent: node.parent ? node.parent.id : null,
            state: node.state
        };
        if (node.loadOnDemand !== undefined) {
            o.loadOnDemand = node.loadOnDemand;
        }
        el.innerHTML = JSON.stringify(o, null, 2).replace(/\n/g, '
').replace(/\s/g, ' ');
    } else {
        el.innerHTML = '';
    }
};

const tree = new InfiniteTree(document.querySelector('#classic [data-id="tree"]'), {
    autoOpen: true, // Defaults to false
    droppable: true, // Defaults to false
    loadNodes: (parentNode, done) => {
        const suffix = parentNode.id.replace(/(\w)+/, '');
        const nodes = [
            {
                id: 'node1' + suffix,
                name: 'Node 1'
            },
            {
                id: 'node2' + suffix,
                name: 'Node 2'
            }
        ];
        setTimeout(() => {
            done(null, nodes);
        }, 1000);
    },
    rowRenderer: renderer,
    selectable: true, // Defaults to true
    shouldSelectNode: (node) => { // Defaults to null
        if (!node || (node === tree.getSelectedNode())) {
            return false; // Prevent from deselecting the current node
        }
        return true;
    }
});

tree.on('contentWillUpdate', () => {
    console.log('contentWillUpdate');
});
tree.on('contentDidUpdate', () => {
    console.log('contentDidUpdate');
    const node = tree.getSelectedNode();
    updatePreview(node);
});
tree.on('openNode', (node) => {
    console.log('openNode', node);
});
tree.on('closeNode', (node) => {
    console.log('closeNode', node);
});
tree.on('dropNode', (node, e) => {
    console.log('dropNode', node);
    const source = e.dataTransfer.getData('text');
    const innerHTML = 'Dropped to ' + quoteattr(node.name) + '';
    document.querySelector('#classic [data-id="dropped-result"]').innerHTML = innerHTML;
});
tree.on('selectNode', (node) => {
    console.log('selectNode', node);
    updatePreview(node);
});

tree.loadData(data);

// Scroll Element
addEventListener(tree.scrollElement, 'scroll', (e) => {
    const progress = (tree.scrollElement.scrollTop / tree.contentElement.clientHeight) * 100 || 0;
    document.querySelector('#classic [data-id="scrolling-progress"]').style.width = progress + '%';
});

// Draggable Element
const draggableElement = document.querySelector('#classic [data-id="draggable-element"]');

// http://stackoverflow.com/questions/5500615/internet-explorer-9-drag-and-drop-dnd
addEventListener(draggableElement, 'selectstart', (e) => {
    preventDefault(e);
    stopPropagation(e);
    draggableElement.dragDrop();
    return false;
});

addEventListener(draggableElement, 'dragstart', (e) => {
    e.dataTransfer.effectAllowed = 'move';
    const target = e.target || e.srcElement;
    e.dataTransfer.setData('text', target.id);
    document.querySelector('#classic [data-id="dropped-result"]').innerHTML = '';
});

addEventListener(draggableElement, 'dragend', function(e) {
});

const load = () => {
    const childNodes = tree.getChildNodes();

    if (childNodes.length > 0) {
        // Select the first node
        tree.selectNode(childNodes[0]);
    }
};

export {
    load
}
<|endoftext|>


<commit_before>"use strict";
var assert = require('assert');

var Suit = {
  Spades: 1,
  Diamonds: 2,
  Clubs: 3,
  Hearts: 4
};

var Stack = function() {

  Stack.prototype._cards = [];

  Stack.prototype.empty = function() {
    return true;
  };

  Stack.prototype.add = function(card) {
    this._cards.push(card);
  };

  Stack.prototype.top = function() {
    return this._cards[this._cards.length - 1];
  };

  Stack.prototype.pop = function() {
    return this._cards.pop();
  };

  return this;
};

var Card = function(suit,value) {
  this._suit = suit;
  this._value = value;

  Card.prototype.suit = function() {
    return this._suit;
  };

  Card.prototype.value = function() {
    return this._value;
  };

  return this;
};

var Foundation = function() {
  this[Suit.Spades] = new Stack();
  this[Suit.Clubs] = new Stack();
  this[Suit.Hearts] = new Stack();
  this[Suit.Diamonds] = new Stack();

  return this;
};

describe('klondike', function() {
  describe('card', function() {
    it('has a suit and a value', function() {
      var card = new Card(Suit.Spades,1);
      assert.equal(Suit.Spades, card.suit());
      assert.equal(1, card.value());
    });
  });

  describe('foundation', function() {
    it('has four stacks', function() {
      var foundation = new Foundation();
      assert(foundation[Suit.Spades].empty());
      assert(foundation[Suit.Hearts].empty());
      assert(foundation[Suit.Diamonds].empty());
      assert(foundation[Suit.Clubs].empty());
    });

    it('can raise cards to the right stack', function() {
      var foundation = new Foundation();

      assert(!foundation.canRaise(new Card(Suit.Spades, 2)));
    });
  });

  describe('stack', function() {
    it('is a concept', function() {
      assert(new Stack().empty());
    });

    it('can add card', function() {
      var stack = new Stack();
      stack.add(new Card(Suit.Spades, 1));

      assert.deepEqual(new Card(Suit.Spades, 1), stack.top());
    });

    var stackWithTwoCards = function() {
      var stack = new Stack();
      stack.add(new Card(Suit.Spades, 1));
      stack.add(new Card(Suit.Hearts, 2));

      return stack;
    };

    it('can add multiple cards', function() {
      var stack = stackWithTwoCards();
      assert.deepEqual(new Card(Suit.Hearts, 2), stack.top());
    });

    it('can pop cards', function() {
      var stack = stackWithTwoCards();
      stack.pop();
      assert.deepEqual(new Card(Suit.Spades, 1), stack.top());
    });
  });

});
<commit_msg>simplest possible pass<commit_after>"use strict";
var assert = require('assert');

var Suit = {
  Spades: 1,
  Diamonds: 2,
  Clubs: 3,
  Hearts: 4
};

var Stack = function() {

  Stack.prototype._cards = [];

  Stack.prototype.empty = function() {
    return true;
  };

  Stack.prototype.add = function(card) {
    this._cards.push(card);
  };

  Stack.prototype.top = function() {
    return this._cards[this._cards.length - 1];
  };

  Stack.prototype.pop = function() {
    return this._cards.pop();
  };

  return this;
};

var Card = function(suit,value) {
  this._suit = suit;
  this._value = value;

  Card.prototype.suit = function() {
    return this._suit;
  };

  Card.prototype.value = function() {
    return this._value;
  };

  return this;
};

var Foundation = function() {
  this[Suit.Spades] = new Stack();
  this[Suit.Clubs] = new Stack();
  this[Suit.Hearts] = new Stack();
  this[Suit.Diamonds] = new Stack();

  Foundation.prototype.canRaise = function() {
    return false;
  };

  return this;
};

describe('klondike', function() {
  describe('card', function() {
    it('has a suit and a value', function() {
      var card = new Card(Suit.Spades,1);
      assert.equal(Suit.Spades, card.suit());
      assert.equal(1, card.value());
    });
  });

  describe('foundation', function() {
    it('has four stacks', function() {
      var foundation = new Foundation();
      assert(foundation[Suit.Spades].empty());
      assert(foundation[Suit.Hearts].empty());
      assert(foundation[Suit.Diamonds].empty());
      assert(foundation[Suit.Clubs].empty());
    });

    it('can raise cards to the right stack', function() {
      var foundation = new Foundation();

      assert(!foundation.canRaise(new Card(Suit.Spades, 2)));
    });
  });

  describe('stack', function() {
    it('is a concept', function() {
      assert(new Stack().empty());
    });

    it('can add card', function() {
      var stack = new Stack();
      stack.add(new Card(Suit.Spades, 1));

      assert.deepEqual(new Card(Suit.Spades, 1), stack.top());
    });

    var stackWithTwoCards = function() {
      var stack = new Stack();
      stack.add(new Card(Suit.Spades, 1));
      stack.add(new Card(Suit.Hearts, 2));

      return stack;
    };

    it('can add multiple cards', function() {
      var stack = stackWithTwoCards();
      assert.deepEqual(new Card(Suit.Hearts, 2), stack.top());
    });

    it('can pop cards', function() {
      var stack = stackWithTwoCards();
      stack.pop();
      assert.deepEqual(new Card(Suit.Spades, 1), stack.top());
    });
  });

});
<|endoftext|>


<commit_before>var SpanCreatorTaskList = function(topContainer) {

  var input;
  var list;
  var tasks = [];

  var init = function() {
    gatherComponents();
    addBehavior();
  };

  var gatherComponents = function() {
    input = topContainer.find('input');
    list = topContainer.find('ul');
  };

  var addBehavior = function() {
    input.keyup(onKeyUp);
    new InputSizeAdjuster(input);
  };

  var onKeyUp = function(e) {
    if (e.key == 'Enter')
      addTypedTask();
  };

  var addTypedTask = function() {
    addTask(input.val());
  };

  var addTask = function(task) {
    task = jQuery.trim(task);
    if (!task || tasks.indexOf(task) > -1)
      return;

    input.val('');
    tasks.push(task);

    var li = jQuery('<li>').appendTo(list);

    jQuery('<a>')
      .appendTo(li)
      .addClass('far fa-times')
      .click(removeItem);

    li.append(task);
    publishChange();
  };

  var removeItem = function() {
    var anchor = jQuery(this);
    var taskText = anchor[0].nextSibling;
    tasks.splice(tasks.indexOf(taskText), 1);
    anchor.parent().remove();
    publishChange();
  };

  var clear = function() {
    tasks = [];
    list.empty();
    input.val('');
    publishChange();
  };

  var publishChange = function() {
    App.dispatcher.publish('SPAN_CHANGED');
  };

  init();

  return {
    getTasks:function() {
      return tasks;
    },
    addCurrent:addTypedTask,
    clear:clear,
    setTasks:function(tasks) {
      clear();
      jQuery.each(tasks, function(index, task) {
        addTask(task);
      });
    },
    focus:function() {
      input.focus();
    }
  };
};
<commit_msg>Fixing bug that sometimes caused edited task list to silently include the wrong items.<commit_after>var SpanCreatorTaskList = function(topContainer) {

  var input;
  var list;
  var tasks = [];

  var init = function() {
    gatherComponents();
    addBehavior();
  };

  var gatherComponents = function() {
    input = topContainer.find('input');
    list = topContainer.find('ul');
  };

  var addBehavior = function() {
    input.keyup(onKeyUp);
    new InputSizeAdjuster(input);
  };

  var onKeyUp = function(e) {
    if (e.key == 'Enter')
      addTypedTask();
  };

  var addTypedTask = function() {
    addTask(input.val());
  };

  var addTask = function(task) {
    task = jQuery.trim(task);
    if (!task || tasks.indexOf(task) > -1)
      return;

    input.val('');
    tasks.push(task);

    var li = jQuery('<li>').appendTo(list);

    jQuery('<a>')
      .appendTo(li)
      .addClass('far fa-times')
      .click(removeItem);

    li.append(task);
    publishChange();
  };

  var removeItem = function() {
    var anchor = jQuery(this);
    var taskText = anchor[0].nextSibling.textContent;
    tasks.splice(tasks.indexOf(taskText), 1);
    anchor.parent().remove();
    publishChange();
  };

  var clear = function() {
    tasks = [];
    list.empty();
    input.val('');
    publishChange();
  };

  var publishChange = function() {
    App.dispatcher.publish('SPAN_CHANGED');
  };

  init();

  return {
    getTasks:function() {
      return tasks;
    },
    addCurrent:addTypedTask,
    clear:clear,
    setTasks:function(tasks) {
      clear();
      jQuery.each(tasks, function(index, task) {
        addTask(task);
      });
    },
    focus:function() {
      input.focus();
    }
  };
};
<|endoftext|>


<commit_before>module.exports = {
  // this controls whether to abort the test execution when an assertion failed and skip the rest
  // it's being used in waitFor commands and expect assertions
  abortOnAssertionFailure: true,

  // this will overwrite the default polling interval (currently 500ms) for waitFor commands
  // and expect assertions that use retry
  waitForConditionPollInterval: 500,

  // default timeout value in milliseconds for waitFor commands and implicit waitFor value for
  // expect assertions
  waitForConditionTimeout : 5000,

  // this will cause waitFor commands on elements to throw an error if multiple
  // elements are found using the given locate strategy and selector
  throwOnMultipleElementsReturned: false,

  // controls the timeout value for async hooks. Expects the done() callback to be invoked within this time
  // or an error is thrown
  asyncHookTimeout : 10000,

  // controls the timeout value for when running async unit tests. Expects the done() callback to be invoked within this time
  // or an error is thrown
  unitTestsTimeout : 2000,

  // controls the timeout value for when executing the global async reporter. Expects the done() callback to be invoked within this time
  // or an error is thrown
  customReporterCallbackTimeout: 20000,

  // Automatically retrying failed assertions - You can tell Nightwatch to automatically retry failed assertions until a given timeout is reached, before the test runner gives up and fails the test.
  retryAssertionTimeout: 1000,

  'default' : {
    myGlobal : function() {
      return 'I\'m a method';
    }
  },

  'test_env' : {
    myGlobal: 'test_global',
    beforeEach : function() {

    }
  },

  before(cb) {
    //console.log('GLOBAL BEFORE')
    cb();
  },

  beforeEach(browser, cb) {
    //console.log('GLOBAL beforeEach')
    cb();
  },

  after(cb) {
    //console.log('GLOBAL AFTER')
    cb();
  },

  afterEach(browser, cb) {
    browser.perform(function() {
      //console.log('GLOBAL afterEach')
      cb();
    });
  },

  reporter(results, cb) {
    cb();
  }
};
<commit_msg>syntax fixed (#2045)<commit_after>module.exports = {
  // this controls whether to abort the test execution when an assertion failed and skip the rest
  // it's being used in waitFor commands and expect assertions
  abortOnAssertionFailure: true,

  // this will overwrite the default polling interval (currently 500ms) for waitFor commands
  // and expect assertions that use retry
  waitForConditionPollInterval: 500,

  // default timeout value in milliseconds for waitFor commands and implicit waitFor value for
  // expect assertions
  waitForConditionTimeout: 5000,

  // this will cause waitFor commands on elements to throw an error if multiple
  // elements are found using the given locate strategy and selector
  throwOnMultipleElementsReturned: false,

  // controls the timeout value for async hooks. Expects the done() callback to be invoked within this time
  // or an error is thrown
  asyncHookTimeout: 10000,

  // controls the timeout value for when running async unit tests. Expects the done() callback to be invoked within this time
  // or an error is thrown
  unitTestsTimeout: 2000,

  // controls the timeout value for when executing the global async reporter. Expects the done() callback to be invoked within this time
  // or an error is thrown
  customReporterCallbackTimeout: 20000,

  // Automatically retrying failed assertions - You can tell Nightwatch to automatically retry failed assertions until a given timeout is reached, before the test runner gives up and fails the test.
  retryAssertionTimeout: 1000,

  'default' : {
    myGlobal : function() {
      return 'I\'m a method';
    }
  },

  'test_env' : {
    myGlobal: 'test_global',
    beforeEach : function() {

    }
  },

  before(cb) {
    //console.log('GLOBAL BEFORE')
    cb();
  },

  beforeEach(browser, cb) {
    //console.log('GLOBAL beforeEach')
    cb();
  },

  after(cb) {
    //console.log('GLOBAL AFTER')
    cb();
  },

  afterEach(browser, cb) {
    browser.perform(function() {
      //console.log('GLOBAL afterEach')
      cb();
    });
  },

  reporter(results, cb) {
    cb();
  }
};
<|endoftext|>


<commit_before>var amazon = AWSSum.load('amazon/amazon');
var S3 = AWSSum.load('amazon/s3', 'S3');
var Future = Npm.require("fibers/future");
var child_process = Npm.require("child_process");

// gets git sha passed in via --settings
var getGitSha = function () {
  var gitSha = Meteor.settings["git-sha"];
  if (!gitSha) {
    console.log("Run with --settings to set 'git-sha'");
    process.exit(1);
  }
  return gitSha;
};

// calls 'cmd', returns stdout.
// XXX should we have a smart package for these? 'process'?
var execSync = function (cmd) {
  return Future.wrap(function(cb) {
    var cb2 = function(err, stdout, stderr) { cb(err, stdout); };
    child_process.exec(cmd, cb2);
  })().wait();
};

// returns usable S3 object
var configureS3 = function () {
  // calls 's3cmd --dump-config', returns {accessKey: ..., secretKey: ...}
  var getS3Credentials = function () {
    var unparsedConfig = execSync("s3cmd --dump-config");
    var accessKey = /access_key = (.*)/.exec(unparsedConfig)[1];
    var secretKey = /secret_key = (.*)/.exec(unparsedConfig)[1];
    return {accessKey: accessKey, secretKey: secretKey};
  };

  var s3Credentials = getS3Credentials();
  var s3 = new S3({
    accessKeyId: s3Credentials.accessKey,
    secretAccessKey: s3Credentials.secretKey,
    region: amazon.US_EAST_1
  });

  return s3;
};

// fetch and parse release manifest
var getManifest = function(s3, release) {
  var content;
  try {
    content = s3.GetObject({
      BucketName: "com.meteor.packages",
      ObjectName: ["unpublished", release, "manifest.json"].join("/")
    }).Body;
  } catch (e) {
    console.log("Release " + release + " not built.");
    process.exit(1);
  }

  return JSON.parse(content);
};

// are there any files with this prefix?
var noneWithPrefix = function(s3, prefix) {
  var files = s3.ListObjects({
    BucketName: "com.meteor.packages",
    Prefix: prefix
  });
  return !_.isEmpty(files.Body.ListBucketResult.Contents);
};

// publish a given engine, copying multiple files from
// s3://com.meteor.packages/RELEASE/unpublished/ to
// s3://com.meteor.packages/engines/VERSION/
var publishEngine = function(s3, release, version) {
  var destPath = ["engines", version].join("/");

  process.stdout.write("Engine " + version + ": ");
  if (noneWithPrefix(s3, destPath)) {
    console.log("already published");
    return;
  } else {
    console.log("publishing");
  }

  var engineArtifacts = s3.ListObjects({
    BucketName: "com.meteor.packages",
    Prefix: ["unpublished", release, "meteor-engine-"].join("/")
  }).Body.ListBucketResult.Contents;

  _.each(engineArtifacts, function (artifact) {
    var sourceKey = artifact.Key;
    var filename = _.last(sourceKey.split("/"));
    var destKey = [destPath, filename].join("/");

    var opts = {
      BucketName: "com.meteor.packages",
      ObjectName: destKey,
      SourceBucket: "com.meteor.packages",
      SourceObject: sourceKey
    };
    s3.CopyObject(opts);
  });
};

// publish a given package, copying from
// s3://com.meteor.packages/unpublished/RELEASE/NAME-VERSION.tar.gz to
// s3://com.meteor.packages/packages/NAME-VERSION.tar.gz
var publishPackage = function(s3, release, name, version) {
  var filename = name + "-" + version + ".tar.gz";
  var destKey = ["packages", name, filename].join("/");
  var sourceKey = ["unpublished", release, filename].join("/");

  process.stdout.write("Package " + name + " version " + version + ": ");
  if (noneWithPrefix(s3, destKey)) {
    console.log("already published");
    return;
  } else {
    console.log("publishing");
  }

  var opts = {
    BucketName: "com.meteor.packages",
    ObjectName: destKey,
    SourceBucket: "com.meteor.packages",
    SourceObject: sourceKey
  };
  s3.CopyObject(opts);
};

// publish the release manifest, copying from
// s3://com.meteor.packages/unpublished/RELEASE/manifest.json to
// s3://com.meteor.packages/releases/RELEASE.json
var publishManifest = function(s3, release) {
  var destKey = ["releases", release + ".json"].join("/");
  var sourceKey = ["unpublished", release, "manifest.json"].join("/");

  process.stdout.write("Release manifest " + release + ": ");
  if (noneWithPrefix(s3, destKey)) {
    console.log("already published");
    return;
  } else {
    console.log("publishing");
  }

  var opts = {
    BucketName: "com.meteor.packages",
    ObjectName: destKey,
    SourceBucket: "com.meteor.packages",
    SourceObject: sourceKey
  };
  s3.CopyObject(opts);
};

// START HERE
var main = function() {
  // read git sha, used as the version of the unpublished release.
  var release = getGitSha();
  var s3 = configureS3();
  var manifest = getManifest(s3, release);
  publishEngine(s3, release, manifest.engine);
  _.each(manifest.packages, function(version, name) {
    publishPackage(s3, release, name, version);
  });
  publishManifest(s3, release);
  process.exit();
};

main();<commit_msg>publish-release.sh: Explicitly print published artifacts<commit_after>var amazon = AWSSum.load('amazon/amazon');
var S3 = AWSSum.load('amazon/s3', 'S3');
var Future = Npm.require("fibers/future");
var child_process = Npm.require("child_process");

// accumulated while running, printed at the end
var publishedArtifacts = [];

// gets git sha passed in via --settings
var getGitSha = function () {
  var gitSha = Meteor.settings["git-sha"];
  if (!gitSha) {
    console.log("Run with --settings to set 'git-sha'");
    process.exit(1);
  }
  return gitSha;
};

// calls 'cmd', returns stdout.
// XXX should we have a smart package for these? 'process'?
var execSync = function (cmd) {
  return Future.wrap(function(cb) {
    var cb2 = function(err, stdout, stderr) { cb(err, stdout); };
    child_process.exec(cmd, cb2);
  })().wait();
};

// returns usable S3 object
var configureS3 = function () {
  // calls 's3cmd --dump-config', returns {accessKey: ..., secretKey: ...}
  var getS3Credentials = function () {
    var unparsedConfig = execSync("s3cmd --dump-config");
    var accessKey = /access_key = (.*)/.exec(unparsedConfig)[1];
    var secretKey = /secret_key = (.*)/.exec(unparsedConfig)[1];
    return {accessKey: accessKey, secretKey: secretKey};
  };

  var s3Credentials = getS3Credentials();
  var s3 = new S3({
    accessKeyId: s3Credentials.accessKey,
    secretAccessKey: s3Credentials.secretKey,
    region: amazon.US_EAST_1
  });

  return s3;
};

// fetch and parse release manifest
var getManifest = function(s3, release) {
  var content;
  try {
    content = s3.GetObject({
      BucketName: "com.meteor.packages",
      ObjectName: ["unpublished", release, "manifest.json"].join("/")
    }).Body;
  } catch (e) {
    console.log("Release " + release + " not built.");
    process.exit(1);
  }

  return JSON.parse(content);
};

// are there any files with this prefix?
var noneWithPrefix = function(s3, prefix) {
  var files = s3.ListObjects({
    BucketName: "com.meteor.packages",
    Prefix: prefix
  });
  return !_.isEmpty(files.Body.ListBucketResult.Contents);
};

// publish a given engine, copying multiple files from
// s3://com.meteor.packages/RELEASE/unpublished/ to
// s3://com.meteor.packages/engines/VERSION/
var publishEngine = function(s3, release, version) {
  var destPath = ["engines", version].join("/");

  process.stdout.write("engine " + version + ": ");
  if (noneWithPrefix(s3, destPath)) {
    console.log("already published");
    return;
  } else {
    publishedArtifacts.push("engine " + version);
    console.log("publishing");
  }

  var engineArtifacts = s3.ListObjects({
    BucketName: "com.meteor.packages",
    Prefix: ["unpublished", release, "meteor-engine-"].join("/")
  }).Body.ListBucketResult.Contents;

  _.each(engineArtifacts, function (artifact) {
    var sourceKey = artifact.Key;
    var filename = _.last(sourceKey.split("/"));
    var destKey = [destPath, filename].join("/");

    var opts = {
      BucketName: "com.meteor.packages",
      ObjectName: destKey,
      SourceBucket: "com.meteor.packages",
      SourceObject: sourceKey
    };
    s3.CopyObject(opts);
  });
};

// publish a given package, copying from
// s3://com.meteor.packages/unpublished/RELEASE/NAME-VERSION.tar.gz to
// s3://com.meteor.packages/packages/NAME-VERSION.tar.gz
var publishPackage = function(s3, release, name, version) {
  var filename = name + "-" + version + ".tar.gz";
  var destKey = ["packages", name, filename].join("/");
  var sourceKey = ["unpublished", release, filename].join("/");

  process.stdout.write("package " + name + " version " + version + ": ");
  if (noneWithPrefix(s3, destKey)) {
    console.log("already published");
    return;
  } else {
    publishedArtifacts.push("package " + name + " version " + version);
    console.log("publishing");
  }

  var opts = {
    BucketName: "com.meteor.packages",
    ObjectName: destKey,
    SourceBucket: "com.meteor.packages",
    SourceObject: sourceKey
  };
  s3.CopyObject(opts);
};

// publish the release manifest, copying from
// s3://com.meteor.packages/unpublished/RELEASE/manifest.json to
// s3://com.meteor.packages/releases/RELEASE.json
var publishManifest = function(s3, release) {
  var destKey = ["releases", release + ".json"].join("/");
  var sourceKey = ["unpublished", release, "manifest.json"].join("/");

  process.stdout.write("release manifest " + release + ": ");
  if (noneWithPrefix(s3, destKey)) {
    console.log("already published");
    return;
  } else {
    publishedArtifacts.push("release manifest " + release);
    console.log("publishing");
  }

  var opts = {
    BucketName: "com.meteor.packages",
    ObjectName: destKey,
    SourceBucket: "com.meteor.packages",
    SourceObject: sourceKey
  };
  s3.CopyObject(opts);
};

// START HERE
var main = function() {
  // read git sha, used as the version of the unpublished release.
  var release = getGitSha();
  var s3 = configureS3();
  var manifest = getManifest(s3, release);
  publishEngine(s3, release, manifest.engine);
  _.each(manifest.packages, function(version, name) {
    publishPackage(s3, release, name, version);
  });
  publishManifest(s3, release);
  console.log("\nPUBLISHED:\n" + publishedArtifacts.join('\n'));
  process.exit();
};

main();<|endoftext|>


<commit_before>Error.stackTraceLimit = Infinity;

jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;

__karma__.loaded = function() {};

System.config({
  packages: {
    'base/dist/app': {
      defaultExtension: false,
      format: 'register',
      map: Object.keys(window.__karma__.files)
        .filter(onlyAppFiles)
        .reduce(function(pathsMapping, appPath) {
          var moduleName = appPath.replace(/^\/base\/dist\/app\//, './').replace(/\.js$/, '');
          pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath]
        return pathsMapping;
      }, {})
    }
  }
});

System.import('angular2/src/core/dom/browser_adapter').then(function(browser_adapter) {
  // TODO: once beta is out we should change this code to use a "test platform"
  browser_adapter.BrowserDomAdapter.makeCurrent();
}).then(function() {
  return Promise.all(
    Object.keys(window.__karma__.files)
      .filter(onlySpecFiles)
      .map(function(moduleName) {
        return System.import(moduleName);
      }));
}).then(function() {
  __karma__.start();
}, function(error) {
  __karma__.error(error.stack || error);
});

function onlyAppFiles(filePath) {
  return /^\/base\/dist\/app\/(?!spec)([a-z0-9]+)\.js$/.test(filePath);
}

function onlySpecFiles(path) {
  return /\.spec\.js$/.test(path);
}<commit_msg>fix(test): allow dash/underscore separated names<commit_after>Error.stackTraceLimit = Infinity;

jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000;

__karma__.loaded = function() {};

System.config({
  packages: {
    'base/dist/app': {
      defaultExtension: false,
      format: 'register',
      map: Object.keys(window.__karma__.files)
        .filter(onlyAppFiles)
        .reduce(function(pathsMapping, appPath) {
          var moduleName = appPath.replace(/^\/base\/dist\/app\//, './').replace(/\.js$/, '');
          pathsMapping[moduleName] = appPath + '?' + window.__karma__.files[appPath]
        return pathsMapping;
      }, {})
    }
  }
});

System.import('angular2/src/core/dom/browser_adapter').then(function(browser_adapter) {
  // TODO: once beta is out we should change this code to use a "test platform"
  browser_adapter.BrowserDomAdapter.makeCurrent();
}).then(function() {
  return Promise.all(
    Object.keys(window.__karma__.files)
      .filter(onlySpecFiles)
      .map(function(moduleName) {
        return System.import(moduleName);
      }));
}).then(function() {
  __karma__.start();
}, function(error) {
  __karma__.error(error.stack || error);
});

function onlyAppFiles(filePath) {
  return /^\/base\/dist\/app\/(?!spec)([a-z0-9-_]+)\.js$/.test(filePath);
}

function onlySpecFiles(path) {
  return /\.spec\.js$/.test(path);
}
<|endoftext|>


<commit_before>'use strict';

const ezmesure = require('../../..');

exports.command = 'delete <indice>';
exports.desc    = 'Delete <indice>';
exports.builder = {};
exports.handler = function (argv) {
  const options = {};

  if (argv.u) { options.baseUrl = argv.u; }
  if (argv.token) { options.token = argv.token; }
  if (argv.insecure) { options.strictSSL = false; }

  ezmesure.indexDelete(argv.indice, options).then(res => {
    console.log('%s deleted', argv.indice);
  }).catch(err => {
    console.error(err.statusCode === 401 ? 'Invalid token' : err.message);
    process.exit(1);
  });
};<commit_msg>fix delete command<commit_after>'use strict';

const ezmesure = require('../../..');

exports.command = 'delete <indice>';
exports.desc    = 'Delete <indice>';
exports.builder = {};
exports.handler = function (argv) {
  const options = {};

  if (argv.u) { options.baseUrl = argv.u; }
  if (argv.token) { options.token = argv.token; }
  if (argv.insecure) { options.strictSSL = false; }

  ezmesure.indices.delete(argv.indice, options).then(res => {
    console.log('%s deleted', argv.indice);
  }).catch(err => {
    console.error(err.statusCode === 401 ? 'Invalid token' : err.message);
    process.exit(1);
  });
};<|endoftext|>


<commit_before>// Write an HTTP server that serves JSON data when it receives a GET request to the path '/api/parsetime'. Expect the request to contain a query string with a key 'iso' and an ISO-format time as the value.

// For example:
//   /api/parsetime?iso=2013-08-10T12:10:15.474Z
// The JSON response should contain only 'hour', 'minute' and 'second' properties. For example:
//     {
//       "hour": 14,
//       "minute": 23,
//       "second": 15
//     }
// Add second endpoint for the path '/api/unixtime' which accepts the same query string but returns UNIX epoch time under the property 'unixtime'. For example:
//     { "unixtime": 1376136615474 }
// Your server should listen on the port provided by the first argument to your program.<commit_msg>commit initial solution not passing test yet<commit_after>// Write an HTTP server that serves JSON data when it receives a GET request to the path '/api/parsetime'.
// Expect the request to contain a query string with a key 'iso' and an ISO-format time as the value.

// For example:
//   /api/parsetime?iso=2013-08-10T12:10:15.474Z
// The JSON response should contain only 'hour', 'minute' and 'second' properties. For example:
//     {
//       "hour": 14,
//       "minute": 23,
//       "second": 15
//     }
// Add second endpoint for the path '/api/unixtime' which accepts the same query string but returns UNIX epoch time under the property
// 'unixtime'. For example:
//     { "unixtime": 1376136615474 }
// Your server should listen on the port provided by the first argument to your program.
'use strict';

var http = require('http');
var url = require('url');
var qs = require('querystring');

var port = process.argv[2];

var help = function(){
    //provide all the possible rest calls
    var options = 'Options:\n';
    options = options + '/api/parsetime \n with iso parameter containing time. Example: /api/parsetime?iso=2013-08-10T12:10:15.474Z\n';
    options = options + '/api/unixtime \n with iso parameter containing time. Example: /api/parsetime?iso=2013-08-10T12:10:15.474Z';
    return options;
};

var parseTime = function(urlQuery){
    if(urlQuery.iso !== undefined){
        //console.log('Key = ' + urlQuery.iso);
        var d = new Date(urlQuery.iso);
        var jsonResult = {
            hour: parseFloat(d.getHours()).toFixed(2),
            minute: parseFloat(d.getMinutes()).toFixed(2),
            second: parseFloat(d.getSeconds()).toFixed(2)
        };
        return JSON.stringify(jsonResult);
    } else{
        console.error('Error: iso is undefined');
    }
};

var unixTime = function(urlQuery){
    if(urlQuery.iso !== undefined){
        //console.log('Key = ' + urlQuery.iso);
        var d = new Date(urlQuery.iso);
        var jsonResult = {
            unixtime: d.getTime()
        };
        return JSON.stringify(jsonResult);

    } else{
        console.error('Error: iso is undefined');
    }
};

var matchAndProcessURL = function(reqURL, callback){
    if(reqURL.pathname === '/api/parsetime'){
        return callback(null, parseTime(qs.parse(reqURL.query)));
    } else if(reqURL.pathname === '/api/unixtime'){
        return callback(null, unixTime(qs.parse(reqURL.query)));
    }
    else {
        return callback(reqURL.path + ' didn\'t match any of the url matchers\n\n' + help() , false);
    }
};

var server = http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'application/json'});

    var srvUrl = url.parse('http://' + req.url);
    //console.log(srvUrl);
    //res.write('Matching URL...\n');
    matchAndProcessURL(srvUrl, function(err, data){
        if(err){
            res.write(err);
        } else {
            //console.log(data);
            res.write(data);
        }
    });

    req.on('end', function(){
        res.end();
    });

    req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });
});

server.listen(port, '127.0.0.1');
//console.log('Server running at http://127.0.0.1:' + port);<|endoftext|>


<commit_before>import {Dialog, addDropdownBox} from "../../common"
import {tableResizeTemplate, tableInsertTemplate} from "./templates"

export class TableDialog {
    constructor(editor) {
        this.editor = editor
        this.dialogEl = false
    }

    init(){
        this.insertTableDialog()
    }

    markInsertTable(cell, className) {
        this.dialog.dialogEl.querySelectorAll(`td.${className}`).forEach(el => el.classList.remove(className))
        let colCount = 1
        let countElement = cell
        while (countElement.previousElementSibling) {
            countElement = countElement.previousElementSibling
            colCount += 1
        }
        let rowCount = 1
        countElement= countElement.parentElement
        while (countElement.previousElementSibling) {
            countElement = countElement.previousElementSibling
            rowCount += 1
        }
        // add hover class.
        const rows = this.dialog.dialogEl.querySelectorAll('tr')
        for (let i=0;i<rowCount;i++) {
            const cols = rows[i].querySelectorAll('td')
            for (let j=0;j<colCount;j++) {
                cols[j].classList.add(className)
            }
        }
        return {colCount, rowCount}
    }

    insertTableDialog() {
        let rowCount = 1, colCount = 1
        const buttons = []
        buttons.push({
            text: gettext('Insert'),
            classes: 'fw-dark',
            click: () => {
                const table = {type: 'table', content: []}

                for (let i=0;i<rowCount;i++) {
                    const row = {type: 'table_row', content: []}
                    for (let j=0;j<colCount;j++) {
                        row.content.push({type: 'table_cell', content: [{type: 'paragraph'}]})
                    }
                    table.content.push(row)

                }
                const schema = this.editor.currentView.state.schema
                this.editor.currentView.dispatch(
                    this.editor.currentView.state.tr.replaceSelectionWith(
                        schema.nodeFromJSON(table)
                    )
                )
                this.dialog.close()
            }
        })
        buttons.push({
            type: 'cancel'
        })

        this.dialog = new Dialog({
            title: gettext('Insert table'),
            body: tableInsertTemplate(),
            width: 360,
            height: 360,
            buttons,
            onClose: () => this.editor.currentView.focus()
        })

        this.dialog.open()

        // manage hovering over table cells
        this.dialog.dialogEl.querySelectorAll('td').forEach(el => el.addEventListener('mouseenter', () => {
            this.markInsertTable(el, 'hover')
        }))
        this.dialog.dialogEl.querySelectorAll('td').forEach(el => el.addEventListener('mouseleave', () => {
            this.dialog.dialogEl.querySelectorAll('td.hover').forEach(mEl => mEl.classList.remove('hover'))
        }))

        this.dialog.dialogEl.querySelectorAll('td').forEach(el => el.addEventListener('click', event => {
            event.preventDefault()
            event.stopImmediatePropagation()
            const newCounts = this.markInsertTable(el, 'selected')
            rowCount = newCounts.rowCount
            colCount = newCounts.colCount
        }))

    }
}

export class TableResizeDialog {
    constructor(editor) {
        this.editor = editor
        this.dialogEl = false
        this.aligned='center'
        this.width = '100'
        this.layout = 'fixed'
    }

    init() {
        const {table} = this.findTable(this.editor.currentView.state)
        if (table){
            this.width = table.attrs.width
            this.aligned = table.attrs.aligned
            this.layout = table.attrs.layout
        }
        this.insertDialog()
    }

    setTableAlignment() {
        if (this.width == "100"){
            this.dialog.dialogEl.querySelector("#table-alignment-btn").classList.add("disabled")
            this.dialog.dialogEl.querySelector('#table-alignment-btn label').innerHTML = "Center"
            return
        }
        this.dialog.dialogEl.querySelector('#table-alignment-btn label').innerHTML =
            document.getElementById(`table-alignment-${this.aligned}`).innerText
    }

    setTableWidth() {
        if (this.width == "100"){
            this.dialog.dialogEl.querySelector("#table-alignment-btn").classList.add("disabled")
            this.dialog.dialogEl.querySelector('#table-alignment-btn label').innerHTML = "Center"
        } else {
            this.dialog.dialogEl.querySelector("#table-alignment-btn").classList.remove("disabled")
        }
        this.dialog.dialogEl.querySelector('#table-width-btn label').innerHTML =
            document.getElementById(`table-width-${this.width}`).innerText
    }

    setTableLayout() {
        this.dialog.dialogEl.querySelector('#table-layout-btn label').innerHTML =
            document.getElementById(`table-layout-${this.layout}`).innerText
        if (this.layout === "auto")
            this.dialog.dialogEl.querySelector('#table-layout-btn').style.width = "105px"
        else
            this.dialog.dialogEl.querySelector('#table-layout-btn').style.width = "50px"
    }

    findTable(state) {
        const $head = state.selection.$head
        for (let d = $head.depth; d > 0; d--) if ($head.node(d).type.spec.tableRole == "table"){
            return {table: $head.node(d), tablePos: $head.before(d)}}
        return {table:false}
    }

    submitForm(){
        const {table, tablePos} = this.findTable(this.editor.currentView.state)
        if (!table) return
        const attrs = Object.assign({}, table.attrs, {
            width : this.width,
            aligned : this.width == "100" ? "center" : this.aligned,
            layout : this.layout
        })
        this.editor.currentView.dispatch(this.editor.currentView.state.tr.setNodeMarkup(tablePos, false, attrs))
    }

    insertDialog() {
        const buttons = []
        buttons.push({
            text: gettext('Update'),
            classes: 'fw-dark',
            click: () => {
                this.submitForm()
                this.dialog.close()
            }
        })
        buttons.push({
            type: 'cancel'
        })

        this.dialog = new Dialog({
            title: gettext('Resize table'),
            body: tableResizeTemplate(),
            width: 300,
            height: 260,
            buttons,
            onClose: () => this.editor.currentView.focus()
        })

        this.dialog.open()

        this.setTableAlignment()
        this.setTableWidth()
        this.setTableLayout()

        addDropdownBox(
            document.getElementById('table-alignment-btn'),
            document.getElementById('table-alignment-pulldown')
        )

        addDropdownBox(
            document.getElementById('table-width-btn'),
            document.getElementById('table-width-pulldown')
        )

        addDropdownBox(
            document.getElementById('table-layout-btn'),
            document.getElementById('table-layout-pulldown')
        )

        document.querySelectorAll('#table-alignment-pulldown li span').forEach(el => el.addEventListener(
            'click',
            event => {
                event.preventDefault()
                this.aligned = el.id.split('-')[2]
                this.setTableAlignment()
            }
        ))

        document.querySelectorAll('#table-width-pulldown li span').forEach(el => el.addEventListener(
            'click',
            event => {
                event.preventDefault()
                this.width = el.id.split('-')[2]
                this.setTableWidth()
            }
        ))

        document.querySelectorAll('#table-layout-pulldown li span').forEach(el => el.addEventListener(
            'click',
            event => {
                event.preventDefault()
                this.layout = el.id.split('-')[2]
                this.setTableLayout()
            }
        ))
    }
}
<commit_msg>CLA Signed<commit_after>import {Dialog, addDropdownBox} from "../../common"
import {tableResizeTemplate, tableInsertTemplate} from "./templates"

export class TableDialog {
    constructor(editor) {
        this.editor = editor
        this.dialogEl = false
    }

    init(){
        this.insertTableDialog()
    }

    markInsertTable(cell, className) {
        this.dialog.dialogEl.querySelectorAll(`td.${className}`).forEach(el => el.classList.remove(className))
        let colCount = 1
        let countElement = cell
        while (countElement.previousElementSibling) {
            countElement = countElement.previousElementSibling
            colCount += 1
        }
        let rowCount = 1
        countElement= countElement.parentElement
        while (countElement.previousElementSibling) {
            countElement = countElement.previousElementSibling
            rowCount += 1
        }
        // add hover class.
        const rows = this.dialog.dialogEl.querySelectorAll('tr')
        for (let i=0;i<rowCount;i++) {
            const cols = rows[i].querySelectorAll('td')
            for (let j=0;j<colCount;j++) {
                cols[j].classList.add(className)
            }
        }
        return {colCount, rowCount}
    }

    insertTableDialog() {
        let rowCount = 1, colCount = 1
        const buttons = []
        buttons.push({
            text: gettext('Insert'),
            classes: 'fw-dark',
            click: () => {
                const table = {type: 'table', content: []}

                for (let i=0;i<rowCount;i++) {
                    const row = {type: 'table_row', content: []}
                    for (let j=0;j<colCount;j++) {
                        row.content.push({type: 'table_cell', content: [{type: 'paragraph'}]})
                    }
                    table.content.push(row)

                }
                const schema = this.editor.currentView.state.schema
                this.editor.currentView.dispatch(
                    this.editor.currentView.state.tr.replaceSelectionWith(
                        schema.nodeFromJSON(table)
                    )
                )
                this.dialog.close()
            }
        })
        buttons.push({
            type: 'cancel'
        })

        this.dialog = new Dialog({
            title: gettext('Insert table'),
            body: tableInsertTemplate(),
            width: 360,
            height: 360,
            buttons,
            onClose: () => this.editor.currentView.focus()
        })

        this.dialog.open()

        // manage hovering over table cells
        this.dialog.dialogEl.querySelectorAll('td').forEach(el => el.addEventListener('mouseenter', () => {
            this.markInsertTable(el, 'hover')
        }))
        this.dialog.dialogEl.querySelectorAll('td').forEach(el => el.addEventListener('mouseleave', () => {
            this.dialog.dialogEl.querySelectorAll('td.hover').forEach(mEl => mEl.classList.remove('hover'))
        }))

        this.dialog.dialogEl.querySelectorAll('td').forEach(el => el.addEventListener('click', event => {
            event.preventDefault()
            event.stopImmediatePropagation()
            const newCounts = this.markInsertTable(el, 'selected')
            rowCount = newCounts.rowCount
            colCount = newCounts.colCount
        }))

    }
}

export class TableResizeDialog {
    constructor(editor) {
        this.editor = editor
        this.dialogEl = false
        this.aligned='center'
        this.width = '100'
        this.layout = 'fixed'
    }

    init() {
        const {table} = this.findTable(this.editor.currentView.state)
        if (table){
            this.width = table.attrs.width
            this.aligned = table.attrs.aligned
            this.layout = table.attrs.layout
        }
        this.insertDialog()
    }

    setTableAlignment() {
        if (this.width == "100"){
            this.dialog.dialogEl.querySelector("#table-alignment-btn").classList.add("disabled")
            this.dialog.dialogEl.querySelector('#table-alignment-btn label').innerHTML = "Center"
            return
        }
        this.dialog.dialogEl.querySelector('#table-alignment-btn label').innerHTML =
            document.getElementById(`table-alignment-${this.aligned}`).innerText
    }

    setTableWidth() {
        if (this.width == "100"){
            this.dialog.dialogEl.querySelector("#table-alignment-btn").classList.add("disabled")
            this.dialog.dialogEl.querySelector('#table-alignment-btn label').innerHTML = "Center"
        } else {
            this.dialog.dialogEl.querySelector("#table-alignment-btn").classList.remove("disabled")
        }
        this.dialog.dialogEl.querySelector('#table-width-btn label').innerHTML =
            document.getElementById(`table-width-${this.width}`).innerText
    }

    setTableLayout() {
        this.dialog.dialogEl.querySelector('#table-layout-btn label').innerHTML =
            document.getElementById(`table-layout-${this.layout}`).innerText
        if (this.layout === "auto")
            this.dialog.dialogEl.querySelector('#table-layout-btn').style.width = "105px"
        else
            this.dialog.dialogEl.querySelector('#table-layout-btn').style.width = "50px"
    }

    findTable(state) {
        const $head = state.selection.$head
        for (let d = $head.depth; d > 0; d--) if ($head.node(d).type.spec.tableRole == "table"){
            return {table: $head.node(d), tablePos: $head.before(d)}}
        return {table:false}
    }

    submitForm(){
        const {table, tablePos} = this.findTable(this.editor.currentView.state)
        if (!table) return
        const attrs = Object.assign({}, table.attrs, {
            width : this.width,
            aligned : this.width === "100" ? "center" : this.aligned,
            layout : this.layout
        })
        this.editor.currentView.dispatch(this.editor.currentView.state.tr.setNodeMarkup(tablePos, false, attrs))
    }

    insertDialog() {
        const buttons = []
        buttons.push({
            text: gettext('Update'),
            classes: 'fw-dark',
            click: () => {
                this.submitForm()
                this.dialog.close()
            }
        })
        buttons.push({
            type: 'cancel'
        })

        this.dialog = new Dialog({
            title: gettext('Resize table'),
            body: tableResizeTemplate(),
            width: 300,
            height: 260,
            buttons,
            onClose: () => this.editor.currentView.focus()
        })

        this.dialog.open()

        this.setTableAlignment()
        this.setTableWidth()
        this.setTableLayout()

        addDropdownBox(
            document.getElementById('table-alignment-btn'),
            document.getElementById('table-alignment-pulldown')
        )

        addDropdownBox(
            document.getElementById('table-width-btn'),
            document.getElementById('table-width-pulldown')
        )

        addDropdownBox(
            document.getElementById('table-layout-btn'),
            document.getElementById('table-layout-pulldown')
        )

        document.querySelectorAll('#table-alignment-pulldown li span').forEach(el => el.addEventListener(
            'click',
            event => {
                event.preventDefault()
                this.aligned = el.id.split('-')[2]
                this.setTableAlignment()
            }
        ))

        document.querySelectorAll('#table-width-pulldown li span').forEach(el => el.addEventListener(
            'click',
            event => {
                event.preventDefault()
                this.width = el.id.split('-')[2]
                this.setTableWidth()
            }
        ))

        document.querySelectorAll('#table-layout-pulldown li span').forEach(el => el.addEventListener(
            'click',
            event => {
                event.preventDefault()
                this.layout = el.id.split('-')[2]
                this.setTableLayout()
            }
        ))
    }
}
<|endoftext|>


<commit_before>'use strict';

(function() {

    angular
        .module('simpleArmoryApp')
        .factory('MountsAndPetsService', MountsAndPetsService);

    function MountsAndPetsService($http, $log, LoginService, $routeParams) {
        // issues/53: Pets that we can ignore warning for because they are battle pets
        var ignoredFoundPets =
        {
            10708:  true,
            132785: true,
            148065: true,
            148068: true,
            148069: true
        };

        return {
            getItems: function(jsonFile, characterProperty, collectedId) {
                return LoginService.getCharacter(
                        {
                            'region': $routeParams.region,
                            'realm':$routeParams.realm,
                            'character':$routeParams.character
                        })
                    .then(function(character) {
                        return $http.get('data/' + jsonFile + '.json', { cache: true, isArray:true })
                            .then(function(data) {

                                $log.log('Parsing ' + jsonFile + '.json...');
                                return parseItemsObject(data.data, character[0], characterProperty, collectedId);
                            });
                    });
            }
        };

        function parseItemsObject(categories, character, characterProperty, collectedId) {
            var obj = { 'categories': [] };
            var collected = {};
            var totalCollected = 0;
            var totalPossible = 0;
            var found = {};

            // Hack: Horde chopper doesn't show up, so we have to check for achievement and just assume they 'learned' it
            if (character.achievements.achievementsCompleted.indexOf(9909) >= 0) {
                collected[179244] = {
                    'spellid': '179244',
                    'allianceId': null,
                    'hordeId': null,
                    'itemId': '122703',
                    'icon': 'inv_misc_key_06',
                    'obtainable': true,
                    'allowableRaces': [
                        2,
                        5,
                        6,
                        8,
                        9,
                        10,
                        26
                    ],
                    'allowableClasses': null
                };
                found[179244] = false;
            }

            // Build up lookup for items that character has
            angular.forEach(character[characterProperty].collected, function(item) {
                collected[item[collectedId]] = item;
                found[item[collectedId]] = false;
            });

            // Lets parse out all the categories and build out our structure
            angular.forEach(categories, function(category) {

                // Add the item category to the item list
                var cat = { 'name': category.name, 'subCategories': [] };
                obj.categories.push(cat);

                angular.forEach(category.subcats, function(subCategory) {

                    var subCat = { 'name': subCategory.name, 'items':[] };

                    angular.forEach(subCategory.items, function(item) {

                        var itm = item;

                        // fix spellid typo
                        itm.spellId = item.spellid;
                        delete itm.spellid;

                        // Mark it found
                        found[itm[collectedId]] = true;

                        if (collected[itm[collectedId]]) {
                            var fullItem = collected[itm[collectedId]];
                            itm.collected =  true;

                            // Add pet info if we have it
                            if (fullItem.qualityId) {
                                var quality = '';
                                switch(fullItem.qualityId)
                                {
                                    case 0:
                                        quality = 'poor';
                                        break;
                                    case 1:
                                        quality = 'common';
                                        break;
                                    case 2:
                                        quality = 'uncommon';
                                        break;
                                    case 3:
                                        quality = 'rare';
                                        break;
                                    case 4:
                                        quality = 'epic';
                                        break;
                                    case 5:
                                        quality = 'legendary';
                                        break;
                                }

                                itm.quality = quality;
                            }

                            if (fullItem.stats) {
                                if (fullItem.stats.breedId) {
                                    var breed = '';
                                    switch(fullItem.stats.breedId)
                                    {
                                        case 4:
                                        case 14:
                                            breed = 'P/P';
                                            break;
                                        case 5:
                                        case 15:
                                            breed = 'S/S';
                                            break;
                                        case 6:
                                        case 16:
                                            breed = 'H/H';
                                            break;
                                        case 7:
                                        case 17:
                                            breed = 'H/P';
                                            break;
                                        case 8:
                                        case 18:
                                            breed = 'P/S';
                                            break;
                                        case 9:
                                        case 19:
                                            breed = 'H/S';
                                            break;
                                        case 10:
                                        case 20:
                                            breed = 'P/B';
                                            break;
                                        case 11:
                                        case 21:
                                            breed = 'S/B';
                                            break;
                                        case 12:
                                        case 22:
                                            breed = 'H/B';
                                            break;
                                        case 3:
                                        case 13:
                                            breed = 'B/B';
                                            break;
                                    }

                                    itm.breed = breed;
                                }

                                itm.level = fullItem.stats.level;
                            }
                        }

                        // Need to some extra work to determine what our url should be
                        // By default we'll use a spell id
                        var link = 'spell='+itm.spellId;

                        // If the item id is available lets use that
                        if (item.itemId) {
                            link = 'item='+item.itemId;
                        } else if (item.allianceId && (character.faction === 'A' || character.faction === 'Alliance')) {
                            link = 'item='+item.allianceId;
                        } else if (item.hordeId && (character.faction === 'H' || character.faction === 'Horde')) {
                            link = 'item='+item.hordeId;
                        } else if (item.creatureId) {
                            link = 'npc='+item.creatureId;
                        }

                        itm.link = link;

                        // What would cause it to show up in the UI:
                        //    1) You have the item
                        //    2) Its still obtainable
                        //    3) You meet the class restriction
                        //    4) You meet the race restriction
                        var hasthis = itm.collected;
                        var showthis = (hasthis || item.obtainable);
                        if (item.allowableRaces.length > 0)
                        {
                            var foundRace = false;
                            angular.forEach(item.allowableRaces, function(race) {
                                if (race === character.race) {
                                    foundRace = true;
                                }
                            });

                            if (!foundRace) {
                                showthis = false;
                            }
                        }

                        if (item.allowableClasses && item.allowableClasses.length > 0)
                        {
                            var foundClass = false;
                            angular.forEach(item.allowableClasses, function(allowedClass) {
                                if (allowedClass === character.class) {
                                    foundClass = true;
                                }
                            });

                            if (!foundClass) {
                                showthis = false;
                            }
                        }

                        if (showthis) {
                            subCat.items.push(itm);
                            if (hasthis) {
                                totalCollected++;
                            }

                            totalPossible++;
                        }
                    });

                    if (subCat.items.length > 0) {
                        cat.subCategories.push(subCat);
                    }
                });
            });

            // don't do this check for battle pets, I'm lazy and don't want to figure it out
            if (collectedId !== 'creatureId') {
                for (var collId in found) {
                    if (collId !== '0' && found.hasOwnProperty(collId) && !found[collId] && !ignoredFoundPets[collId]) {
                        console.log('WARN: Found item "' + collId + '" from character but not in db.');
                    }
                }
            }

            // Add totals
            obj.collected = totalCollected;
            obj.possible = totalPossible;
            obj.lookup = collected;

            // Add stuff that planner needs
            obj.isAlliance = (character.faction === 'A' || character.faction === 'Alliance');

            // Data object we expose externally
            return obj;
        }
    }

})();<commit_msg>Fixing missing mounts<commit_after>'use strict';

(function() {

    angular
        .module('simpleArmoryApp')
        .factory('MountsAndPetsService', MountsAndPetsService);

    function MountsAndPetsService($http, $log, LoginService, $routeParams) {
        // issues/53: Pets that we can ignore warning for because they are battle pets
        var ignoredFoundPets =
        {
            10708:  true,
            132785: true,
            148065: true,
            148068: true,
            148069: true
        };

        return {
            getItems: function(jsonFile, characterProperty, collectedId) {
                return LoginService.getCharacter(
                        {
                            'region': $routeParams.region,
                            'realm':$routeParams.realm,
                            'character':$routeParams.character
                        })
                    .then(function(character) {
                        return $http.get('data/' + jsonFile + '.json', { cache: true, isArray:true })
                            .then(function(data) {

                                $log.log('Parsing ' + jsonFile + '.json...');
                                return parseItemsObject(data.data, character[0], characterProperty, collectedId);
                            });
                    });
            }
        };

        function parseItemsObject(categories, character, characterProperty, collectedId) {
            var obj = { 'categories': [] };
            var collected = {};
            var totalCollected = 0;
            var totalPossible = 0;
            var found = {};

            // Build up lookup for items that character has
            angular.forEach(character[characterProperty].collected, function(item) {
                collected[item[collectedId]] = item;
                found[item[collectedId]] = false;
            });

            // Fix any problems blizzard has introduced
            applyHacks(character, collected, found);

            // Lets parse out all the categories and build out our structure
            angular.forEach(categories, function(category) {

                // Add the item category to the item list
                var cat = { 'name': category.name, 'subCategories': [] };
                obj.categories.push(cat);

                angular.forEach(category.subcats, function(subCategory) {

                    var subCat = { 'name': subCategory.name, 'items':[] };

                    angular.forEach(subCategory.items, function(item) {

                        var itm = item;

                        // fix spellid typo
                        itm.spellId = item.spellid;
                        delete itm.spellid;

                        // Mark it found
                        found[itm[collectedId]] = true;

                        if (collected[itm[collectedId]]) {
                            var fullItem = collected[itm[collectedId]];
                            itm.collected =  true;

                            // Add pet info if we have it
                            if (fullItem.qualityId) {
                                var quality = '';
                                switch(fullItem.qualityId)
                                {
                                    case 0:
                                        quality = 'poor';
                                        break;
                                    case 1:
                                        quality = 'common';
                                        break;
                                    case 2:
                                        quality = 'uncommon';
                                        break;
                                    case 3:
                                        quality = 'rare';
                                        break;
                                    case 4:
                                        quality = 'epic';
                                        break;
                                    case 5:
                                        quality = 'legendary';
                                        break;
                                }

                                itm.quality = quality;
                            }

                            if (fullItem.stats) {
                                if (fullItem.stats.breedId) {
                                    var breed = '';
                                    switch(fullItem.stats.breedId)
                                    {
                                        case 4:
                                        case 14:
                                            breed = 'P/P';
                                            break;
                                        case 5:
                                        case 15:
                                            breed = 'S/S';
                                            break;
                                        case 6:
                                        case 16:
                                            breed = 'H/H';
                                            break;
                                        case 7:
                                        case 17:
                                            breed = 'H/P';
                                            break;
                                        case 8:
                                        case 18:
                                            breed = 'P/S';
                                            break;
                                        case 9:
                                        case 19:
                                            breed = 'H/S';
                                            break;
                                        case 10:
                                        case 20:
                                            breed = 'P/B';
                                            break;
                                        case 11:
                                        case 21:
                                            breed = 'S/B';
                                            break;
                                        case 12:
                                        case 22:
                                            breed = 'H/B';
                                            break;
                                        case 3:
                                        case 13:
                                            breed = 'B/B';
                                            break;
                                    }

                                    itm.breed = breed;
                                }

                                itm.level = fullItem.stats.level;
                            }
                        }

                        // Need to some extra work to determine what our url should be
                        // By default we'll use a spell id
                        var link = 'spell='+itm.spellId;

                        // If the item id is available lets use that
                        if (item.itemId) {
                            link = 'item='+item.itemId;
                        } else if (item.allianceId && (character.faction === 'A' || character.faction === 'Alliance')) {
                            link = 'item='+item.allianceId;
                        } else if (item.hordeId && (character.faction === 'H' || character.faction === 'Horde')) {
                            link = 'item='+item.hordeId;
                        } else if (item.creatureId) {
                            link = 'npc='+item.creatureId;
                        }

                        itm.link = link;

                        // What would cause it to show up in the UI:
                        //    1) You have the item
                        //    2) Its still obtainable
                        //    3) You meet the class restriction
                        //    4) You meet the race restriction
                        var hasthis = itm.collected;
                        var showthis = (hasthis || item.obtainable);
                        if (item.allowableRaces.length > 0)
                        {
                            var foundRace = false;
                            angular.forEach(item.allowableRaces, function(race) {
                                if (race === character.race) {
                                    foundRace = true;
                                }
                            });

                            if (!foundRace) {
                                showthis = false;
                            }
                        }

                        if (item.allowableClasses && item.allowableClasses.length > 0)
                        {
                            var foundClass = false;
                            angular.forEach(item.allowableClasses, function(allowedClass) {
                                if (allowedClass === character.class) {
                                    foundClass = true;
                                }
                            });

                            if (!foundClass) {
                                showthis = false;
                            }
                        }

                        if (showthis) {
                            subCat.items.push(itm);
                            if (hasthis) {
                                totalCollected++;
                            }

                            totalPossible++;
                        }
                    });

                    if (subCat.items.length > 0) {
                        cat.subCategories.push(subCat);
                    }
                });
            });

            // don't do this check for battle pets, I'm lazy and don't want to figure it out
            if (collectedId !== 'creatureId') {
                for (var collId in found) {
                    if (collId !== '0' && found.hasOwnProperty(collId) && !found[collId] && !ignoredFoundPets[collId]) {
                        console.log('WARN: Found item "' + collId + '" from character but not in db.');
                    }
                }
            }

            // Add totals
            obj.collected = totalCollected;
            obj.possible = totalPossible;
            obj.lookup = collected;

            // Add stuff that planner needs
            obj.isAlliance = (character.faction === 'A' || character.faction === 'Alliance');

            // Data object we expose externally
            return obj;
        }

        function applyHacks(character, collected, found) {
            // Hack: Horde chopper doesn't show up, so we have to check for achievement and just assume they 'learned' it
            if (character.achievements.achievementsCompleted.indexOf(9909) >= 0) {
                collected[179244] = {
                    'spellid': '179244',
                    'allianceId': null,
                    'hordeId': null,
                    'itemId': '122703',
                    'icon': 'inv_misc_key_06',
                    'obtainable': true,
                    'allowableRaces': [
                        2,
                        5,
                        6,
                        8,
                        9,
                        10,
                        26
                    ],
                    'allowableClasses': null
                };
                found[179244] = false;
            }

            // Brown Horse (if you have all the other horses, you get this.  Oprah would approve)
            if (!collected[458] && collected[23227] && collected[23229] &&
                 collected[23228] && collected[6648] && collected[470] && collected[472]) {

                console.log('Hack: Blizzard still has the brown horse bug');

                collected[458] = {
                    'spellid': '458',
                    'allianceId': null,
                    'hordeId': null,
                    'itemId': '5656',
                    'icon': 'ability_mount_ridinghorse',
                    'obtainable': true,
                    'allowableRaces': [
                        1,
                        3,
                        4,
                        7,
                        11,
                        22,
                        25
                    ],
                    'allowableClasses': null
                };
                found[458] = false;
            }

            // Swift Warstrider (same problem as brown horse)
            if (!collected[35028] && collected[22718] && collected[22724] &&
                 collected[22722] && collected[22721] && collected[23509] && collected[59788]) {

                console.log('Hack: Blizzard still has the swift warstrider bug');

                collected[35028] = {
                    'spellid': '35028',
                    'allianceId': null,
                    'hordeId': null,
                    'itemId': '34129',
                    'icon': 'ability_mount_cockatricemountelite_black',
                    'obtainable': true,
                    'allowableRaces': [
                        2,
                        5,
                        6,
                        8,
                        9,
                        10,
                        26
                    ],
                    'allowableClasses': null
                };
                found[35028] = false;
            }
        }
    }

})();<|endoftext|>


<commit_before>import { NodeComponent } from 'substance'
import katex from 'katex'

export default class InlineFormulaComponent extends NodeComponent {

  render($$) {
    const node = this.props.node
    // TODO: Find out why node.find('tex-math') returns null here
    const texMath = node.findChild('tex-math').textContent
    // TODO: Use KaTeX

    const el = $$('span').addClass('sc-math')

    if (this.props.isolatedNodeState) {
      el.addClass('sm-'+this.props.isolatedNodeState)
    }

    try {
      el.append(
        $$('span').html(katex.renderToString(texMath))

      )
      let blockerEl = $$('div').addClass('se-blocker')
      el.append(blockerEl)
    } catch (error) {
      el.addClass('sm-error')
        .text(error.message)
    }

    return el
  }
}
<commit_msg>Use separate component for TexMath, so model changes lead to a rerender.<commit_after>import { NodeComponent } from 'substance'
import katex from 'katex'

export default class InlineFormulaComponent extends NodeComponent {

  render($$) {
    const node = this.props.node
    // TODO: Find out why node.find('tex-math') returns null here
    const texMath = node.findChild('tex-math')
    const el = $$('span').addClass('sc-inline-formula')
    el.append(
      $$(TexMathComponent, {
        node: texMath
      })
    )
    if (this.props.isolatedNodeState) {
      el.addClass('sm-'+this.props.isolatedNodeState)
    }
    return el
  }
}

class TexMathComponent extends NodeComponent {
  render($$) {
    const node = this.props.node
    const texMath = node.textContent
    const el = $$('span').addClass('sc-math')
    try {
      el.append(
        $$('span').html(katex.renderToString(texMath))

      )
      let blockerEl = $$('div').addClass('se-blocker')
      el.append(blockerEl)
    } catch (error) {
      el.addClass('sm-error')
        .text(error.message)
    }

    return el
  }
}
<|endoftext|>


<commit_before>sap.ui.define([
   'sap/ui/core/mvc/Controller',
   'sap/m/Button',
   'sap/m/ButtonRenderer',
   'sap/m/Dialog',
   'sap/ui/commons/ColorPicker'
], function (Controller, Button, ButtonRenderer, Dialog, ColorPicker) {
   "use strict";

   var ColorButton = Button.extend("sap.ui.jsroot.ColorButton", {
      metadata: {
         properties: {
            attrcolor : {type : "string", group : "Misc", defaultValue : null}
         }
      },
      renderer: ButtonRenderer.render,
      init: function() {
         // svg images are always loaded without @2
         this.addEventDelegate({
            onAfterRendering: function() { this._setColor(); }
         }, this);
      }

   });

   ColorButton.prototype._setColor = function() {
      this.$().children().css('background-color', this.getProperty("attrcolor"));
   }

   ColorButton.prototype.firePress = function(args) {
      // if (Button.prototype.firePress)
      //   Button.prototype.firePress.call(this, args);

      var that = this;

      if (!this.colorPicker)
         this.colorPicker = new ColorPicker();

      if (!this.colorDialog) {
         this.colorDialog = new Dialog({
            title: 'Select color',
            content: this.colorPicker,
            beginButton: new Button({
               text: 'Apply',
               press: function () {
                  if (that.colorPicker) {
                     var col = that.colorPicker.getColorString();
                      that.setProperty("attrcolor", col);
                  }
                  that.colorDialog.close();
               }
            }),
            endButton: new Button({
               text: 'Cancel',
               press: function () {
                  that.colorDialog.close();
               }
            })
         });
      }

      var col = this.getProperty("attrcolor");

      this.colorPicker.setColorString(col);
      this.colorDialog.open();
   }

   return ColorButton;

});
<commit_msg>Small formatting<commit_after>sap.ui.define([
   'sap/ui/core/mvc/Controller',
   'sap/m/Button',
   'sap/m/ButtonRenderer',
   'sap/m/Dialog',
   'sap/ui/commons/ColorPicker'
], function (Controller, Button, ButtonRenderer, Dialog, ColorPicker) {

   "use strict";

   var ColorButton = Button.extend("sap.ui.jsroot.ColorButton", {
      metadata: {
         properties: {
            attrcolor : { type : "string", group : "Misc", defaultValue : null }
         }
      },
      renderer: ButtonRenderer.render,
      init: function() {
         // svg images are always loaded without @2
         this.addEventDelegate({
            onAfterRendering: function() { this._setColor(); }
         }, this);
      }
   });

   ColorButton.prototype._setColor = function() {
      this.$().children().css('background-color', this.getProperty("attrcolor"));
   }

   ColorButton.prototype.firePress = function(args) {
      // if (Button.prototype.firePress)
      //   Button.prototype.firePress.call(this, args);

      var that = this;

      if (!this.colorPicker)
         this.colorPicker = new ColorPicker();

      if (!this.colorDialog) {
         this.colorDialog = new Dialog({
            title: 'Select color',
            content: this.colorPicker,
            beginButton: new Button({
               text: 'Apply',
               press: function () {
                  if (that.colorPicker) {
                     var col = that.colorPicker.getColorString();
                      that.setProperty("attrcolor", col);
                  }
                  that.colorDialog.close();
               }
            }),
            endButton: new Button({
               text: 'Cancel',
               press: function () {
                  that.colorDialog.close();
               }
            })
         });
      }

      var col = this.getProperty("attrcolor");

      this.colorPicker.setColorString(col);
      this.colorDialog.open();
   }

   return ColorButton;

});
<|endoftext|>


<commit_before>
const send = require('../../fb/send/');
const msg = require('../../fb/assemble/')
const modeManager = require('../GuidedMode');

let state = '';

let tutorial = {

  timeline: [
    {
      introduction: (userId) => {
         const introPromise = send(msg.text('Hi developer,')).to(userId).then(()=>{
           return send(msg.text('I\'m Starbot. Hopefully I\'ll be making your life a tad bit easier.')).to(userId).then(() => {
             return send(msg.text('Lets start with Persistent Menus.')).to(userId);
           });
         });
         introPromise.then(() => {
           console.log('Promises Called');
         })
        //  modeManager.nextState(userId);
      }
    },
    {
      persistentMenu: (userId) => {
        send(msg.text('We will talk about the Persistent Menu Here')).to(userId);

      }
    },
    {
      contentTypes: (userId) => {
        send(msg.text('We will talk about various content types next')).to(userId);
      }
    },
    {
      staticImages: (userId) => {
        send(msg.text('Let me show you a static image!')).to(userId);
        send(msg.image('https://img.grouponcdn.com/deal/iTzVW4nyCypjLANEjKKF/YC-2048x1229.jpg/v1/c700x420.jpg')).to(userId);
      }
    },
    {
      pngFiles: () => {}
    },
    {
      animatedGifs: () => {}
    },
    {
      audio: () => {}
    },
    {
      video: () => {}
    },
    {
      miscFiles: () => {}
    },
    {
      structuredMessages: () => {}
    },
    {
      basicTemplate: () => {}
    },
    {
      articleLink: () => {}
    },
    {
      webview: () => {}
    },
    {
      instantArticles: () => {}
    },
    {
      articleLists: () => {}
    },
    {
      partnerContent: () => {}
    },
    {
      quickReplies: () => {}
    },
    {
      breakingNews: () => {}
    },
    {
      profileBuilding: () => {}
    },
    {
      opinionPolling: () => {}
    },
    {
      subscriptions: () => {}
    },
    {
      conclusion: () => {}
    }
  ]

};

// console.log(Object.getOwnPropertyNames(tutorial.timeline[0])[0]);

//
// tutorial.timeline.forEach((obj) => {
//   console.log(obj, state);
//   console.log(obj[Object.getOwnPropertyNames(obj)[0]]());
// })

module.exports = tutorial;

// console.log(modeManager.setMode);
<commit_msg>No longer returning promises<commit_after>
const send = require('../../fb/send/');
const msg = require('../../fb/assemble/')
const modeManager = require('../GuidedMode');

let state = '';

let tutorial = {

  timeline: [
    {
      introduction: (userId) => {
         send(msg.text('Hi developer,')).to(userId).then(()=>{
           send(msg.text('I\'m Starbot. Hopefully I\'ll be making your life a tad bit easier.')).to(userId).then(() => {
             send(msg.text('Lets start with Persistent Menus.')).to(userId);
           });
         });
        //  introPromise.then(() => {
        //    console.log('Promises Called');
        //  })
        //  modeManager.nextState(userId);
      }
    },
    {
      persistentMenu: (userId) => {
        send(msg.text('We will talk about the Persistent Menu Here')).to(userId);

      }
    },
    {
      contentTypes: (userId) => {
        send(msg.text('We will talk about various content types next')).to(userId);
      }
    },
    {
      staticImages: (userId) => {
        send(msg.text('Let me show you a static image!')).to(userId);
        send(msg.image('https://img.grouponcdn.com/deal/iTzVW4nyCypjLANEjKKF/YC-2048x1229.jpg/v1/c700x420.jpg')).to(userId);
      }
    },
    {
      pngFiles: () => {}
    },
    {
      animatedGifs: () => {}
    },
    {
      audio: () => {}
    },
    {
      video: () => {}
    },
    {
      miscFiles: () => {}
    },
    {
      structuredMessages: () => {}
    },
    {
      basicTemplate: () => {}
    },
    {
      articleLink: () => {}
    },
    {
      webview: () => {}
    },
    {
      instantArticles: () => {}
    },
    {
      articleLists: () => {}
    },
    {
      partnerContent: () => {}
    },
    {
      quickReplies: () => {}
    },
    {
      breakingNews: () => {}
    },
    {
      profileBuilding: () => {}
    },
    {
      opinionPolling: () => {}
    },
    {
      subscriptions: () => {}
    },
    {
      conclusion: () => {}
    }
  ]

};

// console.log(Object.getOwnPropertyNames(tutorial.timeline[0])[0]);

//
// tutorial.timeline.forEach((obj) => {
//   console.log(obj, state);
//   console.log(obj[Object.getOwnPropertyNames(obj)[0]]());
// })

module.exports = tutorial;

// console.log(modeManager.setMode);
<|endoftext|>


<commit_before>var backbone = require('backbone');
var backboneBase = require('backbone-base');
var jsonEditor = require('json-editor');
var highlight = require('highlight-redux');
var UploadView = require('./upload');
var registry = require('./registry');
var _ = require('underscore');
var $ = require('jquery');

// Upload data file and populate .resource array with item
DataUploadView = backbone.BaseView.extend({
  events: {
    'click [data-id=upload-data-file]': function() { this.$('[data-id=input]').trigger('click'); }
  },

  render: function() {
    this.$el
      .append('<input data-id="input" type="file" style="display: none;">')

      .append(
        $(this.options.form.theme.getButton('Upload data file', '', 'Upload data file'))
          .attr('data-id', 'upload-data-file')
      );

    return this;
  }
});

module.exports = {
  DescriptorEditView: backbone.BaseView.extend({
    activate: function(state) {
      backbone.BaseView.prototype.activate.call(this, state);
      this.layout.upload.activate(state);
      return this;
    },

    initialize: function() {
      highlight.configure({useBR: true});
      return backbone.BaseView.prototype.initialize.apply(this, arguments);
    },

    render: function() {
      this.layout.upload = new UploadView({el: window.APP.$('#upload-data-package'), parent: this});
      this.layout.registryList = new registry.ListView({el: window.APP.$('#registry-list'), parent: this});
      return this;
    },

    // Utility method to remove empty values from object recursive
    compactObject: function(data) {
      _.each(data, function(v, k) {
        if(_.isEmpty(v)) {
          delete data[k];
        } else if(_.isArray(v) || _.isObject(v)) {
          v = this.compactObject(v);

          if(_.isArray(v))
            v = _.compact(v);

          if(_.isEmpty(v))
            delete data[k];
          else data[k] = v;
        }
      }, this);
      return data;
    },

    getFilledValues: function() { return this.compactObject(this.layout.form.getValue()); },
    getValue: function () { return this.layout.form.getValue(); },
    hasChanges: function() { return Boolean(this.changed); },

    reset: function(schema) {
      var formData;

      // Clean up previous state
      if(this.layout.form) {
        formData = this.getFilledValues();
        this.layout.form.destroy();
        this.layout.uploadData.undelegateEvents().remove();
      }

      this.layout.form = new JSONEditor(this.el, {
        schema: schema,
        theme: 'bootstrap3'
      });

      this.layout.uploadData = (new DataUploadView({
        el: this.layout.form.theme.getHeaderButtonHolder(),
        form: this.layout.form,
        parent: this
      })).render();

      this.layout.form.on('ready', (function() {
        // There is no any good way to bind events to custom button or even add cutsom button
        $(this.layout.form.getEditor('root.resources').container)
          .children('h3').append(this.layout.uploadData.el);

        // Detecting changes
        this.changed = false;

        // After `ready` event fired, editor fire `change` event regarding to the initial changes
        this.layout.form.on('change', _.after(2, (function() {
          this.changed = true;
          window.APP.layout.download.reset(this.layout.form.getValue()).activate();
          this.showResult();
        }).bind(this)));

        // If on the previous form was entered values try to apply it to new form
        if(formData)
          this.layout.form.setValue(_.extend({}, this.layout.form.getValue(formData), formData));
      }).bind(this));
    },

    showResult: function() {
      $('#json-code').html(highlight.fixMarkup(
        highlight.highlight('json', JSON.stringify(this.layout.form.getValue(), undefined, 2)).value
      ));

      return this;
    }
  })
};<commit_msg>Code formatting<commit_after>var backbone = require('backbone');
var backboneBase = require('backbone-base');
var jsonEditor = require('json-editor');
var highlight = require('highlight-redux');
var UploadView = require('./upload');
var registry = require('./registry');
var _ = require('underscore');
var $ = require('jquery');

// Upload data file and populate .resource array with item
DataUploadView = backbone.BaseView.extend({
  events: {
    'click [data-id=upload-data-file]': function() { this.$('[data-id=input]').trigger('click'); }
  },

  render: function() {
    this.$el
      .append('<input data-id="input" type="file" style="display: none;">')

      .append(
        $(this.options.form.theme.getButton('Upload data file', '', 'Upload data file'))
          .attr('data-id', 'upload-data-file')
      );

    return this;
  }
});

module.exports = {
  DescriptorEditView: backbone.BaseView.extend({
    activate: function(state) {
      backbone.BaseView.prototype.activate.call(this, state);
      this.layout.upload.activate(state);
      return this;
    },

    initialize: function() {
      highlight.configure({useBR: true});
      return backbone.BaseView.prototype.initialize.apply(this, arguments);
    },

    render: function() {
      this.layout.upload = new UploadView({el: window.APP.$('#upload-data-package'), parent: this});
      this.layout.registryList = new registry.ListView({el: window.APP.$('#registry-list'), parent: this});
      return this;
    },

    // Utility method to remove empty values from object recursive
    compactObject: function(data) {
      _.each(data, function(v, k) {
        if(_.isEmpty(v)) {
          delete data[k];
        } else if(_.isArray(v) || _.isObject(v)) {
          v = this.compactObject(v);

          if(_.isArray(v))
            v = _.compact(v);

          if(_.isEmpty(v))
            delete data[k];
          else data[k] = v;
        }
      }, this);

      return data;
    },

    getFilledValues: function() { return this.compactObject(this.layout.form.getValue()); },
    getValue: function () { return this.layout.form.getValue(); },
    hasChanges: function() { return Boolean(this.changed); },

    reset: function(schema) {
      var formData;

      // Clean up previous state
      if(this.layout.form) {
        formData = this.getFilledValues();
        this.layout.form.destroy();
        this.layout.uploadData.undelegateEvents().remove();
      }

      this.layout.form = new JSONEditor(this.el, {
        schema: schema,
        theme: 'bootstrap3'
      });

      this.layout.uploadData = (new DataUploadView({
        el: this.layout.form.theme.getHeaderButtonHolder(),
        form: this.layout.form,
        parent: this
      })).render();

      this.layout.form.on('ready', (function() {
        // There is no any good way to bind events to custom button or even add cutsom button
        $(this.layout.form.getEditor('root.resources').container)
          .children('h3').append(this.layout.uploadData.el);

        // Detecting changes
        this.changed = false;

        // After `ready` event fired, editor fire `change` event regarding to the initial changes
        this.layout.form.on('change', _.after(2, (function() {
          this.changed = true;
          window.APP.layout.download.reset(this.layout.form.getValue()).activate();
          this.showResult();
        }).bind(this)));

        // If on the previous form was entered values try to apply it to new form
        if(formData)
          this.layout.form.setValue(_.extend({}, this.layout.form.getValue(formData), formData));
      }).bind(this));
    },

    showResult: function() {
      $('#json-code').html(highlight.fixMarkup(
        highlight.highlight('json', JSON.stringify(this.layout.form.getValue(), undefined, 2)).value
      ));

      return this;
    }
  })
};<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';

class Box extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return(

hello

    );
  }
}

ReactDOM.render(<Box />, document.getElementById('root'));
<commit_msg>Rename Box to Root<commit_after>import React from 'react';
import ReactDOM from 'react-dom';

class Root extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return(

hello

    );
  }
}

ReactDOM.render(<Root />, document.getElementById('root'));
<|endoftext|>