<commit_before>/*!
 * Copyright 2013 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var _ = require('underscore');
var Etherpad = require('etherpad-lite-client');
var Url = require('url');

var log = require('oae-logger').logger('etherpad');
var Signature = require('oae-util/lib/signature');
var Validator = require('oae-util/lib/validator').Validator;

var etherpadServers = [];
var etherpadConfig = null;

/**
 * Initializes the etherpad client.
 *
 * @param  {Object}   _etherpadConfig     The etherpad config from config.js.
 */
var refreshConfiguration = module.exports.refreshConfiguration = function(_etherpadConfig) {
    // Remember this config.
    etherpadConfig = _etherpadConfig;

    // Rebuild the servers list and recreate from the configuration
    etherpadServers = [];
    _.each(etherpadConfig.hosts, function(host, index) {
        // Create the etherpad client with its sharding index
        var etherpad = {
            'index': index,
            'client': Etherpad.connect({
                'apikey': _etherpadConfig.apikey,
                'host': host.host,
                'port': host.port
            })
        };
        etherpadServers.push(etherpad);
    });
};

/**
 * Get the etherpad configuration.
 *
 * @return {Object} The etherpad configuration.
 */
var getConfig = module.exports.getConfig = function() {
    return etherpadConfig;
};

/**
 * Creates a pad via the etherpad API.
 *
 * @param  {String}     contentId                       The ID of the collaborative document for which an etherpad pad should be created.
 * @param  {Function}   callback                        Standard callback method.
 * @param  {Object}     callback.err                    Standard error object (if any).
 * @param  {Object}     callback.ids                    An object containing the etherpad IDs for this collaborative document.
 * @param  {String}     callback.ids.etherpadGroupId    The etherpad identifier for the group that was created.
 * @param  {String}     callback.ids.etherpadPadId      The etherpad identifier for the pad that was created.
 */
var createPad = module.exports.createPad = function(contentId, callback) {
    // Because etherpad has a slightly weird system of authenticating users
    // we need to create a group *PER* content item and then create a group pad in this group.

    // Get the client that points to the correct etherpad instance.
    var client = getClient(contentId);

    // Create the group.
    var args = {
        'groupMapper': contentId
    };
    log().trace({'contentId': contentId}, 'Creating etherpad group.');
    client.createGroupIfNotExistsFor(args, function(err, groupData) {
        if (err) {
            log().error({'err': err, 'contentId': contentId}, 'Could not create an etherpad group.');
            return callback({'code': 500, 'msg': err.message});
        }

        // Create the group pad.
        var groupPad = {
            'groupID': groupData.groupID,
            'padName': contentId
        };
        log().trace({'contentId': contentId, 'groupID': groupData.groupID}, 'Creating etherpad group pad.');
        client.createGroupPad(groupPad, function(err, padData) {
            if (err) {
                log().error({'err': err, 'contentId': contentId}, 'Could not create an etherpad group pad.');
                return callback({'code': 500, 'msg': err.message});
            }

            // Store these IDs in the database.
            var ids = {
                'etherpadGroupId': groupData.groupID,
                'etherpadPadId': padData.padID
            };
            log().info({'contentId': contentId, 'groupID': groupData.groupID, 'padID': padData.padID}, 'Created an etherpad group and pad.');
            callback(null, ids);
        });
    });
};

/**
 * Get the HTML for a pad.
 *
 * @param  {String}     contentId       The content id for which the HTML should be retrieved from etherpad.
 * @param  {String}     padId           The ID of the pad for which to retrieve the HTML.
 * @param  {Function}   callback        Standard callback method.
 * @param  {Object}     callback.err    Standard error object (if any.)
 * @param  {String}     callback.html   The HTML fragment for this pad.
 */
var getHTML = module.exports.getHTML = function(contentId, padId, callback) {
    log().trace({'contentId': contentId}, 'Getting etherpad HTML');
    getClient(contentId).getHTML({'padID': padId}, function(err, data) {
        if (err) {
            log().error({'err': err, 'padID': padId, 'contentId': contentId}, 'Could not grab the HTML from etherpad.');
            return callback({'code': 500, 'msg': 'Could not grab the HTML from etherpad.'});
        }

        callback(null, data.html);
    });
};

/**
 * Set the html for a pad.
 *
 * @param  {String}     contentId       The content id for which the HTML should be set in etherpad.
 * @param  {String}     padId           The ID of the pad for which to set the HTML.
 * @param  {String}     html            The HTML fragment to store in etherpad.
 * @param  {Function}   callback        Standard callback method.
 * @param  {Object}     callback.err    Standard error object (if any.)
 */
var setHTML = module.exports.setHTML = function(contentId, padId, html, callback) {
    log().trace({'contentId': contentId, 'html': html}, 'Setting etherpad html');

    // Although Etherpad exposes an API to set the HTML of a pad, it doesn't accept any HTML fragments.
    // We encapsulate the HTML fragment into a simple page and submit that instead.
    var toSend = '<!doctype html><title></title><meta charset="utf-8">' + html + '';
    getClient(contentId).setHTML({'padID': padId, 'html': toSend}, function(err, data) {
        if (err) {
            log().error({'err': err, 'padID': padId, 'contentId': contentId, 'html': html}, 'Could not set the html on the etherpad instance.');
            return callback({'code': 500, 'msg': 'Could not set the html on the etherpad instance.'});
        }

        callback(null);
    });
};

/**
 * Joins the current user in an etherpad.
 * This assumes that the current user has access to the collaborative document.
 *
 * @param  {Context}    ctx             The current context
 * @param  {String}     contentId       The content id of the apd that should be joined..
 * @param  {String}     padId           The ID of the pad that should be joined.
 * @param  {String}     groupId         The ID of the group that is associated to this pad.
 * @param  {Function}   callback        Standard callback method.
 * @param  {String}     callback.url    The public URL that the UI can use to embed the pad.
 */
var joinPad = module.exports.joinPad = function(ctx, contentId, padId, groupId, callback) {
    if (!ctx.user()) {
        return callback({'code': 401, 'msg': 'Anonymous users are not allowed to join collaborative documents.'});
    }

    // Get the etherpad client that will handle this contentId.
    var client = getClient(contentId);

    /*
     *   Joining a pad consists out of three things:
     *    1/ Mapping the OAE user to an etherpad author.
     *    2/ Creating a session for the etherpad author
     *    3/ Returning a url to the UI. It should contain
     *       * The server etherpad is running on (ex: http://7.etherpad.oae.com/)
     *       * The pad URI (ex: /oae/c_cam_abc123)
     *       * The session ID (ex: ?sessionID=s.32b01f91d0e2c9a344)
     */
    var args = {
        'authorMapper': ctx.user().id,
        'name': ctx.user().displayName
    };
    client.createAuthorIfNotExistsFor(args, function(err, author) {
        if (err) {
            log().error({'err': err, 'contentId': contentId, 'principalId': ctx.user().id}, 'Could not create an etherpad author.');
            return callback({'code': 500, 'msg': 'Could not create an author in the etherpad system.'});
        }

        var session = {
            'groupID': groupId,
            'authorID': author.authorID,
            'validUntil': Math.round(Date.now()/1000) + 60*60*24
        };
        log().trace(session, 'Creating a session');
        client.createSession(session, function(err, data) {
            if (err) {
                log().error({'err': err, 'contentId': contentId, 'principalId': ctx.user().id}, 'Could not create an etherpad session.');
                return callback({'code': 500, 'msg': 'Could not create an etherpad session for this user.'});
            }

            // Get the language for the current user.
            var language = 'en';
            var locale = ctx.user().locale;
            if (locale) {
                language = locale.split('_')[0];
            }

            // Construct the URL.
            var url = getPadUrl(contentId, padId, data.sessionID, language);
            return callback(null, {'url': url});
        });
    });
};

/**
 * Get the URL where users can view the etherpad pad.
 * This can be used to embed in the page via an iframe.
 * The URL will be of the form:
 *     /etherpad/0/oae/<pad ID>?sessionID=<session ID>&pathPrefix=/etherpad/0&language=en
 *
 * A couple of notes:
 *     *   The URL that will be embedded should be on the same domain as the current tenant.
 *         This is because Safari will not set cookies that are coming from another domain inside an iframe.
 *     *   We try to shard based on the content ID so that the load is spread across the etherpad cluster.
 *         Note that this is *NOT* sharding based on load, as some documents may be more popular than others.
 *     *   The `/etherpad/0` will have to be stripped off by nginx.
 *     *   We point to `/oae/<pad ID>` which is an endpoint exposed by the `ep_oae` plugin.
 *         That endpoint will take care of sending the session cookie.
 *     *   We need to send a pathPrefix so the `ep_oae` endpoint can construct the
 *         /etherpad/0/p/<pad ID> URL. Etherpad can take it from there.
 *
 * @param  {String}     contentId   The ID of the piece of content.
 * @param  {String}     padId       The ID of the pad in etherpad.
 * @param  {String}     sessionId   The ID of the session that should be included in the query string.
 * @param  {String}     language    The 2 character string that identifies the user's prefered language.
 * @return {String}                 The URL to the pad that can be used to embed in a page.
 */
var getPadUrl = module.exports.getPadUrl = function(contentId, padId, sessionId, language) {
    var serverIndex = _getServer(contentId).index;
    return Url.format({
        'pathname': '/etherpad/' + serverIndex + '/oae/' + padId,
        'query': {
            'sessionID': sessionId,
            'language': language,
            'pathPrefix': '/etherpad/' + serverIndex
        }
    });
};

/**
 * Get an etherpad client that can talk to an etherpad API.
 *
 * @param  {String}     contentId   The ID of the piece of content for which we need to retrieve an etherpad client.
 * @return {Client}                 The request etherpad client.
 */
var getClient = module.exports.getClient = function(contentId) {
    return _getServer(contentId).client;
};

/**
 * Get the server that is tied to a content ID.
 *
 * @param  {String}     contentId   The content ID for which the server should be retrieved.
 * @return {Object}                 The server tied to a collabration document.
 * @api private
 */
var _getServer = function(contentId) {
    var index = _hash(contentId, etherpadServers.length);
    return etherpadServers[index];
};

/**
 * Hashes a string and returns the index.
 *
 * @param  {String}     str     The string to hash.
 * @param  {String}     nr      The upper bound (exclusive) for the index.
 * @return {Number}             The index.
 * @api private
 */
var _hash = function(str, nr) {
    var code = 0;
    for (var i = 0; i < str.length; i++) {
        code += str.charCodeAt(i);
    }
    return code % nr;
};
<commit_msg>Improve documentation of etherpad.js refreshConfiguration method<commit_after>/*!
 * Copyright 2013 Apereo Foundation (AF) Licensed under the
 * Educational Community License, Version 2.0 (the "License"); you may
 * not use this file except in compliance with the License. You may
 * obtain a copy of the License at
 *
 *     http://opensource.org/licenses/ECL-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an "AS IS"
 * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing
 * permissions and limitations under the License.
 */

var _ = require('underscore');
var Etherpad = require('etherpad-lite-client');
var Url = require('url');

var log = require('oae-logger').logger('etherpad');
var Signature = require('oae-util/lib/signature');
var Validator = require('oae-util/lib/validator').Validator;

var etherpadServers = [];
var etherpadConfig = null;

/**
 * Refresh the runtime etherpad configuration (host list, api key, etc...) with the one provided. More
 * documentation about the etherpad configuration may be found in the `config.etherpad` key of the
 * default config.js file.
 *
 * @param  {Object}   etherpadConfig    The etherpad config from config.js
 */
var refreshConfiguration = module.exports.refreshConfiguration = function(_etherpadConfig) {
    // Remember this config.
    etherpadConfig = _etherpadConfig;

    // Rebuild the servers list and recreate from the configuration
    etherpadServers = [];
    _.each(etherpadConfig.hosts, function(host, index) {
        // Create the etherpad client with its sharding index
        var etherpad = {
            'index': index,
            'client': Etherpad.connect({
                'apikey': _etherpadConfig.apikey,
                'host': host.host,
                'port': host.port
            })
        };
        etherpadServers.push(etherpad);
    });
};

/**
 * Get the etherpad configuration.
 *
 * @return {Object} The etherpad configuration.
 */
var getConfig = module.exports.getConfig = function() {
    return etherpadConfig;
};

/**
 * Creates a pad via the etherpad API.
 *
 * @param  {String}     contentId                       The ID of the collaborative document for which an etherpad pad should be created.
 * @param  {Function}   callback                        Standard callback method.
 * @param  {Object}     callback.err                    Standard error object (if any).
 * @param  {Object}     callback.ids                    An object containing the etherpad IDs for this collaborative document.
 * @param  {String}     callback.ids.etherpadGroupId    The etherpad identifier for the group that was created.
 * @param  {String}     callback.ids.etherpadPadId      The etherpad identifier for the pad that was created.
 */
var createPad = module.exports.createPad = function(contentId, callback) {
    // Because etherpad has a slightly weird system of authenticating users
    // we need to create a group *PER* content item and then create a group pad in this group.

    // Get the client that points to the correct etherpad instance.
    var client = getClient(contentId);

    // Create the group.
    var args = {
        'groupMapper': contentId
    };
    log().trace({'contentId': contentId}, 'Creating etherpad group.');
    client.createGroupIfNotExistsFor(args, function(err, groupData) {
        if (err) {
            log().error({'err': err, 'contentId': contentId}, 'Could not create an etherpad group.');
            return callback({'code': 500, 'msg': err.message});
        }

        // Create the group pad.
        var groupPad = {
            'groupID': groupData.groupID,
            'padName': contentId
        };
        log().trace({'contentId': contentId, 'groupID': groupData.groupID}, 'Creating etherpad group pad.');
        client.createGroupPad(groupPad, function(err, padData) {
            if (err) {
                log().error({'err': err, 'contentId': contentId}, 'Could not create an etherpad group pad.');
                return callback({'code': 500, 'msg': err.message});
            }

            // Store these IDs in the database.
            var ids = {
                'etherpadGroupId': groupData.groupID,
                'etherpadPadId': padData.padID
            };
            log().info({'contentId': contentId, 'groupID': groupData.groupID, 'padID': padData.padID}, 'Created an etherpad group and pad.');
            callback(null, ids);
        });
    });
};

/**
 * Get the HTML for a pad.
 *
 * @param  {String}     contentId       The content id for which the HTML should be retrieved from etherpad.
 * @param  {String}     padId           The ID of the pad for which to retrieve the HTML.
 * @param  {Function}   callback        Standard callback method.
 * @param  {Object}     callback.err    Standard error object (if any.)
 * @param  {String}     callback.html   The HTML fragment for this pad.
 */
var getHTML = module.exports.getHTML = function(contentId, padId, callback) {
    log().trace({'contentId': contentId}, 'Getting etherpad HTML');
    getClient(contentId).getHTML({'padID': padId}, function(err, data) {
        if (err) {
            log().error({'err': err, 'padID': padId, 'contentId': contentId}, 'Could not grab the HTML from etherpad.');
            return callback({'code': 500, 'msg': 'Could not grab the HTML from etherpad.'});
        }

        callback(null, data.html);
    });
};

/**
 * Set the html for a pad.
 *
 * @param  {String}     contentId       The content id for which the HTML should be set in etherpad.
 * @param  {String}     padId           The ID of the pad for which to set the HTML.
 * @param  {String}     html            The HTML fragment to store in etherpad.
 * @param  {Function}   callback        Standard callback method.
 * @param  {Object}     callback.err    Standard error object (if any.)
 */
var setHTML = module.exports.setHTML = function(contentId, padId, html, callback) {
    log().trace({'contentId': contentId, 'html': html}, 'Setting etherpad html');

    // Although Etherpad exposes an API to set the HTML of a pad, it doesn't accept any HTML fragments.
    // We encapsulate the HTML fragment into a simple page and submit that instead.
    var toSend = '<!doctype html><title></title><meta charset="utf-8">' + html + '';
    getClient(contentId).setHTML({'padID': padId, 'html': toSend}, function(err, data) {
        if (err) {
            log().error({'err': err, 'padID': padId, 'contentId': contentId, 'html': html}, 'Could not set the html on the etherpad instance.');
            return callback({'code': 500, 'msg': 'Could not set the html on the etherpad instance.'});
        }

        callback(null);
    });
};

/**
 * Joins the current user in an etherpad.
 * This assumes that the current user has access to the collaborative document.
 *
 * @param  {Context}    ctx             The current context
 * @param  {String}     contentId       The content id of the apd that should be joined..
 * @param  {String}     padId           The ID of the pad that should be joined.
 * @param  {String}     groupId         The ID of the group that is associated to this pad.
 * @param  {Function}   callback        Standard callback method.
 * @param  {String}     callback.url    The public URL that the UI can use to embed the pad.
 */
var joinPad = module.exports.joinPad = function(ctx, contentId, padId, groupId, callback) {
    if (!ctx.user()) {
        return callback({'code': 401, 'msg': 'Anonymous users are not allowed to join collaborative documents.'});
    }

    // Get the etherpad client that will handle this contentId.
    var client = getClient(contentId);

    /*
     *   Joining a pad consists out of three things:
     *    1/ Mapping the OAE user to an etherpad author.
     *    2/ Creating a session for the etherpad author
     *    3/ Returning a url to the UI. It should contain
     *       * The server etherpad is running on (ex: http://7.etherpad.oae.com/)
     *       * The pad URI (ex: /oae/c_cam_abc123)
     *       * The session ID (ex: ?sessionID=s.32b01f91d0e2c9a344)
     */
    var args = {
        'authorMapper': ctx.user().id,
        'name': ctx.user().displayName
    };
    client.createAuthorIfNotExistsFor(args, function(err, author) {
        if (err) {
            log().error({'err': err, 'contentId': contentId, 'principalId': ctx.user().id}, 'Could not create an etherpad author.');
            return callback({'code': 500, 'msg': 'Could not create an author in the etherpad system.'});
        }

        var session = {
            'groupID': groupId,
            'authorID': author.authorID,
            'validUntil': Math.round(Date.now()/1000) + 60*60*24
        };
        log().trace(session, 'Creating a session');
        client.createSession(session, function(err, data) {
            if (err) {
                log().error({'err': err, 'contentId': contentId, 'principalId': ctx.user().id}, 'Could not create an etherpad session.');
                return callback({'code': 500, 'msg': 'Could not create an etherpad session for this user.'});
            }

            // Get the language for the current user.
            var language = 'en';
            var locale = ctx.user().locale;
            if (locale) {
                language = locale.split('_')[0];
            }

            // Construct the URL.
            var url = getPadUrl(contentId, padId, data.sessionID, language);
            return callback(null, {'url': url});
        });
    });
};

/**
 * Get the URL where users can view the etherpad pad.
 * This can be used to embed in the page via an iframe.
 * The URL will be of the form:
 *     /etherpad/0/oae/<pad ID>?sessionID=<session ID>&pathPrefix=/etherpad/0&language=en
 *
 * A couple of notes:
 *     *   The URL that will be embedded should be on the same domain as the current tenant.
 *         This is because Safari will not set cookies that are coming from another domain inside an iframe.
 *     *   We try to shard based on the content ID so that the load is spread across the etherpad cluster.
 *         Note that this is *NOT* sharding based on load, as some documents may be more popular than others.
 *     *   The `/etherpad/0` will have to be stripped off by nginx.
 *     *   We point to `/oae/<pad ID>` which is an endpoint exposed by the `ep_oae` plugin.
 *         That endpoint will take care of sending the session cookie.
 *     *   We need to send a pathPrefix so the `ep_oae` endpoint can construct the
 *         /etherpad/0/p/<pad ID> URL. Etherpad can take it from there.
 *
 * @param  {String}     contentId   The ID of the piece of content.
 * @param  {String}     padId       The ID of the pad in etherpad.
 * @param  {String}     sessionId   The ID of the session that should be included in the query string.
 * @param  {String}     language    The 2 character string that identifies the user's prefered language.
 * @return {String}                 The URL to the pad that can be used to embed in a page.
 */
var getPadUrl = module.exports.getPadUrl = function(contentId, padId, sessionId, language) {
    var serverIndex = _getServer(contentId).index;
    return Url.format({
        'pathname': '/etherpad/' + serverIndex + '/oae/' + padId,
        'query': {
            'sessionID': sessionId,
            'language': language,
            'pathPrefix': '/etherpad/' + serverIndex
        }
    });
};

/**
 * Get an etherpad client that can talk to an etherpad API.
 *
 * @param  {String}     contentId   The ID of the piece of content for which we need to retrieve an etherpad client.
 * @return {Client}                 The request etherpad client.
 */
var getClient = module.exports.getClient = function(contentId) {
    return _getServer(contentId).client;
};

/**
 * Get the server that is tied to a content ID.
 *
 * @param  {String}     contentId   The content ID for which the server should be retrieved.
 * @return {Object}                 The server tied to a collabration document.
 * @api private
 */
var _getServer = function(contentId) {
    var index = _hash(contentId, etherpadServers.length);
    return etherpadServers[index];
};

/**
 * Hashes a string and returns the index.
 *
 * @param  {String}     str     The string to hash.
 * @param  {String}     nr      The upper bound (exclusive) for the index.
 * @return {Number}             The index.
 * @api private
 */
var _hash = function(str, nr) {
    var code = 0;
    for (var i = 0; i < str.length; i++) {
        code += str.charCodeAt(i);
    }
    return code % nr;
};
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API

const Tapable = require("tapable-old");

class WebAssemblyParser extends Tapable {
	constructor(options) {
		super();
		this.options = options;
	}

	parse(source, initialState) {
		// Does nothing current
		// TODO parse WASM AST and walk it
		// extract exports, imports
		return initialState;
	}
}

module.exports = WebAssemblyParser;
<commit_msg>upgrade tapable for WebAssemblyParser<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

// Syntax: https://developer.mozilla.org/en/SpiderMonkey/Parser_API

const Tapable = require("tapable").Tapable;

class WebAssemblyParser extends Tapable {
	constructor(options) {
		super();
		this.hooks = {};
		this.options = options;
	}

	parse(source, initialState) {
		// Does nothing current
		// TODO parse WASM AST and walk it
		// extract exports, imports
		return initialState;
	}
}

module.exports = WebAssemblyParser;
<|endoftext|>


<commit_before>elation.require(['elements.elements'], function() {
  elation.elements.define('ui.formgroup', class extends elation.elements.base {
    create() {
    }
  });
});
<commit_msg>Support labels for formgroups<commit_after>elation.require(['elements.elements'], function() {
  elation.elements.define('ui.formgroup', class extends elation.elements.base {
    init() {
      super.init();
      this.defineAttributes({
        'label': { type: 'text' }
      });
    }
    create() {
      if (this.label) {
        this.labelobj = elation.elements.create('ui-label', {
          label: this.label,
          append: this,
          class: 'groupheader'
        });
      }
    }
  });
});
<|endoftext|>


<commit_before>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import classNames from 'classnames';
import ClickListener from '../../internal/ClickListener';
import FloatingMenu from '../../internal/FloatingMenu';
import OptimizedResize from '../../internal/OptimizedResize';
import Icon from '../Icon';

export default class OverflowMenu extends Component {
  static propTypes = {
    open: PropTypes.bool,
    flipped: PropTypes.bool,
    floatingMenu: PropTypes.bool,
    children: PropTypes.node,
    className: PropTypes.string,
    tabIndex: PropTypes.number,
    id: PropTypes.string,
    ariaLabel: PropTypes.string,
    onClick: PropTypes.func,
    onFocus: PropTypes.func,
    onKeyDown: PropTypes.func,
    handleClick: PropTypes.func,
    iconDescription: PropTypes.string.isRequired,
    iconName: PropTypes.string,
    menuOffset: PropTypes.object,
    menuOffsetFlip: PropTypes.object,
    iconClass: PropTypes.string,
  };

  static defaultProps = {
    ariaLabel: 'list of options',
    iconDescription: 'open and close list of options',
    iconName: 'overflow-menu',
    open: false,
    flipped: false,
    floatingMenu: false,
    onClick: () => {},
    tabIndex: 0,
    menuOffset: { top: 0, left: 60.5 },
    menuOffsetFlip: { top: 0, left: -60.5 },
  };

  state = {
    open: this.props.open,
  };

  shouldComponentUpdate(nextProps, nextState) {
    if (nextState.open && !this.state.open) {
      requestAnimationFrame(() => {
        this.getMenuPosition();
      });
      return false; // Let `.getMenuPosition()` cause render
    }
    return true;
  }

  componentDidMount() {
    requestAnimationFrame(() => {
      this.getMenuPosition();
    });
    this.hResize = OptimizedResize.add(() => {
      this.getMenuPosition();
    });
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.open !== this.props.open) {
      this.setState({ open: nextProps.open });
    }
  }

  componentWillUnmount() {
    this.hResize.release();
  }

  getMenuPosition = () => {
    if (this.menuEl) {
      const menuPosition = this.menuEl.getBoundingClientRect();
      this.setState({ menuPosition });
    }
  };

  handleClick = evt => {
    this.setState({ open: !this.state.open });
    this.props.onClick(evt);
  };

  handleKeyPress = evt => {
    const key = evt.key || evt.which;

    if (key === 'Enter' || key === 13 || key === ' ' || key === 32) {
      this.setState({ open: !this.state.open });
    }
  };

  handleClickOutside = () => {
    this.closeMenu();
  };

  closeMenu = () => {
    this.setState({ open: false });
  };

  bindMenuEl = menuEl => {
    this.menuEl = menuEl;
  };

  render() {
    const {
      id,
      tabIndex,
      ariaLabel,
      children,
      iconDescription,
      iconName,
      flipped,
      floatingMenu,
      menuOffset,
      menuOffsetFlip,
      iconClass,
      onClick, // eslint-disable-line
      ...other
    } = this.props;

    const { open } = this.state;

    const overflowMenuClasses = classNames(
      this.props.className,
      'bx--overflow-menu',
      {
        'bx--overflow-menu--open': open,
      }
    );

    const overflowMenuOptionsClasses = classNames('bx--overflow-menu-options', {
      'bx--overflow-menu--flip': this.props.flipped,
      'bx--overflow-menu-options--open': open,
    });

    const overflowMenuIconClasses = classNames(
      'bx--overflow-menu__icon',
      iconClass
    );

    const childrenWithProps = React.Children.toArray(children).map(child =>
      React.cloneElement(child, {
        closeMenu: this.closeMenu,
      })
    );

    return (
      <ClickListener onClickOutside={this.handleClickOutside}>

          <Icon
            onClick={this.handleClick}
            className={overflowMenuIconClasses}
            name={iconName}
            description={iconDescription}
            style={{ width: '100%' }}
          />
          {!open ? null : floatingMenu ? (
            <FloatingMenu
              menuPosition={this.state.menuPosition}
              menuDirection="bottom"
              menuOffset={flipped ? menuOffsetFlip : menuOffset}>

                {childrenWithProps}

            </FloatingMenu>
          ) : (

{childrenWithProps}

          )}

      </ClickListener>
    );
  }
}
<commit_msg>chore(OverflowMenu): hoist menu options nodes (#465)<commit_after>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import classNames from 'classnames';
import ClickListener from '../../internal/ClickListener';
import FloatingMenu from '../../internal/FloatingMenu';
import OptimizedResize from '../../internal/OptimizedResize';
import Icon from '../Icon';

export default class OverflowMenu extends Component {
  static propTypes = {
    open: PropTypes.bool,
    flipped: PropTypes.bool,
    floatingMenu: PropTypes.bool,
    children: PropTypes.node,
    className: PropTypes.string,
    tabIndex: PropTypes.number,
    id: PropTypes.string,
    ariaLabel: PropTypes.string,
    onClick: PropTypes.func,
    onFocus: PropTypes.func,
    onKeyDown: PropTypes.func,
    handleClick: PropTypes.func,
    iconDescription: PropTypes.string.isRequired,
    iconName: PropTypes.string,
    menuOffset: PropTypes.object,
    menuOffsetFlip: PropTypes.object,
    iconClass: PropTypes.string,
  };

  static defaultProps = {
    ariaLabel: 'list of options',
    iconDescription: 'open and close list of options',
    iconName: 'overflow-menu',
    open: false,
    flipped: false,
    floatingMenu: false,
    onClick: () => {},
    tabIndex: 0,
    menuOffset: { top: 0, left: 60.5 },
    menuOffsetFlip: { top: 0, left: -60.5 },
  };

  state = {
    open: this.props.open,
  };

  shouldComponentUpdate(nextProps, nextState) {
    if (nextState.open && !this.state.open) {
      requestAnimationFrame(() => {
        this.getMenuPosition();
      });
      return false; // Let `.getMenuPosition()` cause render
    }
    return true;
  }

  componentDidMount() {
    requestAnimationFrame(() => {
      this.getMenuPosition();
    });
    this.hResize = OptimizedResize.add(() => {
      this.getMenuPosition();
    });
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.open !== this.props.open) {
      this.setState({ open: nextProps.open });
    }
  }

  componentWillUnmount() {
    this.hResize.release();
  }

  getMenuPosition = () => {
    if (this.menuEl) {
      const menuPosition = this.menuEl.getBoundingClientRect();
      this.setState({ menuPosition });
    }
  };

  handleClick = evt => {
    this.setState({ open: !this.state.open });
    this.props.onClick(evt);
  };

  handleKeyPress = evt => {
    const key = evt.key || evt.which;

    if (key === 'Enter' || key === 13 || key === ' ' || key === 32) {
      this.setState({ open: !this.state.open });
    }
  };

  handleClickOutside = () => {
    this.closeMenu();
  };

  closeMenu = () => {
    this.setState({ open: false });
  };

  bindMenuEl = menuEl => {
    this.menuEl = menuEl;
  };

  render() {
    const {
      id,
      tabIndex,
      ariaLabel,
      children,
      iconDescription,
      iconName,
      flipped,
      floatingMenu,
      menuOffset,
      menuOffsetFlip,
      iconClass,
      onClick, // eslint-disable-line
      ...other
    } = this.props;

    const { open } = this.state;

    const overflowMenuClasses = classNames(
      this.props.className,
      'bx--overflow-menu',
      {
        'bx--overflow-menu--open': open,
      }
    );

    const overflowMenuOptionsClasses = classNames('bx--overflow-menu-options', {
      'bx--overflow-menu--flip': this.props.flipped,
      'bx--overflow-menu-options--open': open,
    });

    const overflowMenuIconClasses = classNames(
      'bx--overflow-menu__icon',
      iconClass
    );

    const childrenWithProps = React.Children.toArray(children).map(child =>
      React.cloneElement(child, {
        closeMenu: this.closeMenu,
      })
    );

    const menuBody = (

{childrenWithProps}

    );
    const wrappedMenuBody = !floatingMenu ? (
      menuBody
    ) : (
      <FloatingMenu
        menuPosition={this.state.menuPosition}
        menuDirection="bottom"
        menuOffset={flipped ? menuOffsetFlip : menuOffset}>
        {menuBody}
      </FloatingMenu>
    );

    return (
      <ClickListener onClickOutside={this.handleClickOutside}>

          <Icon
            onClick={this.handleClick}
            className={overflowMenuIconClasses}
            name={iconName}
            description={iconDescription}
            style={{ width: '100%' }}
          />
          {open && wrappedMenuBody}

      </ClickListener>
    );
  }
}
<|endoftext|>


<commit_before>var path = require("path");

var Component = require("../component");
var ScriptsComponent = require("./scripts");

var array_utils = require("../../utils/array");
var verify = require("../../utils/verify");

var GCOVR_PATH = path.resolve("build-tools/gcovr");

/**
 * @class CppComponent
 * C++ component definiton.
 *
 * @param {!Object} configuration The configuration of the component.
 */
var CppComponent = module.exports = function CppComponent(configuration) {
  this._verify(configuration);
  this._exclude = configuration.exclude;

  Component.call(this, configuration);

  this._path  = configuration.path;
  this._types = {
    bin: this._compileBin,
    lib: this._compileLib
  };
};
CppComponent.prototype = Object.create(Component.prototype);

/**
 * Configures and enqueues tasks based on the target type.
 * @param {!String} key    The base configuration key for generated tasks.
 * @param {!String} name   The base task name for generated tasks.
 * @param {!String} target The target to compile.
 * @param {!Components} components Collection of components in the system.
 */
CppComponent.prototype._compileByType = function _compileByType(
    key, name, target, components
) {
  var type = this._targets[target].type;
  if (!type) {
    // No type set, skip this step.
    return;
  }

  if (!(type in this._types)) {
    throw new Error("Unrecognised target type '" + type + "'");
  }

  var handler = this._types[type];
  handler.call(this, key, name, target, components);
};

/**
 * Configures and enqueues the tasks to compile the core of the component.
 * @param {!String} key    The base configuration key for generated tasks.
 * @param {!String} name   The base task name for generated tasks.
 * @param {!String} target The target to compile.
 * @param {!Components} components Collection of components in the system.
 */
CppComponent.prototype._compileCore = function _compileCore(
    key, name, target, components
) {
  var include = this._includes(components, target);
  var sources = this._sources(target);

  this._grunt.config("g++." + key + "\\.core", {
    coverage: target === "test",
    debug:    target !== "release",
    include:  include,
    objects_path: path.join("out", "build", target),
    src: sources
  });
  this._grunt.task.run("g++:" + name + ".core");
};

/**
 * Configures and enqueues tasks for binaries.
 * @param {!String} key    The base configuration key for generated tasks.
 * @param {!String} name   The base task name for generated tasks.
 * @param {!String} target The target to compile.
 * @param {Boolean} link_gtest True if linking tests.
 * @param {!Components} components Collection of components in the system.
 */
CppComponent.prototype._compileBin = function _compileBin(
    key, name, target, components, link_gtest
) {
  var bin_name  = this._name;
  var libraries = this._dynamicLibraries(components, target);
  var objects   = [path.join("out", "build", target, this._path, "**", "*.o")];
  var task_ext  = "bin";

  if (link_gtest) {
    bin_name = "run-tests";
    libraries.push("pthread", "gcov");
    task_ext = "gtest";

    // Exclude main.o from tests to avoid link error.
    objects.push(
        "!" + path.join("out", "build", target, this._path, "**", "main.o"),
        path.join("out", "build", "gtest", "**", "*.o")
    );
  }

  objects.push.apply(objects, this._staticLibraries(components, target));

  this._grunt.config("link++." + key + "\\." + task_ext, {
    libs:  libraries,
    files: [{
      dest: path.join("out", "dist", target, this._path, bin_name),
      src:  objects
    }]
  });
  this._grunt.task.run("link++:" + name + "." + task_ext);
};

CppComponent.prototype._compileGTest = function _compileGTest(key, name) {
  this._grunt.config("g++." + key + "\\.gtest", {
    coverage: true,
    debug:    true,
    include:  ["3rd-parties/include", "3rd-parties/sources/gtest"],
    objects_path: path.join("out", "build", "gtest"),
    src: [
      "3rd-parties/sources/gtest/src/gtest-all.cc",
      "3rd-parties/sources/gtest/src/gtest_main.cc"
    ]
  });
  this._grunt.task.run("g++:" + name + ".gtest");
};

/**
 * Configures and enqueues tasks for static libraries.
 * @param {!String} key    The base configuration key for generated tasks.
 * @param {!String} name   The base task name for generated tasks.
 * @param {!String} target The target to compile.
 * @param {!Components} components Collection of components in the system.
 */
CppComponent.prototype._compileLib = function _compileLib(
    key, name, target, components
) {
  this._grunt.config("ar." + key + "\\.lib", {
    files: [{
      dest: path.join("out", "dist", target, this._path, this._name + ".a"),
      src:  path.join("out", "build", target, this._path, "**", "*.o")
    }]
  });
  this._grunt.task.run("ar:" + name + ".lib");
};

/**
 * Lists the dynamic libraries needed for this component.
 * @param {!Components} components Collection of components in the system.
 * @param {!String}     target     The target mode to compile for.
 * @returns {!Array.<!String>} the list of dynamic libraries.
 */
CppComponent.prototype._dynamicLibraries = function _dynamicLibraries(
    components, target
) {
  var libs = [];
  var deps = components.resolve(this._name, target);

  deps.forEach(function(dep) {
    var dep_target = dep.target;
    dep = dep.instance;
    var should_check = (
        dep instanceof CppComponent &&
        dep._targets[dep_target].type === "lib"
    );
    if (should_check) {
      libs.push.apply(libs, dep._targets[dep_target].libs || []);
    }
  });

  libs.push.apply(libs, this._targets[target].libs || []);
  return libs;
};

/**
 * List include paths for the current component based on its dependencies.
 * @param {!Components} components Collection of components in the system.
 * @param {!String}     target     The target mode to compile for.
 * @returns {!Array.<!String>} the list of include paths.
 */
CppComponent.prototype._includes = function _includes(components, target) {
  var include = [];
  var deps    = components.resolve(this._name, target);

  deps.forEach(function(dep) {
    dep = dep.instance;
    if (dep instanceof CppComponent || dep instanceof ScriptsComponent) {
      include.push(path.join(dep._path, "include"));
    }
  });

  if (this._targets[target].include) {
    include.push.apply(include, this._targets[target].include);
  }
  return include;
};

//@override
CppComponent.prototype._process_targets = function _process_targets(config) {
  Component.prototype._process_targets.call(this, config);

  var _this   = this;
  var targets = Object.keys(this._targets);

  targets.forEach(function(target_name) {
    _this._verifyTarget(config.targets[target_name]);

    var target  = config.targets[target_name];
    var exclude = [];
    var include = [];
    var libs    = [];

    if (config.exclude) {
      exclude.push.apply(exclude, config.exclude);
    }
    if (target.exclude) {
      exclude.push.apply(exclude, target.exclude);
    }

    if (config.include) {
      include.push.apply(include, config.include);
    }
    if (target.include) {
      include.push.apply(include, target.include);
    }

    if (config.libs) {
      libs.push.apply(libs, config.libs);
    }
    if (target.libs) {
      libs.push.apply(libs, target.libs);
    }

    _this._targets[target_name].exclude = array_utils.filterDuplicates(exclude);
    _this._targets[target_name].include = array_utils.filterDuplicates(include);
    _this._targets[target_name].libs = array_utils.filterDuplicates(libs);
    _this._targets[target_name].type = target.type;
  });
};

/**
 * Lists glob patterns for source files of the core task.
 * @param {!String} target The target mode to compile for.
 * @returns {!Array.<!String>} the list of source files.
 */
CppComponent.prototype._sources = function _sources(target) {
  var sources = [path.join(this._path, "src", "**", "*.cpp")];

  if (this._targets[target].exclude) {
    this._targets[target].exclude.forEach(function(exclude) {
      sources.push("!" + exclude);
    });
  }

  return sources;
};

/**
 * Lists the static libraries needed for this component.
 * @param {!Components} components Collection of components in the system.
 * @param {!String}     target     The target mode to compile for.
 * @returns {!Array.<!String>} the list of static library paths.
 */
CppComponent.prototype._staticLibraries = function _staticLibraries(
    components, target
) {
  var libs = [];
  var deps = components.resolve(this._name, target);

  deps.forEach(function(dep) {
    var dep_target = dep.target;
    dep = dep.instance;
    var should_check = (
        dep instanceof CppComponent &&
        dep._targets[dep_target].type === "lib"
    );
    if (should_check) {
      libs.push(path.join(
          "out", "dist", dep_target, dep._path, dep.name() + ".a"
      ));
    }
  });

  libs.reverse();
  return libs;
};

/**
 * Verifies the configuration.
 * @param {!Object} configuration The configuration to verify.
 */
CppComponent.prototype._verify = function _verify(configuration) {
  var exclude_message = (
      "The exclude attribute must be array of strings, if specified"
  );

  verify.notEmptyString(configuration.path, "Missing component path");
  verify.optionalArray(configuration.exclude, exclude_message);

  (configuration.exclude || []).forEach(function(exclude) {
    verify.notEmptyString(exclude, exclude_message);
  });
};

/**
 * Verifies a target configuration.
 * @param {!Object} target The target configuration to verify.
 */
CppComponent.prototype._verifyTarget = function _verifyTarget(target) {
  var exclude_message = (
      "The exclude attribute must be array of strings, if specified"
  );
  var include_message = (
      "The include attribute must be array of strings, if specified"
  );
  var libs_message = (
      "The libs attribute must be array of strings, if specified"
  );

  verify.optionalArray(target.exclude, exclude_message);
  verify.optionalArray(target.include, include_message);
  verify.optionalArray(target.libs,    libs_message);

  (target.exclude || []).forEach(function(exclude) {
    verify.notEmptyString(exclude, exclude_message);
  });
  (target.include || []).forEach(function(include) {
    verify.notEmptyString(include, include_message);
  });
  (target.libs || []).forEach(function(lib) {
    verify.notEmptyString(lib, libs_message);
  });

  if (typeof target.type !== "undefined") {
    verify.notEmptyString(target.type, "Type must be a valid string");
  }
};

//@override
CppComponent.prototype.getCleanPath = function getCleanPath(target) {
  var paths = [
    path.join("out", "build", target, this._path),
    path.join("out", "dist",  target, this._path)
  ];

  if (target === "analysis") {
    paths.push(path.join("out", "reports", this._path));
  }

  return paths;
};

//Override
Component.prototype.handleAnalysis = function handleAnalysis(components) {
  var key  = "analysis\\." + this._name;
  var name = "analysis." + this._name;

  // Run linter.
  this._grunt.config("cpplint." + key, {
    options: {
      root: path.normalize(path.join(this._path, "include")),
      filter: [
        "-runtime/indentation_namespace"
      ]
    },
    src: [
      path.join(this._path, "include", "**", "*.h"),
      path.join(this._path, "src", "**", "*.cpp")
    ]
  });
  this._grunt.task.run("cpplint:" + name);

  // Stop here if test target does not exist.
  if (!this.hasTarget("test")) {
    return;
  }

  // Run static analysis.
  var include = this._includes(components, "test");
  this._grunt.config("cppcheck." + key, {
    exclude: ["3rd-parties", path.join(this._path, "tests")],
    include: include,
    save_to: path.join("out", "reports", this._path, "cppcheck.xml"),
    src: [
      path.join(this._path, "include", "**", "*.h"),
      path.join(this._path, "src", "**", "*.cpp")
    ]
  });
  this._grunt.task.run("cppcheck:" + name);

  // Run tests.
  this._grunt.config("shell." + key, {
    command: (
      path.join("out", "dist", "test", this._path, "run-tests") +
      " --gtest_output='xml:" +
      path.join("out", "reports", this._path, "test-results.xml") + "'"
    )
  });
  this._grunt.task.run("shell:" + name);

  // Run coverage.
  this._grunt.config("gcovr." + key, {
    exclude: ".*(3rd-parties|tests).*",
    gcovr:   GCOVR_PATH,
    objects: path.join("out", "build", "test", this._path, "src"),
    save_to: path.join("out", "reports", this._path, "coverage.xml")
  });
  this._grunt.task.run("gcovr:" + name);
};

//Override
CppComponent.prototype.handleTarget = function handleTarget(
    target, components
) {
  var key  = target + "\\." + this._name;
  var name = target + "." + this._name;

  this._compileCore(key, name, target, components);
  this._compileByType(key, name, target, components);

  if (target === "test") {
    this._compileGTest(key, name);
    this._compileBin(key, name, target, components, true);
  }
};
<commit_msg>Fixed C++ compilation process that ignored all tests.<commit_after>var path = require("path");

var Component = require("../component");
var ScriptsComponent = require("./scripts");

var array_utils = require("../../utils/array");
var verify = require("../../utils/verify");

var GCOVR_PATH = path.resolve("build-tools/gcovr");

/**
 * @class CppComponent
 * C++ component definiton.
 *
 * @param {!Object} configuration The configuration of the component.
 */
var CppComponent = module.exports = function CppComponent(configuration) {
  this._verify(configuration);
  this._exclude = configuration.exclude;

  Component.call(this, configuration);

  this._path  = configuration.path;
  this._types = {
    bin: this._compileBin,
    lib: this._compileLib
  };
};
CppComponent.prototype = Object.create(Component.prototype);

/**
 * Configures and enqueues tasks based on the target type.
 * @param {!String} key    The base configuration key for generated tasks.
 * @param {!String} name   The base task name for generated tasks.
 * @param {!String} target The target to compile.
 * @param {!Components} components Collection of components in the system.
 */
CppComponent.prototype._compileByType = function _compileByType(
    key, name, target, components
) {
  var type = this._targets[target].type;
  if (!type) {
    // No type set, skip this step.
    return;
  }

  if (!(type in this._types)) {
    throw new Error("Unrecognised target type '" + type + "'");
  }

  var handler = this._types[type];
  handler.call(this, key, name, target, components);
};

/**
 * Configures and enqueues the tasks to compile the core of the component.
 * @param {!String} key    The base configuration key for generated tasks.
 * @param {!String} name   The base task name for generated tasks.
 * @param {!String} target The target to compile.
 * @param {!Components} components Collection of components in the system.
 */
CppComponent.prototype._compileCore = function _compileCore(
    key, name, target, components
) {
  var include = this._includes(components, target);
  var sources = this._sources(target);

  this._grunt.config("g++." + key + "\\.core", {
    coverage: target === "test",
    debug:    target !== "release",
    include:  include,
    objects_path: path.join("out", "build", target),
    src: sources
  });
  this._grunt.task.run("g++:" + name + ".core");
};

/**
 * Configures and enqueues tasks for binaries.
 * @param {!String} key    The base configuration key for generated tasks.
 * @param {!String} name   The base task name for generated tasks.
 * @param {!String} target The target to compile.
 * @param {Boolean} link_gtest True if linking tests.
 * @param {!Components} components Collection of components in the system.
 */
CppComponent.prototype._compileBin = function _compileBin(
    key, name, target, components, link_gtest
) {
  var bin_name  = this._name;
  var libraries = this._dynamicLibraries(components, target);
  var objects   = [path.join("out", "build", target, this._path, "**", "*.o")];
  var task_ext  = "bin";

  if (link_gtest) {
    bin_name = "run-tests";
    libraries.push("pthread", "gcov");
    task_ext = "gtest";

    // Exclude main.o from tests to avoid link error.
    objects.push(
        "!" + path.join("out", "build", target, this._path, "**", "main.o"),
        path.join("out", "build", "gtest", "**", "*.o")
    );
  }

  objects.push.apply(objects, this._staticLibraries(components, target));

  this._grunt.config("link++." + key + "\\." + task_ext, {
    libs:  libraries,
    files: [{
      dest: path.join("out", "dist", target, this._path, bin_name),
      src:  objects
    }]
  });
  this._grunt.task.run("link++:" + name + "." + task_ext);
};

CppComponent.prototype._compileGTest = function _compileGTest(key, name) {
  this._grunt.config("g++." + key + "\\.gtest", {
    coverage: true,
    debug:    true,
    include:  ["3rd-parties/include", "3rd-parties/sources/gtest"],
    objects_path: path.join("out", "build", "gtest"),
    src: [
      "3rd-parties/sources/gtest/src/gtest-all.cc",
      "3rd-parties/sources/gtest/src/gtest_main.cc"
    ]
  });
  this._grunt.task.run("g++:" + name + ".gtest");
};

/**
 * Configures and enqueues tasks for static libraries.
 * @param {!String} key    The base configuration key for generated tasks.
 * @param {!String} name   The base task name for generated tasks.
 * @param {!String} target The target to compile.
 * @param {!Components} components Collection of components in the system.
 */
CppComponent.prototype._compileLib = function _compileLib(
    key, name, target, components
) {
  this._grunt.config("ar." + key + "\\.lib", {
    files: [{
      dest: path.join("out", "dist", target, this._path, this._name + ".a"),
      src:  path.join("out", "build", target, this._path, "**", "*.o")
    }]
  });
  this._grunt.task.run("ar:" + name + ".lib");
};

/**
 * Lists the dynamic libraries needed for this component.
 * @param {!Components} components Collection of components in the system.
 * @param {!String}     target     The target mode to compile for.
 * @returns {!Array.<!String>} the list of dynamic libraries.
 */
CppComponent.prototype._dynamicLibraries = function _dynamicLibraries(
    components, target
) {
  var libs = [];
  var deps = components.resolve(this._name, target);

  deps.forEach(function(dep) {
    var dep_target = dep.target;
    dep = dep.instance;
    var should_check = (
        dep instanceof CppComponent &&
        dep._targets[dep_target].type === "lib"
    );
    if (should_check) {
      libs.push.apply(libs, dep._targets[dep_target].libs || []);
    }
  });

  libs.push.apply(libs, this._targets[target].libs || []);
  return libs;
};

/**
 * List include paths for the current component based on its dependencies.
 * @param {!Components} components Collection of components in the system.
 * @param {!String}     target     The target mode to compile for.
 * @returns {!Array.<!String>} the list of include paths.
 */
CppComponent.prototype._includes = function _includes(components, target) {
  var include = [];
  var deps    = components.resolve(this._name, target);

  deps.forEach(function(dep) {
    dep = dep.instance;
    if (dep instanceof CppComponent || dep instanceof ScriptsComponent) {
      include.push(path.join(dep._path, "include"));
    }
  });

  if (this._targets[target].include) {
    include.push.apply(include, this._targets[target].include);
  }

  // Use bundled-in gtest in case the system has another version.
  if (target === "test") {
    include.push("3rd-parties/include");
  }
  return include;
};

//@override
CppComponent.prototype._process_targets = function _process_targets(config) {
  Component.prototype._process_targets.call(this, config);

  var _this   = this;
  var targets = Object.keys(this._targets);

  targets.forEach(function(target_name) {
    _this._verifyTarget(config.targets[target_name]);

    var target  = config.targets[target_name];
    var exclude = [];
    var include = [];
    var libs    = [];

    if (config.exclude) {
      exclude.push.apply(exclude, config.exclude);
    }
    if (target.exclude) {
      exclude.push.apply(exclude, target.exclude);
    }

    if (config.include) {
      include.push.apply(include, config.include);
    }
    if (target.include) {
      include.push.apply(include, target.include);
    }

    if (config.libs) {
      libs.push.apply(libs, config.libs);
    }
    if (target.libs) {
      libs.push.apply(libs, target.libs);
    }

    _this._targets[target_name].exclude = array_utils.filterDuplicates(exclude);
    _this._targets[target_name].include = array_utils.filterDuplicates(include);
    _this._targets[target_name].libs = array_utils.filterDuplicates(libs);
    _this._targets[target_name].type = target.type;
  });
};

/**
 * Lists glob patterns for source files of the core task.
 * @param {!String} target The target mode to compile for.
 * @returns {!Array.<!String>} the list of source files.
 */
CppComponent.prototype._sources = function _sources(target) {
  var sources = [path.join(this._path, "src", "**", "*.cpp")];
  if (target === "test") {
    sources.push(path.join(this._path, "tests", "**", "*.cpp"));
  }

  if (this._targets[target].exclude) {
    this._targets[target].exclude.forEach(function(exclude) {
      sources.push("!" + exclude);
    });
  }

  return sources;
};

/**
 * Lists the static libraries needed for this component.
 * @param {!Components} components Collection of components in the system.
 * @param {!String}     target     The target mode to compile for.
 * @returns {!Array.<!String>} the list of static library paths.
 */
CppComponent.prototype._staticLibraries = function _staticLibraries(
    components, target
) {
  var libs = [];
  var deps = components.resolve(this._name, target);

  deps.forEach(function(dep) {
    var dep_target = dep.target;
    dep = dep.instance;
    var should_check = (
        dep instanceof CppComponent &&
        dep._targets[dep_target].type === "lib"
    );
    if (should_check) {
      libs.push(path.join(
          "out", "dist", dep_target, dep._path, dep.name() + ".a"
      ));
    }
  });

  libs.reverse();
  return libs;
};

/**
 * Verifies the configuration.
 * @param {!Object} configuration The configuration to verify.
 */
CppComponent.prototype._verify = function _verify(configuration) {
  var exclude_message = (
      "The exclude attribute must be array of strings, if specified"
  );

  verify.notEmptyString(configuration.path, "Missing component path");
  verify.optionalArray(configuration.exclude, exclude_message);

  (configuration.exclude || []).forEach(function(exclude) {
    verify.notEmptyString(exclude, exclude_message);
  });
};

/**
 * Verifies a target configuration.
 * @param {!Object} target The target configuration to verify.
 */
CppComponent.prototype._verifyTarget = function _verifyTarget(target) {
  var exclude_message = (
      "The exclude attribute must be array of strings, if specified"
  );
  var include_message = (
      "The include attribute must be array of strings, if specified"
  );
  var libs_message = (
      "The libs attribute must be array of strings, if specified"
  );

  verify.optionalArray(target.exclude, exclude_message);
  verify.optionalArray(target.include, include_message);
  verify.optionalArray(target.libs,    libs_message);

  (target.exclude || []).forEach(function(exclude) {
    verify.notEmptyString(exclude, exclude_message);
  });
  (target.include || []).forEach(function(include) {
    verify.notEmptyString(include, include_message);
  });
  (target.libs || []).forEach(function(lib) {
    verify.notEmptyString(lib, libs_message);
  });

  if (typeof target.type !== "undefined") {
    verify.notEmptyString(target.type, "Type must be a valid string");
  }
};

//@override
CppComponent.prototype.getCleanPath = function getCleanPath(target) {
  var paths = [
    path.join("out", "build", target, this._path),
    path.join("out", "dist",  target, this._path)
  ];

  if (target === "analysis") {
    paths.push(path.join("out", "reports", this._path));
  }

  return paths;
};

//Override
CppComponent.prototype.handleAnalysis = function handleAnalysis(components) {
  var key  = "analysis\\." + this._name;
  var name = "analysis." + this._name;

  // Run linter.
  this._grunt.config("cpplint." + key, {
    options: {
      root: path.normalize(path.join(this._path, "include")),
      filter: [
        "-runtime/indentation_namespace"
      ]
    },
    src: [
      path.join(this._path, "include", "**", "*.h"),
      path.join(this._path, "src", "**", "*.cpp")
    ]
  });
  this._grunt.task.run("cpplint:" + name);

  // Stop here if test target does not exist.
  if (!this.hasTarget("test")) {
    return;
  }

  // Run static analysis.
  var include = this._includes(components, "test");
  this._grunt.config("cppcheck." + key, {
    exclude: ["3rd-parties", path.join(this._path, "tests")],
    include: include,
    save_to: path.join("out", "reports", this._path, "cppcheck.xml"),
    src: [
      path.join(this._path, "include", "**", "*.h"),
      path.join(this._path, "src", "**", "*.cpp")
    ]
  });
  this._grunt.task.run("cppcheck:" + name);

  // Run tests.
  this._grunt.config("shell." + key, {
    command: (
      path.join("out", "dist", "test", this._path, "run-tests") +
      " --gtest_output='xml:" +
      path.join("out", "reports", this._path, "test-results.xml") + "'"
    )
  });
  this._grunt.task.run("shell:" + name);

  // Run coverage.
  this._grunt.config("gcovr." + key, {
    exclude: ".*(3rd-parties|tests).*",
    gcovr:   GCOVR_PATH,
    objects: path.join("out", "build", "test", this._path, "src"),
    save_to: path.join("out", "reports", this._path, "coverage.xml")
  });
  this._grunt.task.run("gcovr:" + name);
};

//Override
CppComponent.prototype.handleTarget = function handleTarget(
    target, components
) {
  var key  = target + "\\." + this._name;
  var name = target + "." + this._name;

  this._compileCore(key, name, target, components);
  this._compileByType(key, name, target, components);

  if (target === "test") {
    this._compileGTest(key, name);
    this._compileBin(key, name, target, components, true);
  }
};
<|endoftext|>


<commit_before>var stream = require("stream");

module.exports = function() {
  var transform = new stream.Transform({objectMode: true});

  transform._transform = function(value, encoding, callback) {
    visit(value);
    transform.push("\n");
    callback();
  };

  function visit(value) {
    if (typeof value === "object") {
      if (!value) return void transform.push("null");
      if (Array.isArray(value)) {
        transform.push("[");
        var i = 0, n = value.length;
        if (n) visit(value[i]);
        while (++i < n) transform.push(","), visit(value[i]);
        transform.push("]");
      } else {
        transform.push("{");
        var separate = false;
        for (var key in value) {
          if (separate) transform.push(",");
          else separate = true;
          transform.push(JSON.stringify(key));
          transform.push(":");
          visit(value[key]);
        }
        transform.push("}");
      }
    } else {
      transform.push(JSON.stringify(value));
    }
  }

  return transform;
};
<commit_msg>Use EOL.<commit_after>var stream = require("stream"),
    eol = require("os").EOL;

module.exports = function() {
  var transform = new stream.Transform({objectMode: true});

  transform._transform = function(value, encoding, callback) {
    visit(value);
    transform.push(eol);
    callback();
  };

  function visit(value) {
    if (typeof value === "object") {
      if (!value) return void transform.push("null");
      if (Array.isArray(value)) {
        transform.push("[");
        var i = 0, n = value.length;
        if (n) visit(value[i]);
        while (++i < n) transform.push(","), visit(value[i]);
        transform.push("]");
      } else {
        transform.push("{");
        var separate = false;
        for (var key in value) {
          if (separate) transform.push(",");
          else separate = true;
          transform.push(JSON.stringify(key));
          transform.push(":");
          visit(value[key]);
        }
        transform.push("}");
      }
    } else {
      transform.push(JSON.stringify(value));
    }
  }

  return transform;
};
<|endoftext|>


<commit_before>'use strict'

const childProcess = require('child_process')
const isUrl = require('is-url')
const utils = require('./utils')

const MACOS_BROWSERS = {
  'chrome': 'google chrome',
  'firefox': 'firefox',
  'safari': 'safari'
}

const WINDOWS_BROWSERS = {
  'chrome': 'Chrome',
  'ie': 'iexplore',
  'firefox': 'firefox',
  'edge': 'microsoft-edge'
}

const INCOGNITOS = {
  'chrome': '--incognito',
  'firefox': '-private-window',
  'ie': '-private'
}

const open = (location, options) => {
  return new Promise((resolve, reject) => {
    if (typeof location !== 'string') {
      return reject(new Error('No location specified'))
    }

    let defaultBrowser = options.defaultBrowser
    let browser = options.browser || defaultBrowser

    let cmd
    let app = options.app
    let args = options.args || []
    let appArgs = options.appArgs || []
    let isAUrl = isUrl(location)
    let isToOpenInSafariInIncognito = false

    if (process.platform === 'darwin') {
      cmd = 'open'

      if (isAUrl) {
        if (!app && browser) {
          app = MACOS_BROWSERS[browser]
        }

        if (browser === 'safari' && options.incognito) {
          isToOpenInSafariInIncognito = true
        }

        if (options.incognito && browser && INCOGNITOS[browser]) {
          if (browser === 'chrome') {
            args.push('-n')
          }
          appArgs.push(INCOGNITOS[browser])
        }
      }

      if (app) {
        args.push('-a', app)
      }

      if (appArgs.length !== 0) {
        args.push('--args')
        args = args.concat(appArgs)
      }
    } else if (process.platform === 'win32') {
      cmd = 'cmd'
      args.push('/c', 'start', '""')
      location = location.replace(/&/g, '^&')

      if (isAUrl) {
        if (!app && browser) {
          app = WINDOWS_BROWSERS[browser]
        }

        if (options.incognito && browser) {
          appArgs.push(INCOGNITOS[browser])
        }
      }

      if (app) {
        let appForArgs = app

        if (browser === 'edge') {
          appForArgs = `${app}:${location}`
        }

        args.push(appForArgs)
      }

      if (appArgs.length !== 0) {
        args = args.concat(appArgs)
      }
    } else {
      reject(new Error(`The platform "${process.platform}" is not supported`))
    }

    if (browser !== 'edge') {
      args.push(location)
    }

    if (!isToOpenInSafariInIncognito) {
      if (!options.outputOnly) {
        childProcess.spawn(cmd, args)
      }

      resolve({
        cmd: cmd,
        args: args
      })
    } else {
      utils.openSafariIncognito(location).then(response => {
        resolve(response)
      }).catch(reason => {
        reject(reason)
      })
    }
  })
}

module.exports = (location, opts) => {
  return new Promise((resolve, reject) => {
    let options = opts || {}
    utils.getDefaultBrowser().then((defaultBrowser) => {
      options.defaultBrowser = defaultBrowser
      open(location, options).then((response) => {
        resolve(response)
      }).catch((reason) => {
        return reject(reason)
      })
    }).catch(() => {
      return reject(new Error('No default browser found'))
    })
  })
}
<commit_msg>fix spawn<commit_after>'use strict'

const childProcess = require('child_process')
const isUrl = require('is-url')
const utils = require('./utils')

const MACOS_BROWSERS = {
  'chrome': 'google chrome',
  'firefox': 'firefox',
  'safari': 'safari'
}

const WINDOWS_BROWSERS = {
  'chrome': 'Chrome',
  'ie': 'iexplore',
  'firefox': 'firefox',
  'edge': 'microsoft-edge'
}

const INCOGNITOS = {
  'chrome': '--incognito',
  'firefox': '-private-window',
  'ie': '-private'
}

const open = (location, options) => {
  return new Promise((resolve, reject) => {
    if (typeof location !== 'string') {
      return reject(new Error('No location specified'))
    }

    let defaultBrowser = options.defaultBrowser
    let browser = options.browser || defaultBrowser

    let cmd
    let app = options.app
    let args = options.args || []
    let appArgs = options.appArgs || []
    let isAUrl = isUrl(location)
    let isToOpenInSafariInIncognito = false

    if (process.platform === 'darwin') {
      cmd = 'open'

      if (isAUrl) {
        if (!app && browser) {
          app = MACOS_BROWSERS[browser]
        }

        if (browser === 'safari' && options.incognito) {
          isToOpenInSafariInIncognito = true
        }

        if (options.incognito && browser && INCOGNITOS[browser]) {
          if (browser === 'chrome') {
            args.push('-n')
          }
          appArgs.push(INCOGNITOS[browser])
        }
      }

      if (app) {
        args.push('-a', app)
      }

      if (appArgs.length !== 0) {
        args.push('--args')
        args = args.concat(appArgs)
      }
    } else if (process.platform === 'win32') {
      cmd = 'cmd'
      args.push('/c', 'start', '""')
      location = location.replace(/&/g, '^&')

      if (isAUrl) {
        if (!app && browser) {
          app = WINDOWS_BROWSERS[browser]
        }

        if (options.incognito && browser) {
          appArgs.push(INCOGNITOS[browser])
        }
      }

      if (app) {
        let appForArgs = app

        if (browser === 'edge') {
          appForArgs = `${app}:${location}`
        }

        args.push(appForArgs)
      }

      if (appArgs.length !== 0) {
        args = args.concat(appArgs)
      }
    } else {
      reject(new Error(`The platform "${process.platform}" is not supported`))
    }

    if (browser !== 'edge') {
      args.push(location)
    }

    if (!isToOpenInSafariInIncognito) {
      if (!options.outputOnly) {
        const child = childProcess.spawn(cmd, args, {
          detached: true,
          stdio: 'ignore'
        })
        child.unref()
      }

      resolve({
        cmd: cmd,
        args: args
      })
    } else {
      utils.openSafariIncognito(location).then(response => {
        resolve(response)
      }).catch(reason => {
        reject(reason)
      })
    }
  })
}

module.exports = (location, opts) => {
  return new Promise((resolve, reject) => {
    let options = opts || {}
    utils.getDefaultBrowser().then((defaultBrowser) => {
      options.defaultBrowser = defaultBrowser
      open(location, options).then((response) => {
        resolve(response)
      }).catch((reason) => {
        return reject(reason)
      })
    }).catch(() => {
      return reject(new Error('No default browser found'))
    })
  })
}
<|endoftext|>


<commit_before>/*global define, CKEDITOR */
/*jshint indent:4 */

define(["ckeditor"], function () {
    "use strict";

    //open a simpler link dialog
    CKEDITOR.on("dialogDefinition", function(ev) {
        var dialogName = ev.data.name;
        var dialogDefinition = ev.data.definition;

        if (dialogName === "link") {
            dialogDefinition.removeContents("target");
            dialogDefinition.removeContents("advanced");

            var infoTab = dialogDefinition.getContents("info");

            infoTab.remove("linkType");
            infoTab.remove("protocol");
        }
    });

    var config = {};

    config.customConfig = "";
    config.language = "pt_BR";
    config.height = "400px";
    config.allowedContent = "p b i br u s; a[!href]";
    config.entities = false;
    config.basicEntities = true;
    config.entities_greek = false;
    config.entities_latin = false;
    config.entities_additional = "";
    config.htmlEncodeOutput = false;
    config.removeButtons = "Anchor,Subscript,Superscript";

    config.toolbar = [
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', '-'] },
        { name: 'links', items: [ 'Link', 'Unlink'] }
    ];

    config.toolbarGroups = [
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
        { name: 'links' }
    ];

    return config;
});
<commit_msg>add the undo / redo button to the CKEditor config<commit_after>/*global define, CKEDITOR */
/*jshint indent:4 */

define(["ckeditor"], function () {
    "use strict";

    //open a simpler link dialog
    CKEDITOR.on("dialogDefinition", function(ev) {
        var dialogName = ev.data.name;
        var dialogDefinition = ev.data.definition;

        if (dialogName === "link") {
            dialogDefinition.removeContents("target");
            dialogDefinition.removeContents("advanced");

            var infoTab = dialogDefinition.getContents("info");

            infoTab.remove("linkType");
            infoTab.remove("protocol");
        }
    });

    var config = {};

    config.customConfig = "";
    config.language = "pt_BR";
    config.height = "400px";
    config.allowedContent = "p b i br u s; a[!href]";
    config.entities = false;
    config.basicEntities = true;
    config.entities_greek = false;
    config.entities_latin = false;
    config.entities_additional = "";
    config.htmlEncodeOutput = false;
    config.removeButtons = "Anchor,Subscript,Superscript";

    config.toolbar = [
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ], items: [ 'Bold', 'Italic', 'Underline', 'Strike', '-'] },
        { name: 'links', items: [ 'Link', 'Unlink'] },
        { name: 'clipboard', items : [ 'Undo','Redo' ] }
    ];

    config.toolbarGroups = [
        { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] },
        { name: 'links' }
    ];

    return config;
});
<|endoftext|>


<commit_before>/*global _, Kinetic, MAPJS, Image, setTimeout */
Kinetic.IdeaProxy = function (idea, container, stage, layer) {
	'use strict';
	var cached,
		cacheImage = function () {
			var x = -1, y = -1,
				width = idea.getWidth() + 20,
				height = idea.getHeight() + 20;
			idea.remove();
			idea.toImage({
				x: x,
				y: y,
				width: width,
				height: height,
				callback: function (img) {
					var image = new Kinetic.Image({
						x: x,
						y: y,
						width: width,
						height: height,
						image: img
					});
					container.add(image);
					cached = image;
					container.getLayer().draw();
				}
			});
		};

	container.attrs.x = idea.attrs.x;
	container.attrs.y = idea.attrs.y;
	idea.attrs.x = 0;
	idea.attrs.y = 0;
	container.add(idea);

	container.cacheImage = cacheImage;

	container.isVisible = function (offset) {
		return stage && stage.isRectVisible(new MAPJS.Rectangle(container.attrs.x, container.attrs.y, container.getWidth(), container.getHeight()), offset);
	};
	idea.isVisible = function (offset) {
		return stage && stage.isRectVisible(new MAPJS.Rectangle(container.attrs.x, container.attrs.y, container.getWidth(), container.getHeight()), offset);
	};
	container.transitionToAndDontStopCurrentTransitions = function (config) {
		var transition = new Kinetic.Transition(container, config),
			animation = new Kinetic.Animation();
		animation.func = transition._onEnterFrame.bind(transition);
		animation.node = container.getLayer();
		transition.onFinished = animation.stop.bind(animation);
		transition.start();
		animation.start();
	};
	_.each(['getHeight', 'getWidth'], function (fname) {
		container[fname] = function () {
			if (cacheImage && cacheImage[fname]) {
				return cacheImage[fname].apply(cacheImage, arguments);
			}
			return idea && idea[fname] && idea[fname].apply(idea, arguments);
		};
	});
	_.each(['setMMStyle', 'setIsSelected', 'setText', 'setIsDroppable'], function (fname) {
		container[fname] = function () {
			var result = idea && idea[fname] && idea[fname].apply(idea, arguments);
			return result;
		};
	});

	layer.add(container);
	container.transitionToAndDontStopCurrentTransitions({
		opacity: 1,
		duration: 0.4
	});
	setTimeout(container.cacheImage, 10000);
	return container;
};

<commit_msg>using images from the start<commit_after>/*global _, Kinetic, MAPJS, Image, setTimeout */
Kinetic.IdeaProxy = function (idea, container, stage, layer) {
	'use strict';
	var cached,
		cacheImage = function () {
			var x = -1, y = -1,
				width = idea.getWidth() + 20,
				height = idea.getHeight() + 20;
			idea.toImage({
				x: x,
				y: y,
				width: width,
				height: height,
				callback: function (img) {
					if (cached) {
						cached.setImage(img);
					} else {
						var image = new Kinetic.Image({
							x: x,
							y: y,
							width: width,
							height: height,
							image: img
						});
						container.add(image);
						cached = image;
						container.getLayer().draw();
					}
				}
			});
		};

	container.attrs.x = idea.attrs.x;
	container.attrs.y = idea.attrs.y;
	idea.attrs.x = 0;
	idea.attrs.y = 0;
	//container.add(idea);

	container.cacheImage = cacheImage;

	container.isVisible = function (offset) {
		return stage && stage.isRectVisible(new MAPJS.Rectangle(container.attrs.x, container.attrs.y, container.getWidth(), container.getHeight()), offset);
	};
	idea.isVisible = function (offset) {
		return stage && stage.isRectVisible(new MAPJS.Rectangle(container.attrs.x, container.attrs.y, container.getWidth(), container.getHeight()), offset);
	};
	idea.getLayer = function () {
		return layer;
	};
	container.transitionToAndDontStopCurrentTransitions = function (config) {
		var transition = new Kinetic.Transition(container, config),
			animation = new Kinetic.Animation();
		animation.func = transition._onEnterFrame.bind(transition);
		animation.node = container.getLayer();
		transition.onFinished = animation.stop.bind(animation);
		transition.start();
		animation.start();
	};
	_.each(['getHeight', 'getWidth'], function (fname) {
		container[fname] = function () {
			return idea && idea[fname] && idea[fname].apply(idea, arguments);
		};
	});
	_.each(['setMMStyle', 'setIsSelected', 'setText', 'setIsDroppable'], function (fname) {
		container[fname] = function () {
			var result = idea && idea[fname] && idea[fname].apply(idea, arguments);
			cacheImage();
			return result;
		};
	});

	layer.add(container);
	container.transitionToAndDontStopCurrentTransitions({
		opacity: 1,
		duration: 0.4
	});
	container.cacheImage();
	return container;
};

<|endoftext|>


<commit_before>// verbose-pancake server side

// imports
var express    = require('express');
var fs         = require('fs');
var dotenv     = require('dotenv');
var shortid    = require('shortid');
var bodyParser = require('body-parser')

// inits
var app     = express();
app.use(express.static(__dirname + '/static'));
app.use("/data", express.static(__dirname + '/data'));
var urlencodedParser = bodyParser.urlencoded({ extended: false })
dotenv.load();
var PORT    = process.env.PORT || 8080;
var DATADIR = __dirname + "/data/";

// Form handling
app.post('/submit', urlencodedParser, function (req, res) {
  // Creating a new Citation
  console.log("Creating new Citation");
  var id      = shortid.generate();
  var content = {
    "id"     : id,
    "author" : req.body.Author,
    "title"  : req.body.Title,
    "journal": req.body.Journal,
    "volume" : req.body.Volume,
    "year"   : req.body.Year,
    "pages"  : req.body.Pages
  };

  filePath = DATADIR + id;

  fs.writeFile(filePath, JSON.stringify(content), function(err) {
    if(err) {
      return console.log(err);
    }
    res.sendStatus(200);
  });
});

// Data listing
app.get('/list', function (req, res) {
  var filelist = [];
  fs.readdir(DATADIR, function (err, files) {
    if (err) {
      return console.log(err);
    }
    files.forEach(function (filename) {
      if(! /^\..*/.test(filename)) {
        filelist.push(filename);
      }
    });
    res.send(JSON.stringify(filelist));
  });
});

//BibTex Output
app.get('/bibtex-list', function(req, res) {
  fs.readdir(DATADIR, function (err, files) {
    if (err) {
      return console.log(err);
    }
    var arg = "";
    files.forEach(function (filename) {
        arg += (filename + ",");
    });
    arg = arg.substring(0, arg.length-1);
    var spawn = require('child_process').spawn;
    var process = spawn('python', ["./bibtexify.py",arg]);
    console.log("BibTeX generated from list to bibtex-list.txt");
    process.stdout.on('data', function(data) {
      res.send(data);
    });
  });
});

// Start server!
app.listen(PORT, function () {
  console.log('Running verbose pancake on port ' + PORT);
});
<commit_msg>Checkout server.js from referencetypes-serverside<commit_after>// verbose-pancake server side

// imports
var express    = require('express');
var fs         = require('fs');
var dotenv     = require('dotenv');
var shortid    = require('shortid');
var bodyParser = require('body-parser')

// inits
var app     = express();
app.use(express.static(__dirname + '/static'));
app.use("/data", express.static(__dirname + '/data'));
var urlencodedParser = bodyParser.urlencoded({ extended: false })
dotenv.load();
var PORT    = process.env.PORT || 8080;
var DATADIR = __dirname + "/data/";

// Form handling
app.post('/submit', urlencodedParser, function (req, res) {
  // Creating a new Citation
  console.log("Creating new Citation");
  var id      = shortid.generate();
  var format  = req.body.Format;
  var content;

  if (format == "article") {
    content = {
      "id"     : id,
      "format" : "article",
      "author" : req.body.Author,
      "title"  : req.body.Title,
      "journal": req.body.Journal,
      "volume" : req.body.Volume,
      "year"   : req.body.Year,
      "pages"  : req.body.Pages
    };
  }

  else if (format == "book") {
    content = {
      "id"        : id,
      "format"    : "book",
      "author"    : req.body.Author,
      "title"     : req.body.Title,
      "publisher" : req.body.Publisher,
      "year"      : req.body.Year,
    };
  }

  else if (format == "inproceedings") {
    content = {
      "id"        : id,
      "format"    : "inproceedings",
      "author"    : req.body.Author,
      "title"     : req.body.Title,
      "booktitle" : req.body.Booktitle,
      "year"      : req.body.Year,
    };
  }

  filePath = DATADIR + id;

  fs.writeFile(filePath, JSON.stringify(content), function(err) {
    if(err) {
      return console.log(err);
    }
    res.sendStatus(200);
  });
});

// Data listing
app.get('/list', function (req, res) {
  var filelist = [];
  fs.readdir(DATADIR, function (err, files) {
    if (err) {
      return console.log(err);
    }
    files.forEach(function (filename) {
      if(! /^\..*/.test(filename)) {
        filelist.push(filename);
      }
    });
    res.send(JSON.stringify(filelist));
  });
});

//BibTex Output
app.get('/bibtex-list', function(req, res) {
  fs.readdir(DATADIR, function (err, files) {
    if (err) {
      return console.log(err);
    }
    var arg = "";
    files.forEach(function (filename) {
        arg += (filename + ",");
    });
    arg = arg.substring(0, arg.length-1);
    var spawn = require('child_process').spawn;
    var process = spawn('python', ["./bibtexify.py",arg]);
    console.log("BibTeX generated from list to bibtex-list.txt");
    process.stdout.on('data', function(data) {
      res.send(data);
    });
  });
});

// Start server!
app.listen(PORT, function () {
  console.log('Running verbose pancake on port ' + PORT);
});
<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const translate = require('google-translate-api')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('context')

var slapp = Slapp({
    convo_store: ConvoStore(),
    context: Context(),
})

var HELP_TEXT = `
Oto lista rzeczy, które potrafię:
\`help\` - wyświetla tą wiadomość.
\`tusklate\` - tłumaczę Twoje zdanie na mój zaawansowany angielski.
\`pics\` - pokażę Ci ciekawy obrazek.
`

slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

var app = slapp.attachToExpress(express())

app.get('/', (req, res) => {
    res.send('Hello! I\'m Tusklator!')
})

app.listen(process.env.PORT, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${process.env.PORT}`)
})<commit_msg>fix beep boop context import<commit_after>'use strict'

const express = require('express')
const translate = require('google-translate-api')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

var slapp = Slapp({
    convo_store: ConvoStore(),
    context: Context(),
})

var HELP_TEXT = `
Oto lista rzeczy, które potrafię:
\`help\` - wyświetla tą wiadomość.
\`tusklate\` - tłumaczę Twoje zdanie na mój zaawansowany angielski.
\`pics\` - pokażę Ci ciekawy obrazek.
`

slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

var app = slapp.attachToExpress(express())

app.get('/', (req, res) => {
    res.send('Hello! I\'m Tusklator!')
})

app.listen(process.env.PORT, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${process.env.PORT}`)
})<|endoftext|>


<commit_before>import OS from 'os'
import { fork } from 'child_process'
import chalk from 'chalk'
import { progress, time, timeEnd } from '../utils'
import exporter from './exporter'

const cores = Math.max(OS.cpus().length, 1)

export default (async function buildHTML({
  config: oldConfig,
  siteData,
  clientStats,
  incremental,
}) {
  const { routes, ...config } = oldConfig
  time(chalk.green('=> [\u2713] HTML Exported'))

  // in case of an absolute path for DIST we must tell node to load the modules from our project root
  if (!config.paths.DIST.startsWith(config.paths.ROOT)) {
    process.env.NODE_PATH = config.paths.NODE_MODULES
    require('module').Module._initPaths()
  }

  // Single threaded export
  if (config.maxThreads <= 1) {
    console.log('=> Exporting HTML...')
    await exporter({
      config,
      routes,
      siteData,
      clientStats,
      incremental,
    })
  } else {
    // Multi-threaded export
    const threads = Math.min(cores, config.maxThreads)
    const htmlProgress = progress(routes.length)
    console.log(`=> Exporting HTML across ${cores} threads...`)

    const exporters = []
    for (let i = 0; i < threads; i++) {
      exporters.push(
        fork(require.resolve('./exporter.threaded'), [], {
          env: {
            ...process.env,
            REACT_STATIC_SLAVE: 'true',
          },
          stdio: 'inherit',
        })
      )
    }

    const exporterRoutes = exporters.map(() => [])

    routes.forEach((route, i) => {
      exporterRoutes[i % exporterRoutes.length].push(route)
    })

    await Promise.all(
      exporters.map((exporter, i) => {
        const routes = exporterRoutes[i]
        return new Promise((resolve, reject) => {
          exporter.send({
            config,
            routes,
            siteData,
            clientStats,
            incremental,
          })
          exporter.on('message', ({ type, payload }) => {
            if (type === 'error') {
              reject(payload)
            }
            if (type === 'log') {
              console.log(...payload)
            }
            if (type === 'tick') {
              htmlProgress.tick()
            }
            if (type === 'done') {
              resolve()
            }
          })
        })
      })
    )
  }

  timeEnd(chalk.green('=> [\u2713] HTML Exported'))
})
<commit_msg>Log threads not cores from export (#1020)<commit_after>import OS from 'os'
import { fork } from 'child_process'
import chalk from 'chalk'
import { progress, time, timeEnd } from '../utils'
import exporter from './exporter'

const cores = Math.max(OS.cpus().length, 1)

export default (async function buildHTML({
  config: oldConfig,
  siteData,
  clientStats,
  incremental,
}) {
  const { routes, ...config } = oldConfig
  time(chalk.green('=> [\u2713] HTML Exported'))

  // in case of an absolute path for DIST we must tell node to load the modules from our project root
  if (!config.paths.DIST.startsWith(config.paths.ROOT)) {
    process.env.NODE_PATH = config.paths.NODE_MODULES
    require('module').Module._initPaths()
  }

  // Single threaded export
  if (config.maxThreads <= 1) {
    console.log('=> Exporting HTML...')
    await exporter({
      config,
      routes,
      siteData,
      clientStats,
      incremental,
    })
  } else {
    // Multi-threaded export
    const threads = Math.min(cores, config.maxThreads)
    const htmlProgress = progress(routes.length)
    console.log(`=> Exporting HTML across ${threads} threads...`)

    const exporters = []
    for (let i = 0; i < threads; i++) {
      exporters.push(
        fork(require.resolve('./exporter.threaded'), [], {
          env: {
            ...process.env,
            REACT_STATIC_SLAVE: 'true',
          },
          stdio: 'inherit',
        })
      )
    }

    const exporterRoutes = exporters.map(() => [])

    routes.forEach((route, i) => {
      exporterRoutes[i % exporterRoutes.length].push(route)
    })

    await Promise.all(
      exporters.map((exporter, i) => {
        const routes = exporterRoutes[i]
        return new Promise((resolve, reject) => {
          exporter.send({
            config,
            routes,
            siteData,
            clientStats,
            incremental,
          })
          exporter.on('message', ({ type, payload }) => {
            if (type === 'error') {
              reject(payload)
            }
            if (type === 'log') {
              console.log(...payload)
            }
            if (type === 'tick') {
              htmlProgress.tick()
            }
            if (type === 'done') {
              resolve()
            }
          })
        })
      })
    )
  }

  timeEnd(chalk.green('=> [\u2713] HTML Exported'))
})
<|endoftext|>