<commit_before>/*!
 * dimsum.js v0.1
 * https://github.com/ninjascribble/dimsum
 * MIT licensed
 *
 * Copyright (C) 2012 Scott Grogan, http://ninjascript.com
 */
;(function(global) {

var classic = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",

cicero_1_10_32 = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",

cicero_1_10_33 = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.",

jabberwocky = "'Twas brillig, and the slithy toves Did gyre and gimble in the wabe; All mimsy were the borogoves, And the mome raths outgrabe. Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch! He took his vorpal sword in hand: Long time the manxome foe he sought So rested he by the Tumtum tree, And stood awhile in thought. And as in uffish thought he stood, The Jabberwock, with eyes of flame, Came whiffling through the tulgey wood, And burbled as it came! One, two! One, two! and through and through The vorpal blade went snicker-snack! He left it dead, and with its head He went galumphing back. And hast thou slain the Jabberwock? Come to my arms, my beamish boy! O frabjous day! Callooh! Callay! He chortled in his joy. 'Twas brillig, and the slithy toves Did gyre and gimble in the wabe; All mimsy were the borogoves, And the mome raths outgrabe.",

defaults = {
    'format': 'text',
    'flavor': 'latin',
    'sentences_per_paragraph': [3, 5],
    'words_per_sentence': [10, 31],
    'commas_per_sentence': [0, 4]
},

config = {},

punct = [',','.',';',':','?','!','"','—','\r','\n'],

punct_reg = new RegExp('[' + punct.join('') + ']*','g'),

flavors = {
    'latin': dedupe( normify([classic, cicero_1_10_32, cicero_1_10_33]).split(' ') ),
    'jabberwocky': dedupe( normify([jabberwocky]).split(' ') )
},

dimsum = global.dimsum = exports = function(num_paragraphs, options) {
    return dimsum.generate(num_paragraphs, options);
};

// For client-side compatibility
if (typeof module !== 'undefined') module.exports = dimsum;

/**
 * The standard Lorem Ipsum passage.
 */
dimsum.classic = function() {
    return classic;
};

/**
 * Section 1.10.32 of Cicero's "de Finibus Bonorum et Malorum".
 */
dimsum.cicero32 = function() {
    return cicero_1_10_32;
};

/**
 * Section 1.10.33 of Cicero's "de Finibus Bonorum et Malorum".
 */
dimsum.cicero33 = function() {
    return cicero_1_10_33;
};

/**
 * Restore default configuration.
 */
dimsum.initialize = function() {
    return this.configure(defaults);
};

/**
 * Override the current configuration.
 *
 * @param options
 *      An object containing new config values.
 */
dimsum.configure = function(options) {
    config = shallow_copy(config, options);
    return this;
};

/**
 * @return A list of flavors that are currently available.
 */
dimsum.flavors = function() {
    return Object.keys(flavors);
};

/**
 * Creates a flavor out of the ingredients.
 *
 * @return An array containing the words used in this flavor.
 */
dimsum.flavor = function(name, ingredients) {

    if (arguments.length == 0) {
        return;
    }
    else if (arguments.length == 1) {

        if (name.match(/\s/)) {
            return dedupe( normify([name]).split(' ') );
        }
        else {
            return flavors[name];
        }
    }
    else {
        flavors[name] = (typeof ingredients == 'Array') ? ingredients : dedupe( normify([ingredients]).split(' ') );
        return flavors[name];
    }
};

/**
 * Create a random chunk of lipsum. Returns a string containing
 * the number of paragraphs specified.
 *
 * @param num_paragraphs
 *      How many paragraphs to generate.
 *
 * @param options
 *      An object containing new config values. The new options
 *      will only apply to this one execution.
 */
dimsum.generate = function(num_paragraphs, options) {

    var config_1 = config,
        sentences = [],
        paragraphs = [],
        result = '',
        num_paragraphs = num_paragraphs || 1;

    // Shift args if only an options arg is passed
    if (typeof num_paragraphs == 'object') {
        options = num_paragraphs;
        num_paragraphs = 1;
    }

    // Temporarily overwrite the configuration
    this.configure(options);

    // Add some paragraphs
    while (paragraphs.length < num_paragraphs) {
        paragraphs.push(this.paragraph());
    }

    // Make it pretty
    switch(config.format) {
        case 'text':
            result = paragraphs.join("\r\n\r\n");
            break;
        case 'html':
            result = '
' + paragraphs.join('

') + '
';
            break;
    }

    // Restore the original configuration
    config = config_1;

    return result;
};

/**
 * Create a single sentence of random lipsum.
 */
dimsum.sentence = function() {

    var word = '',
        words = [],
        num_words = range(config.words_per_sentence[0], config.words_per_sentence[1]),
        num_commas = range(config.commas_per_sentence[0], config.commas_per_sentence[1]),
        flavor = flavors[config.flavor];

    // Get some words
    while (words.length < num_words) {
        word = flavor[ range(0, flavor.length -1) ];
        words.push(word);
    }

    // Add some commas
    for (var i = 0; i < num_commas; i++) {
        word = range(4, words.length - 3);
        if (!words[word]) {
            break;
        }
        else if (words[word].match(',')) {
            i--;
        }
        else {
            words[word] += ',';
        }
    }

    // Capitalize the first word
    words = words.join(' ');
    words = words.replace(/^[a-z]/i, words[0].toUpperCase());

    // Punctuate and return
    return words + '.';
};

/**
 * Create a single paragraph of random lipsum.
 */
dimsum.paragraph = function() {

    var sentences = [],
        num_sentences = range(config.sentences_per_paragraph[0], config.sentences_per_paragraph[1]);

    while (sentences.length < num_sentences) {
        sentences.push(this.sentence());
    }
    return sentences.join(' ');
};

/**
 * Replace any ocurrences of {{dimsum}} with generated text.
 */
dimsum.parse = function(root) {

    var reg = /{{dimsum[:]?([pst0-9]*)}}/ig,
        root = root || document.getElementsByTagName('body')[0],
        command = '';

    // If root is just a string, then return a string with replacement
    if (typeof root == 'string') {
        return root.replace(reg, function(m, sm) {
            return make_dimsum(sm, 'text');
        });
    }

    // If it's a TextNode, then make sure it matches and replace it with some markup
    else if (root.nodeType == 3 && root.data.match(reg)) {

        console.log(root.data);

        var div = document.createElement('div');

        div.className = 'dimsum';
        div.innerHTML = root.data.replace(reg, function(m, sm) {
            return make_dimsum(sm, 'html');
        });

        root.parentNode.insertBefore(div, root);
        root.parentNode.removeChild(root);
    }

    // If it's not a TextNode, then keep on walking the DOM
    else {
        for (var i = 0, len = root.childNodes.length; i < len; i++) {
            dimsum.parse(root.childNodes[i]);
        }
    }
};

dimsum.initialize();

if ('document' in this) {
    this.document.addEventListener('DOMContentLoaded', function() {
        dimsum.parse(document.getElementsByTagName('body')[0]);
    });
}

/** Utils **/
function normify(strings) {
    return strings.join(' ')
            .toLowerCase()
            .replace(punct_reg, function(match) {
                if (match.match(/\r|\n/)) {
                    return ' ';
                }
                else {
                    return '';
                }
            });
};

function dedupe(array) {

    var obj = {},
        result = [];

    for (var i = 0; i < array.length; i++) {
        obj[array[i]] = null;
    }
    for (key in obj) {
        result.push(key);
    }
    return result;
};

function range(min, max) {
    return min + Math.random() * (max - min) << 0;
};

function shallow_copy() {

    var i, key, result = {},
        args = Array.prototype.slice.call(arguments);

    for (i = 0; i < args.length; i++) {
        for (key in args[i]) {
            result[key] = args[i][key];
        }
    }
    return result;
};

function make_dimsum(shorthand, format) {

    var shorthand = shorthand || '',
        format = format || 'text',
        type = shorthand[0] || 'p',
        len = parseInt( shorthand.slice(1, shorthand.length) ) || 1,
        i = 0,
        result = [];

    switch (type) {

        case 'p':
            result.push(dimsum(len, { format: format }));
            break;

        case 's':
            for (i; i < len; i++) {
                result.push(dimsum.sentence());
            }
            if (format == 'html') {
                result.unshift('
');
                result.push('
');
            }
            break;

        default:
            break;
    }

    return result.join(' ');
};

/* Debug */
// dimsum.normify = normify;
// dimsum.dedupe = dedupe;
// dimsum.range = range;
// dimsum.shallow_copy = shallow_copy;

}(this));<commit_msg>Removing erroneous console.log statement<commit_after>/*!
 * dimsum.js v0.1
 * https://github.com/ninjascribble/dimsum
 * MIT licensed
 *
 * Copyright (C) 2012 Scott Grogan, http://ninjascript.com
 */
;(function(global) {

var classic = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",

cicero_1_10_32 = "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?",

cicero_1_10_33 = "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.",

jabberwocky = "'Twas brillig, and the slithy toves Did gyre and gimble in the wabe; All mimsy were the borogoves, And the mome raths outgrabe. Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch! He took his vorpal sword in hand: Long time the manxome foe he sought So rested he by the Tumtum tree, And stood awhile in thought. And as in uffish thought he stood, The Jabberwock, with eyes of flame, Came whiffling through the tulgey wood, And burbled as it came! One, two! One, two! and through and through The vorpal blade went snicker-snack! He left it dead, and with its head He went galumphing back. And hast thou slain the Jabberwock? Come to my arms, my beamish boy! O frabjous day! Callooh! Callay! He chortled in his joy. 'Twas brillig, and the slithy toves Did gyre and gimble in the wabe; All mimsy were the borogoves, And the mome raths outgrabe.",

defaults = {
    'format': 'text',
    'flavor': 'latin',
    'sentences_per_paragraph': [3, 5],
    'words_per_sentence': [10, 31],
    'commas_per_sentence': [0, 4]
},

config = {},

punct = [',','.',';',':','?','!','"','—','\r','\n'],

punct_reg = new RegExp('[' + punct.join('') + ']*','g'),

flavors = {
    'latin': dedupe( normify([classic, cicero_1_10_32, cicero_1_10_33]).split(' ') ),
    'jabberwocky': dedupe( normify([jabberwocky]).split(' ') )
},

dimsum = global.dimsum = exports = function(num_paragraphs, options) {
    return dimsum.generate(num_paragraphs, options);
};

// For client-side compatibility
if (typeof module !== 'undefined') module.exports = dimsum;

/**
 * The standard Lorem Ipsum passage.
 */
dimsum.classic = function() {
    return classic;
};

/**
 * Section 1.10.32 of Cicero's "de Finibus Bonorum et Malorum".
 */
dimsum.cicero32 = function() {
    return cicero_1_10_32;
};

/**
 * Section 1.10.33 of Cicero's "de Finibus Bonorum et Malorum".
 */
dimsum.cicero33 = function() {
    return cicero_1_10_33;
};

/**
 * Restore default configuration.
 */
dimsum.initialize = function() {
    return this.configure(defaults);
};

/**
 * Override the current configuration.
 *
 * @param options
 *      An object containing new config values.
 */
dimsum.configure = function(options) {
    config = shallow_copy(config, options);
    return this;
};

/**
 * @return A list of flavors that are currently available.
 */
dimsum.flavors = function() {
    return Object.keys(flavors);
};

/**
 * Creates a flavor out of the ingredients.
 *
 * @return An array containing the words used in this flavor.
 */
dimsum.flavor = function(name, ingredients) {

    if (arguments.length == 0) {
        return;
    }
    else if (arguments.length == 1) {

        if (name.match(/\s/)) {
            return dedupe( normify([name]).split(' ') );
        }
        else {
            return flavors[name];
        }
    }
    else {
        flavors[name] = (typeof ingredients == 'Array') ? ingredients : dedupe( normify([ingredients]).split(' ') );
        return flavors[name];
    }
};

/**
 * Create a random chunk of lipsum. Returns a string containing
 * the number of paragraphs specified.
 *
 * @param num_paragraphs
 *      How many paragraphs to generate.
 *
 * @param options
 *      An object containing new config values. The new options
 *      will only apply to this one execution.
 */
dimsum.generate = function(num_paragraphs, options) {

    var config_1 = config,
        sentences = [],
        paragraphs = [],
        result = '',
        num_paragraphs = num_paragraphs || 1;

    // Shift args if only an options arg is passed
    if (typeof num_paragraphs == 'object') {
        options = num_paragraphs;
        num_paragraphs = 1;
    }

    // Temporarily overwrite the configuration
    this.configure(options);

    // Add some paragraphs
    while (paragraphs.length < num_paragraphs) {
        paragraphs.push(this.paragraph());
    }

    // Make it pretty
    switch(config.format) {
        case 'text':
            result = paragraphs.join("\r\n\r\n");
            break;
        case 'html':
            result = '
' + paragraphs.join('

') + '
';
            break;
    }

    // Restore the original configuration
    config = config_1;

    return result;
};

/**
 * Create a single sentence of random lipsum.
 */
dimsum.sentence = function() {

    var word = '',
        words = [],
        num_words = range(config.words_per_sentence[0], config.words_per_sentence[1]),
        num_commas = range(config.commas_per_sentence[0], config.commas_per_sentence[1]),
        flavor = flavors[config.flavor];

    // Get some words
    while (words.length < num_words) {
        word = flavor[ range(0, flavor.length -1) ];
        words.push(word);
    }

    // Add some commas
    for (var i = 0; i < num_commas; i++) {
        word = range(4, words.length - 3);
        if (!words[word]) {
            break;
        }
        else if (words[word].match(',')) {
            i--;
        }
        else {
            words[word] += ',';
        }
    }

    // Capitalize the first word
    words = words.join(' ');
    words = words.replace(/^[a-z]/i, words[0].toUpperCase());

    // Punctuate and return
    return words + '.';
};

/**
 * Create a single paragraph of random lipsum.
 */
dimsum.paragraph = function() {

    var sentences = [],
        num_sentences = range(config.sentences_per_paragraph[0], config.sentences_per_paragraph[1]);

    while (sentences.length < num_sentences) {
        sentences.push(this.sentence());
    }
    return sentences.join(' ');
};

/**
 * Replace any ocurrences of {{dimsum}} with generated text.
 */
dimsum.parse = function(root) {

    var reg = /{{dimsum[:]?([pst0-9]*)}}/ig,
        root = root || document.getElementsByTagName('body')[0],
        command = '';

    // If root is just a string, then return a string with replacement
    if (typeof root == 'string') {
        return root.replace(reg, function(m, sm) {
            return make_dimsum(sm, 'text');
        });
    }

    // If it's a TextNode, then make sure it matches and replace it with some markup
    else if (root.nodeType == 3 && root.data.match(reg)) {

        var div = document.createElement('div');

        div.className = 'dimsum';
        div.innerHTML = root.data.replace(reg, function(m, sm) {
            return make_dimsum(sm, 'html');
        });

        root.parentNode.insertBefore(div, root);
        root.parentNode.removeChild(root);
    }

    // If it's not a TextNode, then keep on walking the DOM
    else {
        for (var i = 0, len = root.childNodes.length; i < len; i++) {
            dimsum.parse(root.childNodes[i]);
        }
    }
};

dimsum.initialize();

if ('document' in this) {
    this.document.addEventListener('DOMContentLoaded', function() {
        dimsum.parse(document.getElementsByTagName('body')[0]);
    });
}

/** Utils **/
function normify(strings) {
    return strings.join(' ')
            .toLowerCase()
            .replace(punct_reg, function(match) {
                if (match.match(/\r|\n/)) {
                    return ' ';
                }
                else {
                    return '';
                }
            });
};

function dedupe(array) {

    var obj = {},
        result = [];

    for (var i = 0; i < array.length; i++) {
        obj[array[i]] = null;
    }
    for (key in obj) {
        result.push(key);
    }
    return result;
};

function range(min, max) {
    return min + Math.random() * (max - min) << 0;
};

function shallow_copy() {

    var i, key, result = {},
        args = Array.prototype.slice.call(arguments);

    for (i = 0; i < args.length; i++) {
        for (key in args[i]) {
            result[key] = args[i][key];
        }
    }
    return result;
};

function make_dimsum(shorthand, format) {

    var shorthand = shorthand || '',
        format = format || 'text',
        type = shorthand[0] || 'p',
        len = parseInt( shorthand.slice(1, shorthand.length) ) || 1,
        i = 0,
        result = [];

    switch (type) {

        case 'p':
            result.push(dimsum(len, { format: format }));
            break;

        case 's':
            for (i; i < len; i++) {
                result.push(dimsum.sentence());
            }
            if (format == 'html') {
                result.unshift('
');
                result.push('
');
            }
            break;

        default:
            break;
    }

    return result.join(' ');
};

/* Debug */
// dimsum.normify = normify;
// dimsum.dedupe = dedupe;
// dimsum.range = range;
// dimsum.shallow_copy = shallow_copy;

}(this));<|endoftext|>


<commit_before>let e = React.createElement;

class Clocks extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clocks: [
        { name: 'Tel Aviv', offset: 0, start: Date.now() },
        { name: 'London', offset: -2, start: Date.now() },
        { name: 'New York', offset: -7, start: Date.now() }
      ]
    }
  }

  reset() {
    this.setState({
      clocks: [
        { name: 'Tel Aviv', offset: 0, start: Date.now() },
        { name: 'London', offset: -2, start: Date.now() },
        { name: 'New York', offset: -7, start: Date.now() }
      ]
    })
  }

  render() {
    return e('div', {}, [
      e('button', { onClick: () => this.reset() }, 'Reset'),
      e('ul', {}, this.state.clocks.map(clock => {
        return e('li', {}, e(Clock, clock))
      }))
    ]);
  }
}

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      time: null,
      lastStart: props.start
    };
  }
  tick() {
    this.setState({ time: new Date(this.state.time.getTime() + 1000) });
  }
  static getOffsetTime(start, offset) {
    let nextTime = new Date(start);
    nextTime.setHours(nextTime.getHours() + offset);
    return nextTime;
  }
  static getDerivedStateFromProps(props, state) {
    if (state.time === null || state.lastStart !== props.start) {
      return {
        time: Clock.getOffsetTime(props.start, props.offset),
        lastStart: props.start
      };
    }
    return state;
  }
  start() {
    this.tick();
    this.intervalId = setInterval(() => {
      this.tick();
    }, 1000);
  }
  pause() {
    clearInterval(this.intervalId);
  }
  componentDidMount() {
    this.start();
  }
  render() {
    let time = (new Date(this.state.time)).toLocaleString();
    return e('div', {}, [
      e('span', {}, `Name: ${this.props.name}`),
      e('span', {}, `Time: ${time}`),
      e('button', { onClick: () => this.pause() }, 'Pause'),
      e('button', { onClick: () => this.start() }, 'Start'),
    ]);
  }
}

ReactDOM.render(
  e(Clocks),
  document.querySelector('main')
);<commit_msg>remove null state<commit_after>let e = React.createElement;

class Clocks extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clocks: [
        { name: 'Tel Aviv', offset: 0, start: Date.now() },
        { name: 'London', offset: -2, start: Date.now() },
        { name: 'New York', offset: -7, start: Date.now() }
      ]
    }
  }

  reset() {
    this.setState({
      clocks: [
        { name: 'Tel Aviv', offset: 0, start: Date.now() },
        { name: 'London', offset: -2, start: Date.now() },
        { name: 'New York', offset: -7, start: Date.now() }
      ]
    })
  }

  render() {
    return e('div', {}, [
      e('button', { onClick: () => this.reset() }, 'Reset'),
      e('ul', {}, this.state.clocks.map(clock => {
        return e('li', {}, e(Clock, clock))
      }))
    ]);
  }
}

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      time: Clock.getOffsetTime(props.start, props.offset),
      lastStart: props.start
    };
  }
  tick() {
    this.setState({ time: new Date(this.state.time.getTime() + 1000) });
  }
  static getOffsetTime(start, offset) {
    let nextTime = new Date(start);
    nextTime.setHours(nextTime.getHours() + offset);
    return nextTime;
  }
  static getDerivedStateFromProps(props, state) {
    if (state.lastStart !== props.start) {
      return {
        time: Clock.getOffsetTime(props.start, props.offset),
        lastStart: props.start
      };
    }
    return state;
  }
  start() {
    this.tick();
    this.intervalId = setInterval(() => {
      this.tick();
    }, 1000);
  }
  pause() {
    clearInterval(this.intervalId);
  }
  componentDidMount() {
    this.start();
  }
  render() {
    let time = (new Date(this.state.time)).toLocaleString();
    return e('div', {}, [
      e('span', {}, `Name: ${this.props.name}`),
      e('span', {}, `Time: ${time}`),
      e('button', { onClick: () => this.pause() }, 'Pause'),
      e('button', { onClick: () => this.start() }, 'Start'),
    ]);
  }
}

ReactDOM.render(
  e(Clocks),
  document.querySelector('main')
);<|endoftext|>


<commit_before>var sys           = require('sys'),
    http          = require('http'),
    URL           = require('url'),
    HtmlToDom     = require('./htmltodom').HtmlToDom,
    domToHtml     = require('./domtohtml').domToHtml,
    htmlencoding  = require('./htmlencoding'),
    HTMLEncode    = htmlencoding.HTMLEncode,
    HTMLDecode    = htmlencoding.HTMLDecode,
    jsdom         = require('../../jsdom'),
    vm            = require('vm');

function NOT_IMPLEMENTED(target) {
  return function() {
    if (!jsdom.debugMode) {
      var trigger = target ? target.trigger : this.trigger;
      trigger.call(this, 'error', 'NOT IMPLEMENTED');
    }
  };
}

/**
 * Creates a window having a document. The document can be passed as option,
 * if omitted, a new document will be created.
 */
exports.windowAugmentation = function(dom, options) {
  options = options || {};
  var window = exports.createWindow(dom, options);

  if (!options.document) {
    var browser = browserAugmentation(dom, options);

    if (options.features && options.features.QuerySelector) {
      require(__dirname + "/../selectors/index").applyQuerySelectorPrototype(browser);
    }

    options.document = (browser.HTMLDocument)             ?
                        new browser.HTMLDocument(options) :
                        new browser.Document(options);

    options.document.write('');
  }

  var doc = window.document = options.document;

  if (doc.addEventListener) {
    if (doc.readyState == 'complete') {
      var ev = doc.createEvent('HTMLEvents');
      ev.initEvent('load', false, false);
      window.dispatchEvent(ev);
    }
    else {
      doc.addEventListener('load', function(ev) {
        window.dispatchEvent(ev);
      });
    }
  }

  return window;
};

/**
 * Creates a document-less window.
 */
exports.createWindow = function(dom, options) {
  var timers = [];

  function startTimer(startFn, stopFn, callback, ms) {
	  var res = startFn(callback, ms);
	  timers.push( [ res, stopFn ] );
	  return res;
  }

  function stopTimer(id) {
	  if (typeof id === 'undefined') {
		  return;
	  }
	  for (var i in timers) {
		  if (timers[i][0] === id) {
			  timers[i][1].call(this, id);
			  timers.splice(i, 1);
			  break;
		  }
	  }
  }

  function stopAllTimers() {
	  timers.forEach(function (t) {
		  t[1].call(this, t[0]);
	  });
	  timers = [];
  }

  function DOMWindow(options) {
    this.frames = [this];
    this.contentWindow = this;
    this.window = this.self = this.parent = this.top = this;

    var href = (options || {}).url || 'file://' + __filename;
    this.location = URL.parse(href);
    this.location.reload = NOT_IMPLEMENTED(this);
    this.location.replace = NOT_IMPLEMENTED(this);
    this.location.toString = function() {
      return href;
    };

    var window = this.console._window = this;

    if (options && options.document) {
      options.document.location = this.location;
    }
    this.addEventListener = function() {
      dom.Node.prototype.addEventListener.apply(window, arguments);
    };
    this.removeEventListener = function() {
      dom.Node.prototype.removeEventListener.apply(window, arguments);
    };
    this.dispatchEvent = function() {
      dom.Node.prototype.dispatchEvent.apply(window, arguments);
    };
    this.trigger = function(){
      dom.Node.prototype.trigger.apply(window.document, arguments);
    };

    this.setTimeout = function (fn, ms) { return startTimer(setTimeout, clearTimeout, fn, ms); };
    this.setInterval = function (fn, ms) { return startTimer(setInterval, clearInterval, fn, ms); };
    this.clearInterval = stopTimer;
    this.clearTimeout = stopTimer;
    this.__stopAllTimers = stopAllTimers;

  }

  DOMWindow.prototype = {
    __proto__: dom,
    close : function() {
      if (this.document) {
        if (this.document.body) {
          this.document.body.innerHTML = "";
        }

        if (this.document.close) {
          this.document.close();
        }
        delete this.document;
      }

      stopAllTimers();

      this.window = this.self = this.parent = this.top = null;
    },
    getComputedStyle: function(node) {
      var s = node.style,
          cs = {};

      for (var n in s) {
        cs[n] = s[n];
      }
      cs.__proto__ = {
        getPropertyValue: function(name) {
          return node.style[name];
        }
      };
      return cs;
    },
    console: {
      log:   function(message) { this._window.trigger('log',   message) },
      info:  function(message) { this._window.trigger('info',  message) },
      warn:  function(message) { this._window.trigger('warn',  message) },
      error: function(message) { this._window.trigger('error', message) }
    },
    navigator: {
      userAgent: 'Node.js (' + process.platform + '; U; rv:' + process.version + ')',
      appName: 'Node.js jsDom',
      platform: process.platform,
      appVersion: process.version
    },
    XMLHttpRequest: function XMLHttpRequest() {},

    name: 'nodejs',
    innerWidth: 1024,
    innerHeight: 768,
    length: 1,
    outerWidth: 1024,
    outerHeight: 768,
    pageXOffset: 0,
    pageYOffset: 0,
    screenX: 0,
    screenY: 0,
    screenLeft: 0,
    screenTop: 0,
    scrollX: 0,
    scrollY: 0,
    scrollTop: 0,
    scrollLeft: 0,
    alert: NOT_IMPLEMENTED(),
    blur: NOT_IMPLEMENTED(),
    confirm: NOT_IMPLEMENTED(),
    createPopup: NOT_IMPLEMENTED(),
    focus: NOT_IMPLEMENTED(),
    moveBy: NOT_IMPLEMENTED(),
    moveTo: NOT_IMPLEMENTED(),
    open: NOT_IMPLEMENTED(),
    print: NOT_IMPLEMENTED(),
    prompt: NOT_IMPLEMENTED(),
    resizeBy: NOT_IMPLEMENTED(),
    resizeTo: NOT_IMPLEMENTED(),
    scroll: NOT_IMPLEMENTED(),
    scrollBy: NOT_IMPLEMENTED(),
    scrollTo: NOT_IMPLEMENTED(),
    screen : {
      width : 0,
      height : 0
    },
    Image : NOT_IMPLEMENTED()
  };

  var window = new DOMWindow(options);

  // This is the last chance we have to properly update the window
  // so turn it into a context now.
  window = vm.createContext(window);
  return window;
};

//Caching for HTMLParser require. HUGE performace boost.
/**
* 5000 iterations
* Without cache: ~1800+ms
* With cache: ~80ms
*/
var defaultParser = null;
function getDefaultParser() {
  if (defaultParser === null) {
    try {
      defaultParser = require('htmlparser');
    }
    catch (e) {
      try {
        defaultParser = require('node-htmlparser/lib/node-htmlparser');
      }
      catch (e2) {
        defaultParser = undefined;
      }
    }
  }
  return defaultParser;
}

/**
 * Augments the given DOM by adding browser-specific properties and methods (BOM).
 * Returns the augmented DOM.
 */
var browserAugmentation = exports.browserAugmentation = function(dom, options) {

  if (dom._augmented) {
    return dom;
  }

  if(!options) {
    options = {};
  }

  // set up html parser - use a provided one or try and load from library
  var htmltodom = new HtmlToDom(options.parser || getDefaultParser());

  if (!dom.HTMLDocument) {
    dom.HTMLDocument = dom.Document;
  }
  if (!dom.HTMLDocument.prototype.write) {
    dom.HTMLDocument.prototype.write = function(html) {
      this.innerHTML = html;
    };
  }

  dom.Element.prototype.getElementsByClassName = function(className) {

    function filterByClassName(child) {
      if (!child) {
        return false;
      }

      if (child.nodeType &&
          child.nodeType === dom.Node.ENTITY_REFERENCE_NODE)
      {
        child = child._entity;
      }

      var classString = child.className;
      if (classString) {
        var s = classString.split(" ");
        for (var i=0; i<s.length; i++) {
          if (s[i] === className) {
            return true;
          }
        }
      }
      return false;
    }

    return new dom.NodeList(this.ownerDocument || this, dom.mapper(this, filterByClassName));
  };

  dom.Element.prototype.__defineGetter__('sourceIndex', function() {
    /*
    * According to QuirksMode:
    * Get the sourceIndex of element x. This is also the index number for
    * the element in the document.getElementsByTagName('*') array.
    * http://www.quirksmode.org/dom/w3c_core.html#t77
    */
    var items = this.ownerDocument.getElementsByTagName('*'),
        len = items.length;

    for (var i = 0; i < len; i++) {
      if (items[i] === this) {
        return i;
      }
    }
  });

  dom.Document.prototype.__defineGetter__('outerHTML', function() {
    return domToHtml(this);
  });

  dom.Element.prototype.__defineGetter__('outerHTML', function() {
    return domToHtml(this);
  });

  dom.Element.prototype.__defineGetter__('innerHTML', function() {
    return domToHtml(this._childNodes, true);
  });
  dom.Element.prototype.__defineSetter__('doctype', function() {
    throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR);
  });
  dom.Element.prototype.__defineGetter__('doctype', function() {
    var r = null;
    if (this.nodeName == '#document') {
        if (this._doctype) {
         r = this._doctype;
        }
    }
    return r;
  });

  dom.Element.prototype.__defineSetter__('innerHTML', function(html) {
    //Check for lib first

    if (html === null) {
      return null;
    }

    //Clear the children first:
    var child;
    while ((child = this._childNodes[0])) {
      this.removeChild(child);
    }

    if (this.nodeName === '#document') {
      parseDocType(this, html);
    }
    var nodes = htmltodom.appendHtmlToElement(html, this);
    return html;
  });

  dom.Document.prototype.__defineGetter__('innerHTML', function() {
    return domToHtml(this._childNodes, true);
  });

  dom.Document.prototype.__defineSetter__('innerHTML', function(html) {
    //Check for lib first

    if (html === null) {
      return null;
    }

    //Clear the children first:
    var child;
    while ((child = this._childNodes[0])) {
      this.removeChild(child);
    }

    if (this.nodeName === '#document') {
      parseDocType(this, html);
    }
    var nodes = htmltodom.appendHtmlToElement(html, this);
    return html;
  });

  var DOC_HTML5      = /<!doctype html>/i,
      DOC_TYPE       = /<!DOCTYPE (\w(.|\n)*)">/i;
      DOC_TYPE_START = '<!DOCTYPE ',
      DOC_TYPE_END   = '">';

  function parseDocType(doc, html) {
    var publicID = '',
        systemID = '',
        fullDT = '',
        name = 'HTML',
        set = true,
        doctype = html.match(DOC_HTML5);

    //Default, No doctype === null
    doc._doctype = null;

    if (doctype && doctype[0]) { //Handle the HTML shorty doctype
      fullDT = doctype[0];
    } else { //Parse the doctype
      // find the start
      var start     = html.indexOf(DOC_TYPE_START),
          end       = html.indexOf(DOC_TYPE_END),
          docString;

      if (start < 0 || end < 0) {
        return;
      }

      docString = html.substr(start, (end-start)+DOC_TYPE_END.length);
      doctype = docString.replace(/[\n\r]/g,'').match(DOC_TYPE);

      if (!doctype) {
        return;
      }

      fullDT = doctype[0];
      doctype = doctype[1].split(' "');
      var _id1 = doctype.length ? doctype.pop().replace(/"/g, '') : '',
          _id2 = doctype.length ? doctype.pop().replace(/"/g, '') : '';

      if (_id1.indexOf('-//') !== -1) {
        publicID = _id1;
      }
      if (_id2.indexOf('-//') !== -1) {
        publicID = _id2;
      }
      if (_id1.indexOf('://') !== -1) {
        systemID = _id1;
      }
      if (_id2.indexOf('://') !== -1) {
        systemID = _id2;
      }
      if (doctype.length) {
        doctype = doctype[0].split(' ');
        name = doctype[0].toUpperCase();
      }
    }
    doc._doctype = new dom.DOMImplementation().createDocumentType(name, publicID, systemID);
    doc._doctype._ownerDocument = doc;
    doc._doctype._fullDT = fullDT;
    doc._doctype.toString = function() {
      return this._fullDT;
    };
  }

  dom.Document.prototype.getElementsByClassName = function(className) {

    function filterByClassName(child) {
      if (!child) {
        return false;
      }

      if (child.nodeType &&
          child.nodeType === dom.Node.ENTITY_REFERENCE_NODE)
      {
        child = child._entity;
      }

      var classString = child.className;
      if (classString) {
        var s = classString.split(" ");
        for (var i=0; i<s.length; i++) {
          if (s[i] === className) {
            return true;
          }
        }
      }
      return false;
    }

    return new dom.NodeList(this.ownerDocument || this, dom.mapper(this, filterByClassName));
  };

  dom.Element.prototype.__defineGetter__('nodeName', function(val) {
    return this._nodeName.toUpperCase();
  });

  dom.Element.prototype.__defineGetter__('tagName', function(val) {
    var t = this._tagName.toUpperCase();
    //Document should not return a tagName
    if (this.nodeName === '#document') {
      t = null;
    }
    return t;
  });

  dom.Element.prototype.scrollTop = 0;
  dom.Element.prototype.scrollLeft = 0;

  dom.Document.prototype.__defineGetter__('parentWindow', function() {
    if (!this._parentWindow) {
      this._parentWindow = exports.windowAugmentation(dom, {document: this, url: this.URL});
    }
    return this._parentWindow;
  });

  dom.Document.prototype.__defineSetter__('parentWindow', function(window) {
    this._parentWindow = window;
  });

  dom.Document.prototype.__defineGetter__('defaultView', function() {
    return this.parentWindow;
  });

  dom._augmented = true;
  return dom;
};
<commit_msg>typo fix<commit_after>var sys           = require('sys'),
    http          = require('http'),
    URL           = require('url'),
    HtmlToDom     = require('./htmltodom').HtmlToDom,
    domToHtml     = require('./domtohtml').domToHtml,
    htmlencoding  = require('./htmlencoding'),
    HTMLEncode    = htmlencoding.HTMLEncode,
    HTMLDecode    = htmlencoding.HTMLDecode,
    jsdom         = require('../../jsdom'),
    vm            = require('vm');

function NOT_IMPLEMENTED(target) {
  return function() {
    if (!jsdom.debugMode) {
      var trigger = target ? target.trigger : this.trigger;
      trigger.call(this, 'error', 'NOT IMPLEMENTED');
    }
  };
}

/**
 * Creates a window having a document. The document can be passed as option,
 * if omitted, a new document will be created.
 */
exports.windowAugmentation = function(dom, options) {
  options = options || {};
  var window = exports.createWindow(dom, options);

  if (!options.document) {
    var browser = browserAugmentation(dom, options);

    if (options.features && options.features.QuerySelector) {
      require(__dirname + "/../selectors/index").applyQuerySelectorPrototype(browser);
    }

    options.document = (browser.HTMLDocument)             ?
                        new browser.HTMLDocument(options) :
                        new browser.Document(options);

    options.document.write('');
  }

  var doc = window.document = options.document;

  if (doc.addEventListener) {
    if (doc.readyState == 'complete') {
      var ev = doc.createEvent('HTMLEvents');
      ev.initEvent('load', false, false);
      window.dispatchEvent(ev);
    }
    else {
      doc.addEventListener('load', function(ev) {
        window.dispatchEvent(ev);
      });
    }
  }

  return window;
};

/**
 * Creates a document-less window.
 */
exports.createWindow = function(dom, options) {
  var timers = [];

  function startTimer(startFn, stopFn, callback, ms) {
	  var res = startFn(callback, ms);
	  timers.push( [ res, stopFn ] );
	  return res;
  }

  function stopTimer(id) {
	  if (typeof id === 'undefined') {
		  return;
	  }
	  for (var i in timers) {
		  if (timers[i][0] === id) {
			  timers[i][1].call(this, id);
			  timers.splice(i, 1);
			  break;
		  }
	  }
  }

  function stopAllTimers() {
	  timers.forEach(function (t) {
		  t[1].call(this, t[0]);
	  });
	  timers = [];
  }

  function DOMWindow(options) {
    this.frames = [this];
    this.contentWindow = this;
    this.window = this.self = this.parent = this.top = this;

    var href = (options || {}).url || 'file://' + __filename;
    this.location = URL.parse(href);
    this.location.reload = NOT_IMPLEMENTED(this);
    this.location.replace = NOT_IMPLEMENTED(this);
    this.location.toString = function() {
      return href;
    };

    var window = this.console._window = this;

    if (options && options.document) {
      options.document.location = this.location;
    }
    this.addEventListener = function() {
      dom.Node.prototype.addEventListener.apply(window, arguments);
    };
    this.removeEventListener = function() {
      dom.Node.prototype.removeEventListener.apply(window, arguments);
    };
    this.dispatchEvent = function() {
      dom.Node.prototype.dispatchEvent.apply(window, arguments);
    };
    this.trigger = function(){
      dom.Node.prototype.trigger.apply(window.document, arguments);
    };

    this.setTimeout = function (fn, ms) { return startTimer(setTimeout, clearTimeout, fn, ms); };
    this.setInterval = function (fn, ms) { return startTimer(setInterval, clearInterval, fn, ms); };
    this.clearInterval = stopTimer;
    this.clearTimeout = stopTimer;
    this.__stopAllTimers = stopAllTimers;

  }

  DOMWindow.prototype = {
    __proto__: dom,
    close : function() {
      if (this.document) {
        if (this.document.body) {
          this.document.body.innerHTML = "";
        }

        if (this.document.close) {
          this.document.close();
        }
        delete this.document;
      }

      stopAllTimers();

      this.window = this.self = this.parent = this.top = null;
    },
    getComputedStyle: function(node) {
      var s = node.style,
          cs = {};

      for (var n in s) {
        cs[n] = s[n];
      }
      cs.__proto__ = {
        getPropertyValue: function(name) {
          return node.style[name];
        }
      };
      return cs;
    },
    console: {
      log:   function(message) { this._window.trigger('log',   message) },
      info:  function(message) { this._window.trigger('info',  message) },
      warn:  function(message) { this._window.trigger('warn',  message) },
      error: function(message) { this._window.trigger('error', message) }
    },
    navigator: {
      userAgent: 'Node.js (' + process.platform + '; U; rv:' + process.version + ')',
      appName: 'Node.js jsDom',
      platform: process.platform,
      appVersion: process.version
    },
    XMLHttpRequest: function XMLHttpRequest() {},

    name: 'nodejs',
    innerWidth: 1024,
    innerHeight: 768,
    length: 1,
    outerWidth: 1024,
    outerHeight: 768,
    pageXOffset: 0,
    pageYOffset: 0,
    screenX: 0,
    screenY: 0,
    screenLeft: 0,
    screenTop: 0,
    scrollX: 0,
    scrollY: 0,
    scrollTop: 0,
    scrollLeft: 0,
    alert: NOT_IMPLEMENTED(),
    blur: NOT_IMPLEMENTED(),
    confirm: NOT_IMPLEMENTED(),
    createPopup: NOT_IMPLEMENTED(),
    focus: NOT_IMPLEMENTED(),
    moveBy: NOT_IMPLEMENTED(),
    moveTo: NOT_IMPLEMENTED(),
    open: NOT_IMPLEMENTED(),
    print: NOT_IMPLEMENTED(),
    prompt: NOT_IMPLEMENTED(),
    resizeBy: NOT_IMPLEMENTED(),
    resizeTo: NOT_IMPLEMENTED(),
    scroll: NOT_IMPLEMENTED(),
    scrollBy: NOT_IMPLEMENTED(),
    scrollTo: NOT_IMPLEMENTED(),
    screen : {
      width : 0,
      height : 0
    },
    Image : NOT_IMPLEMENTED()
  };

  var window = new DOMWindow(options);

  // This is the last chance we have to properly update the window
  // so turn it into a context now.
  window = vm.createContext(window);
  return window;
};

//Caching for HTMLParser require. HUGE performace boost.
/**
* 5000 iterations
* Without cache: ~1800+ms
* With cache: ~80ms
*/
var defaultParser = null;
function getDefaultParser() {
  if (defaultParser === null) {
    try {
      defaultParser = require('htmlparser');
    }
    catch (e) {
      try {
        defaultParser = require('node-htmlparser/lib/node-htmlparser');
      }
      catch (e2) {
        defaultParser = undefined;
      }
    }
  }
  return defaultParser;
}

/**
 * Augments the given DOM by adding browser-specific properties and methods (BOM).
 * Returns the augmented DOM.
 */
var browserAugmentation = exports.browserAugmentation = function(dom, options) {

  if (dom._augmented) {
    return dom;
  }

  if(!options) {
    options = {};
  }

  // set up html parser - use a provided one or try and load from library
  var htmltodom = new HtmlToDom(options.parser || getDefaultParser());

  if (!dom.HTMLDocument) {
    dom.HTMLDocument = dom.Document;
  }
  if (!dom.HTMLDocument.prototype.write) {
    dom.HTMLDocument.prototype.write = function(html) {
      this.innerHTML = html;
    };
  }

  dom.Element.prototype.getElementsByClassName = function(className) {

    function filterByClassName(child) {
      if (!child) {
        return false;
      }

      if (child.nodeType &&
          child.nodeType === dom.Node.ENTITY_REFERENCE_NODE)
      {
        child = child._entity;
      }

      var classString = child.className;
      if (classString) {
        var s = classString.split(" ");
        for (var i=0; i<s.length; i++) {
          if (s[i] === className) {
            return true;
          }
        }
      }
      return false;
    }

    return new dom.NodeList(this.ownerDocument || this, dom.mapper(this, filterByClassName));
  };

  dom.Element.prototype.__defineGetter__('sourceIndex', function() {
    /*
    * According to QuirksMode:
    * Get the sourceIndex of element x. This is also the index number for
    * the element in the document.getElementsByTagName('*') array.
    * http://www.quirksmode.org/dom/w3c_core.html#t77
    */
    var items = this.ownerDocument.getElementsByTagName('*'),
        len = items.length;

    for (var i = 0; i < len; i++) {
      if (items[i] === this) {
        return i;
      }
    }
  });

  dom.Document.prototype.__defineGetter__('outerHTML', function() {
    return domToHtml(this);
  });

  dom.Element.prototype.__defineGetter__('outerHTML', function() {
    return domToHtml(this);
  });

  dom.Element.prototype.__defineGetter__('innerHTML', function() {
    return domToHtml(this._childNodes, true);
  });
  dom.Element.prototype.__defineSetter__('doctype', function() {
    throw new core.DOMException(NO_MODIFICATION_ALLOWED_ERR);
  });
  dom.Element.prototype.__defineGetter__('doctype', function() {
    var r = null;
    if (this.nodeName == '#document') {
        if (this._doctype) {
         r = this._doctype;
        }
    }
    return r;
  });

  dom.Element.prototype.__defineSetter__('innerHTML', function(html) {
    //Check for lib first

    if (html === null) {
      return null;
    }

    //Clear the children first:
    var child;
    while ((child = this._childNodes[0])) {
      this.removeChild(child);
    }

    if (this.nodeName === '#document') {
      parseDocType(this, html);
    }
    var nodes = htmltodom.appendHtmlToElement(html, this);
    return html;
  });

  dom.Document.prototype.__defineGetter__('innerHTML', function() {
    return domToHtml(this._childNodes, true);
  });

  dom.Document.prototype.__defineSetter__('innerHTML', function(html) {
    //Check for lib first

    if (html === null) {
      return null;
    }

    //Clear the children first:
    var child;
    while ((child = this._childNodes[0])) {
      this.removeChild(child);
    }

    if (this.nodeName === '#document') {
      parseDocType(this, html);
    }
    var nodes = htmltodom.appendHtmlToElement(html, this);
    return html;
  });

  var DOC_HTML5      = /<!doctype html>/i,
      DOC_TYPE       = /<!DOCTYPE (\w(.|\n)*)">/i,
      DOC_TYPE_START = '<!DOCTYPE ',
      DOC_TYPE_END   = '">';

  function parseDocType(doc, html) {
    var publicID = '',
        systemID = '',
        fullDT = '',
        name = 'HTML',
        set = true,
        doctype = html.match(DOC_HTML5);

    //Default, No doctype === null
    doc._doctype = null;

    if (doctype && doctype[0]) { //Handle the HTML shorty doctype
      fullDT = doctype[0];
    } else { //Parse the doctype
      // find the start
      var start     = html.indexOf(DOC_TYPE_START),
          end       = html.indexOf(DOC_TYPE_END),
          docString;

      if (start < 0 || end < 0) {
        return;
      }

      docString = html.substr(start, (end-start)+DOC_TYPE_END.length);
      doctype = docString.replace(/[\n\r]/g,'').match(DOC_TYPE);

      if (!doctype) {
        return;
      }

      fullDT = doctype[0];
      doctype = doctype[1].split(' "');
      var _id1 = doctype.length ? doctype.pop().replace(/"/g, '') : '',
          _id2 = doctype.length ? doctype.pop().replace(/"/g, '') : '';

      if (_id1.indexOf('-//') !== -1) {
        publicID = _id1;
      }
      if (_id2.indexOf('-//') !== -1) {
        publicID = _id2;
      }
      if (_id1.indexOf('://') !== -1) {
        systemID = _id1;
      }
      if (_id2.indexOf('://') !== -1) {
        systemID = _id2;
      }
      if (doctype.length) {
        doctype = doctype[0].split(' ');
        name = doctype[0].toUpperCase();
      }
    }
    doc._doctype = new dom.DOMImplementation().createDocumentType(name, publicID, systemID);
    doc._doctype._ownerDocument = doc;
    doc._doctype._fullDT = fullDT;
    doc._doctype.toString = function() {
      return this._fullDT;
    };
  }

  dom.Document.prototype.getElementsByClassName = function(className) {

    function filterByClassName(child) {
      if (!child) {
        return false;
      }

      if (child.nodeType &&
          child.nodeType === dom.Node.ENTITY_REFERENCE_NODE)
      {
        child = child._entity;
      }

      var classString = child.className;
      if (classString) {
        var s = classString.split(" ");
        for (var i=0; i<s.length; i++) {
          if (s[i] === className) {
            return true;
          }
        }
      }
      return false;
    }

    return new dom.NodeList(this.ownerDocument || this, dom.mapper(this, filterByClassName));
  };

  dom.Element.prototype.__defineGetter__('nodeName', function(val) {
    return this._nodeName.toUpperCase();
  });

  dom.Element.prototype.__defineGetter__('tagName', function(val) {
    var t = this._tagName.toUpperCase();
    //Document should not return a tagName
    if (this.nodeName === '#document') {
      t = null;
    }
    return t;
  });

  dom.Element.prototype.scrollTop = 0;
  dom.Element.prototype.scrollLeft = 0;

  dom.Document.prototype.__defineGetter__('parentWindow', function() {
    if (!this._parentWindow) {
      this._parentWindow = exports.windowAugmentation(dom, {document: this, url: this.URL});
    }
    return this._parentWindow;
  });

  dom.Document.prototype.__defineSetter__('parentWindow', function(window) {
    this._parentWindow = window;
  });

  dom.Document.prototype.__defineGetter__('defaultView', function() {
    return this.parentWindow;
  });

  dom._augmented = true;
  return dom;
};
<|endoftext|>


<commit_before>var API = require('../lib/api-helpers')
var Pastie = require('../models/pastie')

var PastiesAPI = module.exports = require('express').Router()

PastiesAPI.get('/pasties/:id', function (req, res) {

  Pastie.find( req.params.id )
    .then( API.prep(200, res) )
    .catch( Pastie.NotFound, API.prep(404, res) )
    .catch( API.catchUnexpectedErrors )
})
<commit_msg>Mockup Pastie Endpoints (#25)<commit_after>var API = require('../lib/api-helpers')
var Pastie = require('../models/pastie')

var PastiesAPI = module.exports = require('express').Router()

PastiesAPI.get('/pasties/:id', function (req, res) {

  Pastie.find( req.params.id )
    .then( API.prep(200, res) )
    .catch( Pastie.NotFound, API.prep(404, res) )
    .catch( API.catchUnexpectedErrors )
})

PastiesAPI.get('/pasties', function(req, res) {

  Pastie.feedForUser( req.user.uid, req.query )
    .then( API.prep(200, res) )
    .catch( Pastie.NotFound, API.prep(404, res) )
    .catch( API.catchUnexpectedErrors )
})

PastiesAPI.get('/pasties/public', function(req, res) {

  Pastie.getPublic( req.query )
    .then( API.prep(200, res) )
    .catch( Pastie.NotFound, API.prep(404, res) )
    .catch( API.catchUnexpectedErrors )
})

PastiesAPI.post('/pasties', function(req, res) {

  Pastie.create( req.body )
    .then( API.prep(201, res) )
    .catch( Pastie.InvalidFormat, API.prep(400, res) )
    .catch( API.catchUnexpectedErrors)
})

// PastiesAPI.post('/groups/:id/pasties') {

// 	Pastie.create(req.body)
// 		.then(API.prep(200, res))
// 		.catch( API.catchUnexpectedErrors)
// }<|endoftext|>


<commit_before>
Meteor.startup(function(){
  Meteor.setTimeout(function(){
      if (Session.get('lightBoxPageViewSetting') === undefined ) {
        Session.set('lightBoxPageViewSetting', checkShowSettings());
      }
  }, 60*1000 );
});

Telescope.modules.add("top", {
template: "newsletter_alt",
order: 0
});

var addMask = function() {
 $('body').addClass('pg-mask');
}

var removeMask = function() {
  $('body').removeClass('pg-mask');
}

var checkShowSettings = function () {
  if (
    !Users.can.view(Meteor.user())
    ||  Session.get('lightBoxPageViewSetting') === false
    ||  Cookie.get('showCustomBanner') === "no"
    ||  (Meteor.user() && Meteor.user().getSetting('profile.dontShowCustomEmailBanner', true) === true)
    ) {
      removeMask();
      return false
    } else {
      addMask();
      return true
    }
  }

Template.layout.events({
  'click a': function (e) {
    Session.get('lightBoxPageViewCount') === undefined ? Session.set('lightBoxPageViewCount', 1 ) : Session.set('lightBoxPageViewCount', (Session.get('lightBoxPageViewCount') + 1 )) ;
    if (Session.get('lightBoxPageViewCount') === 4 ) { Session.set('lightBoxPageViewSetting', checkShowSettings() ) }
  }
});

var updateDontShowCustomEmailBannerField = function() {
   Meteor.call('dontShowCustomEmailBanner', function (error, result) {
      if(error) {
        console.log(error.reason);
      } else {
        console.log(result)
      }
    });
}

var dismissBanner = function () {
  var checked = $('#dont-ask-me-again-check').is(':checked');
  removeMask();
  Session.set('lightBoxPageViewSetting', false);
  if (Meteor.user() && checked ) {
    updateDontShowCustomEmailBannerField();
    Cookie.set('showCustomBanner', "no");
  }
};

Template.newsletter_alt.helpers({
  isNotConnected: function () {
    return !Meteor.user();
  },
  showBanner: function () {
    return Session.get('lightBoxPageViewSetting');
  }
});

Template.newsletter_alt.events({
  'click .newsletter-button': function (e) {
    e.preventDefault();
    var $banner = $('.newsletter-banner');
    var email = $('.newsletter-email').val();
    if(!email){
      alert('Please fill in your email.');
      return;
    }
    $banner.addClass('show-loader');
    Meteor.call('addEmailToMailChimpList', email, function (error, result) {
      $banner.removeClass('show-loader');
      if(error){
        console.log(error);
        Messages.flash(error.reason, "error");
      }else{
        Messages.clearSeen();
        console.log(result);
        dismissBanner();
      }
    });
    if (Meteor.user()) {
      updateDontShowCustomEmailBannerField();
    }
  },
  'click .newsletter-dismiss': function (e) {
    e.preventDefault();
    Session.set('lightBoxPageViewSetting', false);
    dismissBanner();
  }
});

<commit_msg>removed console.logs<commit_after>
Meteor.startup(function(){
  Meteor.setTimeout(function(){
      if (Session.get('lightBoxPageViewSetting') === undefined ) {
        Session.set('lightBoxPageViewSetting', checkShowSettings());
      }
  }, 60*1000 );
});

Telescope.modules.add("top", {
template: "newsletter_alt",
order: 0
});

var addMask = function() {
 $('body').addClass('pg-mask');
}

var removeMask = function() {
  $('body').removeClass('pg-mask');
}

var checkShowSettings = function () {
  if (
    !Users.can.view(Meteor.user())
    ||  Session.get('lightBoxPageViewSetting') === false
    ||  Cookie.get('showCustomBanner') === "no"
    ||  (Meteor.user() && Meteor.user().getSetting('profile.dontShowCustomEmailBanner', true) === true)
    ) {
      removeMask();
      return false
    } else {
      addMask();
      return true
    }
  }

Template.layout.events({
  'click a': function (e) {
    Session.get('lightBoxPageViewCount') === undefined ? Session.set('lightBoxPageViewCount', 1 ) : Session.set('lightBoxPageViewCount', (Session.get('lightBoxPageViewCount') + 1 )) ;
    if (Session.get('lightBoxPageViewCount') === 4 ) { Session.set('lightBoxPageViewSetting', checkShowSettings() ) }
  }
});

var updateDontShowCustomEmailBannerField = function() {
   Meteor.call('dontShowCustomEmailBanner', function (error, result) {
      if(error) {
        console.log(error.reason);
      }
    });
}

var dismissBanner = function () {
  var checked = $('#dont-ask-me-again-check').is(':checked');
  removeMask();
  Session.set('lightBoxPageViewSetting', false);
  if (Meteor.user() && checked ) {
    updateDontShowCustomEmailBannerField();
    Cookie.set('showCustomBanner', "no");
  }
};

Template.newsletter_alt.helpers({
  isNotConnected: function () {
    return !Meteor.user();
  },
  showBanner: function () {
    return Session.get('lightBoxPageViewSetting');
  }
});

Template.newsletter_alt.events({
  'click .newsletter-button': function (e) {
    e.preventDefault();
    var $banner = $('.newsletter-banner');
    var email = $('.newsletter-email').val();
    if(!email){
      alert('Please fill in your email.');
      return;
    }
    $banner.addClass('show-loader');
    Meteor.call('addEmailToMailChimpList', email, function (error, result) {
      $banner.removeClass('show-loader');
      if(error){
        console.log(error);
        Messages.flash(error.reason, "error");
      }else{
        Messages.clearSeen();
        dismissBanner();
      }
    });
    if (Meteor.user()) {
      updateDontShowCustomEmailBannerField();
    }
  },
  'click .newsletter-dismiss': function (e) {
    e.preventDefault();
    Session.set('lightBoxPageViewSetting', false);
    dismissBanner();
  }
});

<|endoftext|>


<commit_before>/*
Rabbitmq wrapper for promise based connection
 */
const amqp = require('amqplib/callback_api');
let exchange = '';
let exchangeFanout = '';
let channel;
let connection;

/*const connect = (config) => {
    return new Promise(function (resolve, reject) {
        try {
            exchange = config.exchange;
            exchangeFanout = config.exchange + ".fanout";
            amqp.connect(config.url, function (err, conn) {
                connection = conn;
                if (err) {
                    console.error("[AMQP]", err);
                    reject(err);
                }
                console.log("[AMQP] connected");
                conn.createConfirmChannel(function (err, ch) {
                    console.log("Connected to rabbit");
                    channel = ch;
                    channel.assertExchange(exchange, 'direct', {durable: true});
                    channel.assertExchange(exchangeFanout, 'fanout', {durable: true});
                    resolve(conn);
                });
            });
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] connect", e.message);
        }
    });
};*/
function connect(config,cb)
{

    exchange = config.exchange;
    exchangeFanout = config.exchange+".fanout";
    amqp.connect(config.url, function (err, conn) {
        connection = conn;
        if (err) {
            console.error("[AMQP]", err);
            return setTimeout(connect.bind(this,config,cb), 1000);
        }
        conn.on("error", function(err) {
            if (err.message !== "Connection closing") {
                console.error("[AMQP] conn error", err);
                return setTimeout(connect.bind(this,config,cb), 1000);
            }
        });
        conn.on("close", function(err) {
            if (err.message !== "Connection closing") {
                console.error("[AMQP] conn error", err);
                return setTimeout(connect.bind(this,config,cb), 1000);
            }
        });

        console.log("[AMQP] connected");
        conn.createConfirmChannel(function (err, ch) {
            console.log("Connected to rabbit");
            channel = ch;
            channel.assertExchange(exchange, 'direct', {durable: true});
            channel.assertExchange(exchangeFanout, 'fanout', {durable: true});
            if(cb)
                cb(ch);

        });

    });
}

const publish = (msg,key) => {
    return new Promise(function(resolve, reject) {
        try {

            channel.publish(exchange, key, new Buffer(msg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    });
};
const fanout = (sendMsg,key) => {
    return new Promise(function(resolve, reject) {
        try {
            if (typeof sendMsg !== 'string') {
                sendMsg = JSON.stringify(sendMsg);
            }
            channel.publish(exchangeFanout, key, new Buffer(sendMsg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    });
};

const RPC = (queue,service,sendMsg) =>{
    return new Promise(function(resolve, reject) {
        try {
            connection.createChannel((err, ch) => {
                ch.assertQueue('', {exclusive: true,autoDelete:true}, (err, q) => {
                    const corr = generateUuid();
                    ch.consume(q.queue, (msg) => {
                        if (msg.properties.correlationId === corr) {
                            resolve(msg.content.toString());
                            ch.close();
                        }
                    }, {noAck: true});

                    if (typeof sendMsg !== 'string') {
                        sendMsg = JSON.stringify(sendMsg);
                    }
                    ch.sendToQueue("RPC." + queue,
                        new Buffer(sendMsg),
                        {correlationId: corr, replyTo: q.queue, type: service}
                    );
                });
            })
        } catch(e) {
            console.error(e);
            reject(e.message);
        }
    });
};
const generateUuid = () => {
    return Math.random().toString() +
        Math.random().toString() +
        Math.random().toString();
};

function RPCListen(queue,cb, ...args) {
    const q = "RPC." + queue;
    channel.assertQueue(q, {durable: false});
    channel.prefetch(1);
    console.log(' [x] Awaiting RPC requests on queue:' + q);
    channel.consume(q, (msg) => {
        (function(msg){
            new Promise((resolve, reject) => {
                let services = cb();
                if (services[msg.properties.type] === undefined) {
                    channel.sendToQueue(msg.properties.replyTo,
                        new Buffer("Unknown service"),
                        {correlationId: msg.properties.correlationId});
                    channel.ack(msg);
                }
                else {
                    services[msg.properties.type](msg.content.toString(), resolve, args);
                }
            }).then((sendMsg) => {
                if (typeof sendMsg !== 'string') {
                    sendMsg = JSON.stringify(sendMsg);
                }

                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer(sendMsg),
                    {correlationId: msg.properties.correlationId});
                channel.ack(msg);
            }).catch((msg) => {
                console.error(msg);
            });
        }(msg))
    });
}
function listen(queue,key,cb){
    channel.assertQueue(queue, {durable:true},function(err, q) {
        console.log(' [*] Waiting for data on'+q.queue);
        channel.bindQueue(q.queue, exchange, key);
        //  channel.bindQueue(q.queue, exchangeFanout, key);
        //Fetch 5 messages in a time and wait for ack on those
        channel.prefetch(5);
        channel.consume(q.queue, function(msg) {
            cb(function(channel,msg) {channel.ack(msg);}.bind(this,channel,msg),msg.content.toString());
        }, {noAck: false});
    });
}
function listenFanout(queue,key,cb){
    channel.assertQueue(queue, {durable:true},function(err, q) {
        console.log(' [*] Waiting for data on'+q.queue);

        channel.bindQueue(q.queue, exchangeFanout, key);
        //Fetch 5 messages in a time and wait for ack on those
        channel.prefetch(5);
        channel.consume(q.queue, function(msg) {
            cb(() => {channel.ack(msg)},msg.content.toString());
        }, {noAck: false});
    });
}

const use = (queue,services, ...params) => {
    const q = "RPC." + queue;
    channel.assertQueue(q, {durable: false});
    channel.prefetch(1);
    console.log(' [x] Awaiting RPC requests on queue:' + q);
    channel.consume(q, (msg) => {
        (function(msg){
            if (services[msg.properties.type] === undefined) {
                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer("Unknown service"),
                    {correlationId: msg.properties.correlationId});
            }
            else {

                Promise.resolve(services[msg.properties.type].resolve(msg.content.toString(),...params))
                    .then((sendMsg) => {
                        if (typeof sendMsg !== 'string') {
                            sendMsg = JSON.stringify(sendMsg);
                        }
                        channel.sendToQueue(msg.properties.replyTo,
                            new Buffer(sendMsg),
                            {correlationId: msg.properties.correlationId});
                    })
                    .catch((err) => console.error(err));
            }
        }(msg))
        channel.ack(msg);
    });
};

/*test:

 var result = await rpc(microservice, service, |schema, externalSystemAPI, args);*/

module.exports = {
    connect:connect,
    publish:publish,
    listen:listen,
    RPCListen:RPCListen,
    RPC:RPC,
    fanout:fanout,
    listenFanout,listenFanout,
    disconnect: (cb) => {
        if(connection) {
            connection.close(() => {
                cb();
            })
        } else {cb();}},
    use:use
};<commit_msg>Promisified connect<commit_after>/*
Rabbitmq wrapper for promise based connection
Test
 */
const amqp = require('amqplib/callback_api');
let exchange = '';
let exchangeFanout = '';
let channel;
let connection;

/*const connect = (config) => {
    return new Promise(function (resolve, reject) {
        try {
            exchange = config.exchange;
            exchangeFanout = config.exchange + ".fanout";
            amqp.connect(config.url, function (err, conn) {
                connection = conn;
                if (err) {
                    console.error("[AMQP]", err);
                    reject(err);
                }
                console.log("[AMQP] connected");
                conn.createConfirmChannel(function (err, ch) {
                    console.log("Connected to rabbit");
                    channel = ch;
                    channel.assertExchange(exchange, 'direct', {durable: true});
                    channel.assertExchange(exchangeFanout, 'fanout', {durable: true});
                    resolve(conn);
                });
            });
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] connect", e.message);
        }
    });
};*/
function connect(config,cb)
{

    exchange = config.exchange;
    exchangeFanout = config.exchange+".fanout";
    amqp.connect(config.url, function (err, conn) {
        connection = conn;
        if (err) {
            console.error("[AMQP]", err);
            return setTimeout(connect.bind(this,config,cb), 1000);
        }
        conn.on("error", function(err) {
            if (err.message !== "Connection closing") {
                console.error("[AMQP] conn error", err);
                return setTimeout(connect.bind(this,config,cb), 1000);
            }
        });
        conn.on("close", function(err) {
            if (err.message !== "Connection closing") {
                console.error("[AMQP] conn error", err);
                return setTimeout(connect.bind(this,config,cb), 1000);
            }
        });

        console.log("[AMQP] connected");
        conn.createConfirmChannel(function (err, ch) {
            console.log("Connected to rabbit");
            channel = ch;
            channel.assertExchange(exchange, 'direct', {durable: true});
            channel.assertExchange(exchangeFanout, 'fanout', {durable: true});
            if(cb)
                cb(ch);

        });

    });
}

const publish = (msg,key) => {
    return new Promise(function(resolve, reject) {
        try {

            channel.publish(exchange, key, new Buffer(msg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    });
};
const fanout = (sendMsg,key) => {
    return new Promise(function(resolve, reject) {
        try {
            if (typeof sendMsg !== 'string') {
                sendMsg = JSON.stringify(sendMsg);
            }
            channel.publish(exchangeFanout, key, new Buffer(sendMsg), {persistent: true}, function (err, ok) {
                    if (err !== null) {
                        reject(err);
                        console.warn(' [*] Message nacked');
                    } else {
                        console.log(' [*] Message acked');
                        resolve("Message sendt");
                    }
                }
            );
        } catch (e) {
            reject(e.message);
            console.error("[AMQP] publish", e.message);
        }
    });
};

const RPC = (queue,service,sendMsg) =>{
    return new Promise(function(resolve, reject) {
        try {
            connection.createChannel((err, ch) => {
                ch.assertQueue('', {exclusive: true,autoDelete:true}, (err, q) => {
                    const corr = generateUuid();
                    ch.consume(q.queue, (msg) => {
                        if (msg.properties.correlationId === corr) {
                            resolve(msg.content.toString());
                            ch.close();
                        }
                    }, {noAck: true});

                    if (typeof sendMsg !== 'string') {
                        sendMsg = JSON.stringify(sendMsg);
                    }
                    ch.sendToQueue("RPC." + queue,
                        new Buffer(sendMsg),
                        {correlationId: corr, replyTo: q.queue, type: service}
                    );
                });
            })
        } catch(e) {
            console.error(e);
            reject(e.message);
        }
    });
};
const generateUuid = () => {
    return Math.random().toString() +
        Math.random().toString() +
        Math.random().toString();
};

function RPCListen(queue,cb, ...args) {
    const q = "RPC." + queue;
    channel.assertQueue(q, {durable: false});
    channel.prefetch(1);
    console.log(' [x] Awaiting RPC requests on queue:' + q);
    channel.consume(q, (msg) => {
        (function(msg){
            new Promise((resolve, reject) => {
                let services = cb();
                if (services[msg.properties.type] === undefined) {
                    channel.sendToQueue(msg.properties.replyTo,
                        new Buffer("Unknown service"),
                        {correlationId: msg.properties.correlationId});
                    channel.ack(msg);
                }
                else {
                    services[msg.properties.type](msg.content.toString(), resolve, args);
                }
            }).then((sendMsg) => {
                if (typeof sendMsg !== 'string') {
                    sendMsg = JSON.stringify(sendMsg);
                }

                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer(sendMsg),
                    {correlationId: msg.properties.correlationId});
                channel.ack(msg);
            }).catch((msg) => {
                console.error(msg);
            });
        }(msg))
    });
}
function listen(queue,key,cb){
    channel.assertQueue(queue, {durable:true},function(err, q) {
        console.log(' [*] Waiting for data on'+q.queue);
        channel.bindQueue(q.queue, exchange, key);
        //  channel.bindQueue(q.queue, exchangeFanout, key);
        //Fetch 5 messages in a time and wait for ack on those
        channel.prefetch(5);
        channel.consume(q.queue, function(msg) {
            cb(function(channel,msg) {channel.ack(msg);}.bind(this,channel,msg),msg.content.toString());
        }, {noAck: false});
    });
}
function listenFanout(queue,key,cb){
    channel.assertQueue(queue, {durable:true},function(err, q) {
        console.log(' [*] Waiting for data on'+q.queue);

        channel.bindQueue(q.queue, exchangeFanout, key);
        //Fetch 5 messages in a time and wait for ack on those
        channel.prefetch(5);
        channel.consume(q.queue, function(msg) {
            cb(() => {channel.ack(msg)},msg.content.toString());
        }, {noAck: false});
    });
}

const use = (queue,services, ...params) => {
    const q = "RPC." + queue;
    channel.assertQueue(q, {durable: false});
    channel.prefetch(1);
    console.log(' [x] Awaiting RPC requests on queue:' + q);
    channel.consume(q, (msg) => {
        (function(msg){
            if (services[msg.properties.type] === undefined) {
                channel.sendToQueue(msg.properties.replyTo,
                    new Buffer("Unknown service"),
                    {correlationId: msg.properties.correlationId});
            }
            else {

                Promise.resolve(services[msg.properties.type].resolve(msg.content.toString(),...params))
                    .then((sendMsg) => {
                        if (typeof sendMsg !== 'string') {
                            sendMsg = JSON.stringify(sendMsg);
                        }
                        channel.sendToQueue(msg.properties.replyTo,
                            new Buffer(sendMsg),
                            {correlationId: msg.properties.correlationId});
                    })
                    .catch((err) => console.error(err));
            }
        }(msg))
        channel.ack(msg);
    });
};

/*test:

 var result = await rpc(microservice, service, |schema, externalSystemAPI, args);*/

module.exports = {
    connect:connect,
    publish:publish,
    listen:listen,
    RPCListen:RPCListen,
    RPC:RPC,
    fanout:fanout,
    listenFanout,listenFanout,
    disconnect: (cb) => {
        if(connection) {
            connection.close(() => {
                cb();
            })
        } else {cb();}},
    use:use
};<|endoftext|>


<commit_before>'use strict';
var mongoose = require('mongoose'),
    _ = require('lodash')
module.exports = {
    //get
    query: query,
    config: config
};
var options = {
    sort: "-created",
    limit: 20,
    select: "",
    populateId: "",
    populateItems: ""
};

function config(configs) {
    if (configs) {
        options = _.extend(options, configs);
    }
}

function query(req, res, next) {
    var defaults = {};
    defaults = _.extend(defaults, options);
    var models = _.keys(mongoose.models);
    var schemas = {};
    var query = req.query;
    var queryParameters = {};
    var schema = []
    var schemaSort = [];
    queryParameters.error = {};
    queryParameters.filter = {};
    _.forEach(models, function(n, key) {
            schemas[n] = {};
            schemas[n].schema = []
            schemas[n].schemaSort = [];
            schemas[n].tree = mongoose.models[n].schema.tree;
            _.forEach(schemas[n].tree, function(j, key) {
                schema.push(key)
                schemaSort.push(key)
                schemaSort.push('-' + key)
                schemas[n].schema.push(key)
                schemas[n].schemaSort.push(key)
                schemas[n].schemaSort.push('-' + key)
                _.forEach(query, function(a, keys) {
                    if (keys == key) {
                        queryParameters.filter[keys] = a;
                    }
                })
            })
        })
        //SORT
    queryParameters.sort = query.sort ? sortCheck(query.sort) : defaults.sort;

    function sortCheck(sort) {
        return -1 !== schemaSort.indexOf(sort) ? sort : errorHandler(query.sort, "sort", defaults.sort);
    }
    //limitCheck
    queryParameters.limit = query.limit ? limitCheck(query.limit) : defaults.limit;

    function limitCheck(number) {
        //plan to switch out for https://jsperf.com/number-vs-parseint-vs-plus/95 in later version
        return number < defaults.limit ? parseInt(number) : errorHandler(query.limit, "limit", defaults.limit);
    }
    //selectCheck
    queryParameters.select = query.select ? selectCheck(query.select) : defaults.select;

    function selectCheck(select) {
        if (_.isArray(query.select)) {
            var selected = '';
            _.forEach(query.select, function(n, key) {
                if (schema.indexOf(n) !== -1) {
                    selected += n + ' ';
                } else {
                    errorHandler(n, "select", defaults.select);
                };
            });
            return selected;
        } else {
            return -1 !== schema.indexOf(select) ? select : errorHandler(query.select, "select", defaults.select);
        }
    }
    //SKIP
    queryParameters.skip = query.skip || 0;
    //populate
    queryParameters.populate = {};
    queryParameters.populate.id = query.populateId ? populateIdCheck(query.populateId) : populateIdCheck(models);
    queryParameters.populate.items = query.populateItems ? populateItemsCheck(query.populateItems) : populateItemsCheck(schema);

    function populateIdCheck(data) {
        var populateId = '';
        if (!_.isArray(data)) {
            data = data.split(" ");
        }
        _.forEach(data, function(n, key) {
            if (models.indexOf(n) !== -1) {
                populateId += n + ' ';
            } else {
                errorHandler(n, "populateId", defaults.populateId);
            };
        })

        return populateId;
    }

    function populateItemsCheck(data) {
        var populateItems = '';
        if (!_.isArray(data)) {
            data = data.split(" ");
        }
        _.forEach(data, function(n, key) {
            if (schema.indexOf(n) !== -1) {
                populateItems += n + ' ';
            } else {
                errorHandler(n, "populateItems", defaults.populateItems);
            };
        })

        return populateItems;
    }
    //ERRORHANDLER
    function errorHandler(errvalue, field, value) {
        if (!queryParameters.error[field]) queryParameters.error[field] = [];
        queryParameters.error[field].push({
            message: 'Unknown Value',
            value: errvalue
        })
        return value;
    }
    req.queryParameters = queryParameters;
    next();
};<commit_msg>added Response and simple error<commit_after>(function() {
'use strict';
var mongoose = require('mongoose'),
    _ = require('lodash')
module.exports = {
    //get
    query: query,
    response: response,
    error: error,
    config: config
};
var options = {
    response: {
        method: "get",
        data: {},
        user: {},
        count: 0,
        hostname: "",
        query: {},
        type: ""
    },
    query: {
        sort: "-created",
        filter: {},
        limit: 20,
        select: "",
        populateId: "",
        populateItems: "",
        lean: false,
        skip: 0,
        where: "",
        gt: 1,
        lt: 0,
        in : [],
        errorMessage: "Unknown Value"
    }
};

function error(err, req, res, next) {
    //Currently just a Sample - Still need to implement
    if (res.headersSent) {
        return next(err);
    }
    res.status(500);
    res.render('error', {
        error: err
    })
}

function config(configs) {
    if (configs) {
        options = _.extend(options, configs);
    }
}

function response(res, value) {
    var defaults = {};
    defaults = _.extend(options.response, defaults);

    var response = {};
    response.actions = {};
    var url = '';
    var hostname = value.hostname || defaults.hostname;

    function urlBuilder(data) {
        data = data.trim().replace(/\s/g, "%20");
        if (url === '') {
            url = '?' + data
        } else {
            url += '&' + data;
        }
        return url
    }

    function queryBuilder() {
        _.forEach(options.query, function (n, key) {
            if (_.isArray(n)) {
                _.forEach(value.query[key], function (k, keyArr) {
                    urlBuilder(keyArr + '=' + k)
                })
            } else if (_.isObject(n)) {
                _.forEach(value.query[key], function (j, keyObj) {
                    urlBuilder(keyObj + '=' + j)
                })
            } else if (value.query[key] && value.query[key] !== n) urlBuilder(key + '=' + value.query[key]);
        })
    }

    function reload() {
        url = '';
        queryBuilder()
        response.actions.reload = {
            allowed: _.keys(value.route.methods),
            ref: value.hostname + url
        }
    }

    function next(number) {
        url = '';
        queryBuilder()
        var dataSkip = parseInt(value.query.limit) + parseInt(value.query.skip);
        if (dataSkip < count) {
            urlBuilder('skip=' + dataSkip);
            response.actions.next = {
                allowed: _.keys(value.route.methods),
                ref: value.hostname + url
            }
        }
    }

    function prev(number) {
        url = '';
        queryBuilder()
            //need to fix this to handle more numbers
        var dataSkip = parseInt(value.query.skip) - parseInt(value.query.limit);
        if (dataSkip > 0) {
            urlBuilder('skip=' + dataSkip)
            response.actions.prev = {
                allowed: _.keys(value.route.methods),
                ref: value.hostname + url
            }
        } else {
            response.actions.prev = {
                allowed: _.keys(value.route.methods),
                ref: value.hostname + url
            }
        }
    }
    response.query = value.query || defaults.query;
    if (value.data && _.isArray(value.data)) {
        response.count = value.data.length || defaults.count;
        response.itemPerPage = value.data.length;
    }
    response.data = value.data || defaults.data;
    response.user = value.user || defaults.user;
    response.type = value.user || defaults.type;
    response.error = value.error || {};
    response.success = true;

    if (value.count) {
        if (value.data && value.data.length < count) {
            reload();
            next(value.data.length);
        } else {
            reload();
        }
        if (value.query.skip !== 0) {
            prev(value.query.skip)
        }
    } else {
        reload();
    }
    res[value.method](response)
}

function query(req, res, next) {
    var defaults = {};
    defaults = _.extend(defaults, options.query);
    var models = _.keys(mongoose.models);
    var schemas = {};
    var query = req.query;
    var queryParameters = {};
    var schema = []
    var schemaSort = [];
    queryParameters.error = {};
    queryParameters.filter = {};
    _.forEach(models, function (n, key) {
        schemas[n] = {};
        schemas[n].schema = []
        schemas[n].schemaSort = [];
        schemas[n].tree = mongoose.models[n].schema.tree;
        _.forEach(schemas[n].tree, function (j, key) {
            schema.push(key)
            schemaSort.push(key)
            schemaSort.push('-' + key)
            schemas[n].schema.push(key)
            schemas[n].schemaSort.push(key)
            schemas[n].schemaSort.push('-' + key)
            _.forEach(query, function (a, keys) {
                if (keys == key) {
                    queryParameters.filter[keys] = a;
                }
            })
        })
    })

    //SKIP
    queryParameters.skip = query.skip || defaults.skip;
    //WHERE
    queryParameters.where = query.where || defaults.where;
    //Equals
    queryParameters.equals = query.equals || defaults.equals;
    //GT
    queryParameters.gt = query.gt || defaults.gt;
    //LT
    queryParameters.lt = query.lt || defaults.lt;
    //IN
    queryParameters.in = query.in || defaults.in;
    //LEAN
    queryParameters.lean = query.lean || defaults.lean;
    //SORT
    queryParameters.sort = query.sort ? sortCheck(query.sort) : defaults.sort;

    function sortCheck(sort) {
        return -1 !== schemaSort.indexOf(sort) ? sort : errorHandler(query.sort, "sort", defaults.sort);
    }
    //limitCheck
    queryParameters.limit = query.limit ? limitCheck(query.limit) : defaults.limit;

    function limitCheck(number) {
        //plan to switch out for https://jsperf.com/number-vs-parseint-vs-plus/95 in later version
        return number < defaults.limit ? parseInt(number) : errorHandler(query.limit, "limit", defaults.limit);
    }
    //selectCheck
    queryParameters.select = query.select ? selectCheck(query.select) : defaults.select;

    function selectCheck(select) {
        if (_.isArray(query.select)) {
            var selected = '';
            _.forEach(query.select, function (n, key) {
                if (schema.indexOf(n) !== -1) {
                    selected += n + ' ';
                } else {
                    errorHandler(n, "select", defaults.select);
                };
            });
            return selected;
        } else {
            return -1 !== schema.indexOf(select) ? select : errorHandler(query.select, "select", defaults.select);
        }
    }

    //populate
    queryParameters.populateId = query.populateId ? populateIdCheck(query.populateId) : populateIdCheck(models);
    queryParameters.populateItems = query.populateItems ? populateItemsCheck(query.populateItems) : populateItemsCheck(schema);

    function populateIdCheck(data) {
        var populateId = '';
        if (!_.isArray(data)) {
            data = data.replace(',', ' ').split(" ");
        }
        data = _.uniq(data);
        _.forEach(data, function (n, key) {
            if (models.indexOf(n) !== -1) {
                populateId += n + ' ';
            } else {
                errorHandler(n, "populateId", defaults.populateId);
            };
        })

        return populateId;
    }

    function populateItemsCheck(data) {
        var populateItems = '';
        if (!_.isArray(data)) {
            data = data.replace(',', ' ').split(" ");
        }
        data = _.uniq(data);
        _.forEach(data, function (n, key) {
            if (schema.indexOf(n) !== -1) {
                populateItems += n + ' ';
            } else {
                errorHandler(n, "populateItems", defaults.populateItems);
            };
        })

        return populateItems;
    }
    //ERRORHANDLER
    function errorHandler(errvalue, field, value) {
        if (!queryParameters.error[field]) queryParameters.error[field] = [];
        queryParameters.error[field].push({
            message: defaults.errorMessage,
            value: errvalue
        })
        return value;
    }
    req.queryParameters = queryParameters;

    next();
};
})();<|endoftext|>