<commit_before>/*
 * Version 5.7 Idempotent DB migration script goes here.
 * Please try to avoid using migration script and instead make special treatment in the code!
 */

// BRCD-1002- Add weight property type to units of measure
var lastConfig = db.config.find().sort({_id: -1}).limit(1).pretty()[0];
if (lastConfig.property_types && lastConfig.property_types.indexOf('weight') === -1) {
	delete lastConfig['_id'];
	lastConfig.property_types.push(
			{
				"system": true,
				"type": "weight",
				"uom": [{"unit": 1, "name": "mg", "label": "mg"}, {"unit": 1000, "name": "g", "label": "g"}, {"unit": 1000000, "name": "kg", "label": "kg"}, {"unit": 1000000000, "name": "ton", "label": "ton"}],
				"invoice_uom": "kg"
			});
	db.config.insert(lastConfig);
}<commit_msg>BRCD-1002 - migration script fixed.<commit_after>/*
 * Version 5.7 Idempotent DB migration script goes here.
 * Please try to avoid using migration script and instead make special treatment in the code!
 */

// BRCD-1002- Add weight property type to units of measure
var lastConfig = db.config.find().sort({_id: -1}).limit(1).pretty()[0];
if (lastConfig.property_types && lastConfig.property_types.filter(element => element.type === 'weight').length == 0) {
	delete lastConfig['_id'];
	lastConfig.property_types.push(
			{
				"system": true,
				"type": "weight",
				"uom": [{"unit": 1, "name": "mg", "label": "mg"}, {"unit": 1000, "name": "g", "label": "g"}, {"unit": 1000000, "name": "kg", "label": "kg"}, {"unit": 1000000000, "name": "ton", "label": "ton"}],
				"invoice_uom": "kg"
			});
	db.config.insert(lastConfig);
}<|endoftext|>


<commit_before>'use strict';

var restify = require('restify'),
  Q = require('q'),

  utils = require('../../common/utils'),
  UpdateSubscription = require('./updateSubscriptionHandler'),
  Subscription = require('../../database/subscription');

/**
 * Parses the provided `torrentSort` and returns a valid torrent sorting method.
 *
 * @param {String} torrentSort - The provided torrent sort string.
 *
 * @returns {String} Valid torrent sorting method.
 */
function getTorrentSort(torrentSort) {
  const DEFAULT_SORT = 'largest',
        validSortsLowercase = [ 'largest', 'smallest', 'newest', 'oldest', 'mostseeded' ];

  var sort = (torrentSort || DEFAULT_SORT).toString().toLowerCase();

  return validSortsLowercase.indexOf(sort) > -1 ? sort : DEFAULT_SORT;
}

/**
 * Recursively looks for new episodes of the same season until no torrents are found for a
 * particular episode.
 *
 * @param {Subscription} subscription - Subscription to which the episodes (would) belong.
 * @param {Number} season - Season of the episode to try and find.
 * @param {Number} episode - Episode of the episode to try and find.
 * @param {Array} torrents - Already found torrents.
 * @param {String} torrentSort - Torrent sorting method.
 * @param {Number} maxTorrentsPerEpisode - Maximum number of torrents that should be retrieved
 *                                         for a single episode.
 *
 * @returns {Promise} Promise which resolves to the array of all found torrents.
 */
function checkForMultipleEpisodes(subscription, season, episode,
    torrents, torrentSort, maxTorrentsPerEpisode) {
  return this.torrentSiteManager.findTorrents(subscription.name + ' '
      + utils.formatEpisodeNumber(season, episode) + ' ' + subscription.searchParameters,
      season, episode, torrentSort, maxTorrentsPerEpisode)
    .then(function (newTorrents) {
      if (newTorrents && newTorrents.length > 0) {
        // we found torrents, add to list
        torrents = torrents.concat(newTorrents);

        // look for next episode...
        return checkForMultipleEpisodes(subscription, season, episode + 1,
          torrents, torrentSort, maxTorrentsPerEpisode);
      }

      // couldn't find the episode, return the torrents we already have
      return torrents;
    });
}

/**
 * Looks for updates of a subscription, both new episodes of the same season, and new episodes
 * of a new season.
 *
 * @param {Subscription} subscription - Subscription to which the episodes (would) belong.
 * @param {String} torrentSort - Torrent sorting method.
 * @param {Number} maxTorrentsPerEpisode - Maximum number of torrents that should be retrieved
 *                                         for a single episode.
 * @param {Bunyan.Log} log - Optional. Logger instance.
 *
 * @returns {Promise} Promise which resolves to the array of all found torrents.
 */
function checkSubscriptionForUpdate(subscription, torrentSort, maxTorrentsPerEpisode, log) {
  log &&
    log.debug('Checking subscription "%s" for new episodes of same season...', subscription.name);

  // check for new episode of same season
  return checkForMultipleEpisodes(subscription, subscription.lastSeason,
      subscription.lastEpisode + 1, [], torrentSort, maxTorrentsPerEpisode)
    .then(function (newEpisodes) {
      // we just finished checking for new episodes
      subscription.updateLastUpdateCheckTime();

      log &&
        log.debug('Checking subscription "%s" for episodes of new season...', subscription.name);
      return checkForMultipleEpisodes(subscription, subscription.lastSeason + 1, 1,
          [], torrentSort, maxTorrentsPerEpisode)
        .then(function (episodes) {
          // we just finished checking for new episodes
          subscription.updateLastUpdateCheckTime();

          // merge episodes from current and new season
          newEpisodes = newEpisodes.concat(episodes);

          return newEpisodes;
        });
    });
}

/**
 * Handles requests to PUT /subscriptions/:subscriptionName/find.
 */
function checkSubscriptionForUpdates(req, res, next) {
  var body = typeof req.body === "string" ? JSON.parse(req.body) : req.body,
    subName = decodeURIComponent(req.params[0]),
    torrentSort = getTorrentSort(body ? body.torrentSort : req.params.torrentSort),
    maxTorrentsPerEpisode = parseInt(body
        ? body.maxTorrentsPerEpisode
        : req.params.maxTorrentsPerEpisode, 10) || 1,
    startDownload = req.params.startDownload === true || req.params.startDownload === 'true';

  Subscription.findSubscriptionByName(subName)
    .then(subscription => subscription
        ? subscription
        : next(new restify.BadRequestError("No subscription with name '" + subName + "'.")))
    .then(function (subscription) {
      return checkSubscriptionForUpdate(subscription, torrentSort, maxTorrentsPerEpisode, req.log)
        .then(function (data) {
          if (startDownload) {
            data.forEach(function (torrent) {
              UpdateSubscription.downloadTorrent(subscription,
                  torrent.season, torrent.episode, torrent.link, req.log);
            });
          }

        utils.sendOkResponse('Found ' +
            (startDownload && data.length > 0 ? 'and started download of ' : '') +
            data.length + ' new torrents', data, res, next, 'http://' + req.headers.host + req.url);
        });
    })
    .fail(() => next(
        new restify.InternalServerError('All known torrent sites appear to be unavailable.')));
}

/**
 * Handles requests to PUT /subscriptions/find.
 */
function checkAllSubscriptionsForUpdates(req, res, next) {
  var body = typeof req.body === "string" ? JSON.parse(req.body) : req.body,
    result,
    updateCount = 0,
    torrentSort = getTorrentSort(body ? body.torrentSort : req.params.torrentSort),
    maxTorrentsPerEpisode = parseInt(body
        ? body.maxTorrentsPerEpisode
        : req.params.maxTorrentsPerEpisode, 10) || 1,
    startDownload = req.params.startDownload === true || req.params.startDownload === 'true';

  // retrieve all subscriptions
  Subscription.findAllSubscriptions()
    // continue when updates are found for all subscriptions
    .then(subscriptions => Q.all(subscriptions.map(function (subscription) {
      return checkSubscriptionForUpdate(subscription, torrentSort, maxTorrentsPerEpisode, req.log)
        .then(function (data) {
          // adding a reference to the subscription for starting the torrent a bit futher down...
          data.subscription = subscription;
          return data;
        });
    })))
    .then(function (data) {
      // prepare result
      result = data.filter(function (entry) { return entry.length > 0; });
      result.forEach(function (torrents) {
        updateCount += torrents.length;
      });

      // remove the subscription property from each result entry
      // but only after starting the download - if requested
      result.forEach(function (entry) {
        if (startDownload) {
          entry.forEach(function (torrent) {
            UpdateSubscription.downloadTorrent(entry.subscription,
                torrent.season, torrent.episode, torrent.link, req.log);
          });
        }
        // we don't need the subscription reference anymore
        delete entry.subscription;
      });

      // done
      utils.sendOkResponse('Checked ' + data.length + ' subscriptions for updates and found ' +
          updateCount + ' new torrents' +
          (startDownload && updateCount > 0 ? ' which were downloaded' : ''),
          result, res, next, 'http://' + req.headers.host + req.url);
    })
    .fail(() => next(
          new restify.InternalServerError('All known torrent sites appear to be unavailable.')));
}

/**
 * Creates an instance of FindSubscriptionUpdatesHandler.
 *
 * @constructor
 *
 * @param {TorrentSiteManager} torrentSiteManager - TorrentSiteManager instance.
 * @param {Bunyan.Log} log - Logger instance.
 */
function FindSubscriptionUpdatesHandler(torrentSiteManager, log) {
  this.torrentSiteManager = torrentSiteManager;
  this.log = log;
  this.checkAllSubscriptionsForUpdates = checkAllSubscriptionsForUpdates;
  this.checkSubscriptionForUpdates = checkSubscriptionForUpdates;

  this.log.info('FindSubscriptionUpdatesHandler created');
}

module.exports = FindSubscriptionUpdatesHandler;

<commit_msg>Fix FSUH functions related to function context<commit_after>'use strict';

var restify = require('restify'),
  Q = require('q'),

  utils = require('../../common/utils'),
  UpdateSubscription = require('./updateSubscriptionHandler'),
  Subscription = require('../../database/subscription');

/**
 * Parses the provided `torrentSort` and returns a valid torrent sorting method.
 *
 * @param {String} torrentSort - The provided torrent sort string.
 *
 * @returns {String} Valid torrent sorting method.
 */
function getTorrentSort(torrentSort) {
  const DEFAULT_SORT = 'largest',
        validSortsLowercase = [ 'largest', 'smallest', 'newest', 'oldest', 'mostseeded' ];

  var sort = (torrentSort || DEFAULT_SORT).toString().toLowerCase();

  return validSortsLowercase.indexOf(sort) > -1 ? sort : DEFAULT_SORT;
}

/**
 * Handles requests to PUT /subscriptions/:subscriptionName/find.
 */
function checkSubscriptionForUpdates(req, res, next) {
  var body = typeof req.body === "string" ? JSON.parse(req.body) : req.body,
    subName = decodeURIComponent(req.params[0]),
    torrentSort = getTorrentSort(body ? body.torrentSort : req.params.torrentSort),
    maxTorrentsPerEpisode = parseInt(body
        ? body.maxTorrentsPerEpisode
        : req.params.maxTorrentsPerEpisode, 10) || 1,
    startDownload = req.params.startDownload === true || req.params.startDownload === 'true',

    // jshint validthis: true
    that = this;

  Subscription.findSubscriptionByName(subName)
    .then(subscription => subscription
        ? subscription
        : next(new restify.BadRequestError("No subscription with name '" + subName + "'.")))
    .then(function (subscription) {
      return that.checkSubscriptionForUpdate(subscription,
        torrentSort, maxTorrentsPerEpisode, req.log)
        .then(function (data) {
          if (startDownload) {
            data.forEach(function (torrent) {
              UpdateSubscription.downloadTorrent(subscription,
                  torrent.season, torrent.episode, torrent.link, req.log);
            });
          }

        utils.sendOkResponse('Found ' +
            (startDownload && data.length > 0 ? 'and started download of ' : '') +
            data.length + ' new torrents', data, res, next, 'http://' + req.headers.host + req.url);
        });
    })
    .fail(() => next(
        new restify.InternalServerError('All known torrent sites appear to be unavailable.')));
}

/**
 * Handles requests to PUT /subscriptions/find.
 */
function checkAllSubscriptionsForUpdates(req, res, next) {
  var body = typeof req.body === "string" ? JSON.parse(req.body) : req.body,
    result,
    updateCount = 0,
    torrentSort = getTorrentSort(body ? body.torrentSort : req.params.torrentSort),
    maxTorrentsPerEpisode = parseInt(body
        ? body.maxTorrentsPerEpisode
        : req.params.maxTorrentsPerEpisode, 10) || 1,
    startDownload = req.params.startDownload === true || req.params.startDownload === 'true',

    // jshint validthis: true
    that = this;

  // retrieve all subscriptions
  Subscription.findAllSubscriptions()
    // continue when updates are found for all subscriptions
    .then(subscriptions => Q.all(subscriptions.map(function (subscription) {
      return that.checkSubscriptionForUpdate(subscription, torrentSort,
        maxTorrentsPerEpisode, req.log)
        .then(function (data) {
          // adding a reference to the subscription for starting the torrent a bit futher down...
          data.subscription = subscription;
          return data;
        });
    })))
    .then(function (data) {
      // prepare result
      result = data.filter(function (entry) { return entry.length > 0; });
      result.forEach(function (torrents) {
        updateCount += torrents.length;
      });

      // remove the subscription property from each result entry
      // but only after starting the download - if requested
      result.forEach(function (entry) {
        if (startDownload) {
          entry.forEach(function (torrent) {
            UpdateSubscription.downloadTorrent(entry.subscription,
                torrent.season, torrent.episode, torrent.link, req.log);
          });
        }
        // we don't need the subscription reference anymore
        delete entry.subscription;
      });

      // done
      utils.sendOkResponse('Checked ' + data.length + ' subscriptions for updates and found ' +
          updateCount + ' new torrents' +
          (startDownload && updateCount > 0 ? ' which were downloaded' : ''),
          result, res, next, 'http://' + req.headers.host + req.url);
    })
    .fail(() => next(
          new restify.InternalServerError('All known torrent sites appear to be unavailable.')));
}

/**
 * Creates an instance of FindSubscriptionUpdatesHandler.
 *
 * @constructor
 *
 * @param {TorrentSiteManager} torrentSiteManager - TorrentSiteManager instance.
 * @param {Bunyan.Log} log - Logger instance.
 */
function FindSubscriptionUpdatesHandler(torrentSiteManager, log) {
  this.torrentSiteManager = torrentSiteManager;
  this.log = log;
  this.checkAllSubscriptionsForUpdates = checkAllSubscriptionsForUpdates;
  this.checkSubscriptionForUpdates = checkSubscriptionForUpdates;

  this.log.info('FindSubscriptionUpdatesHandler created');
}

/**
 * Recursively looks for new episodes of the same season until no torrents are found for a
 * particular episode.
 *
 * @param {Subscription} subscription - Subscription to which the episodes (would) belong.
 * @param {Number} season - Season of the episode to try and find.
 * @param {Number} episode - Episode of the episode to try and find.
 * @param {Array} torrents - Already found torrents.
 * @param {String} torrentSort - Torrent sorting method.
 * @param {Number} maxTorrentsPerEpisode - Maximum number of torrents that should be retrieved
 *                                         for a single episode.
 *
 * @returns {Promise} Promise which resolves to the array of all found torrents.
 */
FindSubscriptionUpdatesHandler.prototype.checkForMultipleEpisodes = function (subscription,
  season, episode, torrents, torrentSort, maxTorrentsPerEpisode) {
  var that = this;

  return this.torrentSiteManager.findTorrents(subscription.name + ' '
      + utils.formatEpisodeNumber(season, episode) + ' ' + subscription.searchParameters,
      season, episode, torrentSort, maxTorrentsPerEpisode)
    .then(function (newTorrents) {
      if (newTorrents && newTorrents.length > 0) {
        // we found torrents, add to list
        torrents = torrents.concat(newTorrents);

        // look for next episode...
        return that.checkForMultipleEpisodes(subscription, season, episode + 1,
          torrents, torrentSort, maxTorrentsPerEpisode);
      }

      // couldn't find the episode, return the torrents we already have
      return torrents;
    });
};

/**
 * Looks for updates of a subscription, both new episodes of the same season, and new episodes
 * of a new season.
 *
 * @param {Subscription} subscription - Subscription to which the episodes (would) belong.
 * @param {String} torrentSort - Torrent sorting method.
 * @param {Number} maxTorrentsPerEpisode - Maximum number of torrents that should be retrieved
 *                                         for a single episode.
 * @param {Bunyan.Log} log - Optional. Logger instance.
 *
 * @returns {Promise} Promise which resolves to the array of all found torrents.
 */
FindSubscriptionUpdatesHandler.prototype.checkSubscriptionForUpdate = function (subscription,
  torrentSort, maxTorrentsPerEpisode, log) {
  var that = this;

  log &&
    log.debug('Checking subscription "%s" for new episodes of same season...', subscription.name);

  // check for new episode of same season
  return this.checkForMultipleEpisodes(subscription, subscription.lastSeason,
      subscription.lastEpisode + 1, [], torrentSort, maxTorrentsPerEpisode)
    .then(function (newEpisodes) {
      // we just finished checking for new episodes
      subscription.updateLastUpdateCheckTime();

      log &&
        log.debug('Checking subscription "%s" for episodes of new season...', subscription.name);
      return that.checkForMultipleEpisodes(subscription, subscription.lastSeason + 1, 1,
          [], torrentSort, maxTorrentsPerEpisode)
        .then(function (episodes) {
          // we just finished checking for new episodes
          subscription.updateLastUpdateCheckTime();

          // merge episodes from current and new season
          newEpisodes = newEpisodes.concat(episodes);

          return newEpisodes;
        });
    });
};

module.exports = FindSubscriptionUpdatesHandler;

<|endoftext|>


<commit_before>import React, {Component} from "react"
import Codemirror from 'react-codemirror'
import {html as html_beautify} from 'js-beautify'
import Modal from 'react-modal'
require('codemirror/mode/htmlmixed/htmlmixed');

export default class CodeMirror extends Component {
    constructor(props) {
        super(props);
        this.beautifyOptions = {
            "wrap_line_length": 140
        };
        if (this.props.node) {
            this.state = {
                sourceEditorActive: false
            };
        } else {
            this.state = {}
        }
        this.code = this.props.data && this.props.data.html || this.props.html;
    }

    updateCode(newCode) {
        this.code = newCode
    }

    onSave() {
        this.props.updatePiece && this.props.updatePiece(this.props.id, {data: {html: this.code}})
        this.props.savePiece && this.props.savePiece(this.props.id)
        this.setState({sourceEditorActive: false})
    }

    onClose() {
        this.props.node ? this.setState({sourceEditorActive: false}) : (this.props.onClose && this.props.onClose())
    }

    render() {
        var options = {
            lineNumbers: true,
            mode: 'htmlmixed'
        };
        var codemirror = null;
        if (this.props.hasOwnProperty('editorActive') && !this.props.editorActive) {
            codemirror =
                <this.props.wrapper className={this.props.className}
                    dangerouslySetInnerHTML={{__html: (this.props.data && this.props.data.html) || this.props.html}}/>
        }
        else if (!this.state.sourceEditorActive && this.props.node) {
            codemirror =
                <this.props.wrapper className={this.props.className} style={this.props.style} dangerouslySetInnerHTML={{__html: this.props.data.html}}
                                    onClick={e=> {
                                        e.preventDefault();
                                        this.setState({sourceEditorActive: true})
                                    }}/>;
        } else {
            codemirror =
                <this.props.wrapper className={this.props.className}>
                    {this.state.sourceEditorActive &&

}
                    <Modal contentLabel="Edit source" isOpen={true} overlayClassName="r_modal-overlay r_visible"
                           className="r_modal-content"
                           onRequestClose={this.onClose.bind(this)}>
                        <Codemirror
                            value={html_beautify(this.props.node ? this.props.data.html : this.props.html, this.beautifyOptions)}
                            onChange={this.updateCode.bind(this)} options={options}/>

Cancel

this.props.node ? this.onSave() : (this.props.onSave && this.props.onSave(this.code))}>
                                Save

                    </Modal>
                </this.props.wrapper>

        }

        return codemirror
    }
}

/**
 * Specify component should be rendered inside target node and capture all inside html
 * @type {string}
 */
CodeMirror.__renderType = "INSIDE";
<commit_msg>Update<commit_after>import React, {Component} from "react"
import Codemirror from 'react-codemirror'
import {html as html_beautify} from 'js-beautify'
import Modal from 'react-modal'
require('codemirror/mode/htmlmixed/htmlmixed');

export default class CodeMirror extends Component {
    constructor(props) {
        super(props);
        this.beautifyOptions = {
            "wrap_line_length": 140
        };
        if (this.props.node) {
            this.state = {
                sourceEditorActive: false
            };
        } else {
            this.state = {}
        }
        this.code = this.props.data && this.props.data.html || this.props.html;
    }

    componentWillUnmount(){
        console.log(`Code mirror ${this.props.id} unmounted`);
    }

    updateCode(newCode) {
        this.code = newCode
    }

    onSave() {
        this.props.updatePiece && this.props.updatePiece(this.props.id, {data: {html: this.code}})
        this.props.savePiece && this.props.savePiece(this.props.id)
        this.setState({sourceEditorActive: false})
    }

    onClose() {
        this.props.node ? this.setState({sourceEditorActive: false}) : (this.props.onClose && this.props.onClose())
    }

    render() {
        var options = {
            lineNumbers: true,
            mode: 'htmlmixed'
        };
        var codemirror = null;
        if (this.props.hasOwnProperty('editorActive') && !this.props.editorActive) {
            codemirror =
                <this.props.wrapper className={this.props.className}
                    dangerouslySetInnerHTML={{__html: (this.props.data && this.props.data.html) || this.props.html}}/>
        }
        else if (!this.state.sourceEditorActive && this.props.node) {
            codemirror =
                <this.props.wrapper className={this.props.className} style={this.props.style} dangerouslySetInnerHTML={{__html: this.props.data.html}}
                                    onClick={e=> {
                                        e.preventDefault();
                                        this.setState({sourceEditorActive: true})
                                    }}/>;
        } else {
            codemirror =
                <this.props.wrapper className={this.props.className}>
                    {this.state.sourceEditorActive &&

}
                    <Modal contentLabel="Edit source" isOpen={true} overlayClassName="r_modal-overlay r_visible"
                           className="r_modal-content"
                           onRequestClose={this.onClose.bind(this)}>
                        <Codemirror
                            value={html_beautify(this.props.node ? this.props.data.html : this.props.html, this.beautifyOptions)}
                            onChange={this.updateCode.bind(this)} options={options}/>

Cancel

this.props.node ? this.onSave() : (this.props.onSave && this.props.onSave(this.code))}>
                                Save

                    </Modal>
                </this.props.wrapper>

        }

        return codemirror
    }
}

/**
 * Specify component should be rendered inside target node and capture all inside html
 * @type {string}
 */
CodeMirror.__renderType = "INSIDE";
CodeMirror.__name = "Source";
<|endoftext|>


<commit_before>/**
 * Faster DOM manipulation
 * The most basic operations, but much faster than jquery. (mostly)
 * @author Vadim Kr.
 */
(function () {
    function FasterDom(s) {
        var z = 'getElement', g = 'Name', a = {'#': 'ById', '.': 'sByClass' + g, '@': 'sBy' + g, '=': 'sByTag' + g}[s[0]] || false,
            b = s.slice(1), u = (a ? document[z + a](b) : document.querySelectorAll(b));
        this.element = (this.checkIf(u, "NodeList")) ? Array.prototype.slice.call(u) : u;
    }

    FasterDom.prototype = {
        constructor: FasterDom,
        attr: function (name, value) {
            if (this.checkIf(name, 'String') && typeof value === "undefined") {
                return this.element.getAttribute(name);
            }
            var that = this;
            this.each(function (element) {
                that.set(element, name, value);
            });
            return this;
        }, set: function (element, name, value) {
            if (this.checkIf(name, "String")) {
                element.setAttribute(name, value);
            } else if (this.checkIf(name, "Object")) {
                for (var property in name) {
                    element.setAttribute(property, name[property]);
                }
            }
        },
        html: function (html) {
            if (typeof html === "undefined") {
                return this.element.innerHTML;
            }
            this.each(function (element) {
                element.innerHTML = html;
            });
            return this;
        },
        css: function (obj) {
            if (typeof obj === "undefined") {
                return this.element.style;
            }
            this.each(function (element) {
                for (var key in obj) {
                    element.style[key] = obj[key];
                }
            });
            return this;
        },
        hide: function () {
            this.each(function (element) {
                element.style.display = 'none';
            });
            return this;
        },
        show: function () {
            this.each(function (element) {
                element.style.display = 'block';
            });
            return this;
        },
        append: function (doc) {
            var type = this.checkIf(doc, "String");
            if (type) {
                this.each(function (element) {
                    element.insertAdjacentHTML('beforeend', doc);
                });
            } else {
                this.each(function (element) {
                    element.appendChild(doc.cloneNode(true));
                });
            }
            return this;

        },
        prepend: function (doc) {
            var type = this.checkIf(doc, "String");
            if (type) {
                this.each(function (element) {
                    element.insertAdjacentHTML('afterbegin', doc);
                });
            } else {
                this.each(function (element) {
                    element.insertBefore(doc.cloneNode(true), element.firstChild);
                });
            }
            return this;

        },
        remove: function () {
            this.each(function (element) {
                element.parentNode && element.parentNode.removeChild(element);
            });
            return this;
        },
        parent: function () {
            return (!this.checkIf(this.element, "Array")) ? this.element.parentNode : null;
        },
        get: function () {
            return this.element;
        },
        each: function (fun) {
            if (!Array.prototype.forEach) {
                Array.prototype.forEach = function (fn, scope) {
                    for (var i = 0, len = this.length; i < len; ++i) {
                        fn.call(scope, this[i], i, this);
                    }
                }
            }
            if (this.checkIf(this.element, "Array")) {
                this.element.forEach(fun,this);
            } else {
                fun(this.element);
            }
        },
        checkIf: function (obj, type) {
            return Object.prototype.toString.call(obj) === '[object ' + type + ']';
        }
    }
    window.$$ = function (a) {
        return new FasterDom(a);
    };

})();
<commit_msg>Allows 'show()' to function with inline elements<commit_after>/**
 * Faster DOM manipulation
 * The most basic operations, but much faster than jquery. (mostly)
 * @author Vadim Kr.
 */
(function () {
    function FasterDom(s) {
        var z = 'getElement', g = 'Name', a = {'#': 'ById', '.': 'sByClass' + g, '@': 'sBy' + g, '=': 'sByTag' + g}[s[0]] || false,
            b = s.slice(1), u = (a ? document[z + a](b) : document.querySelectorAll(b));
        this.element = (this.checkIf(u, "NodeList")) ? Array.prototype.slice.call(u) : u;
    }

    FasterDom.prototype = {
        constructor: FasterDom,
        attr: function (name, value) {
            if (this.checkIf(name, 'String') && typeof value === "undefined") {
                return this.element.getAttribute(name);
            }
            var that = this;
            this.each(function (element) {
                that.set(element, name, value);
            });
            return this;
        }, set: function (element, name, value) {
            if (this.checkIf(name, "String")) {
                element.setAttribute(name, value);
            } else if (this.checkIf(name, "Object")) {
                for (var property in name) {
                    element.setAttribute(property, name[property]);
                }
            }
        },
        html: function (html) {
            if (typeof html === "undefined") {
                return this.element.innerHTML;
            }
            this.each(function (element) {
                element.innerHTML = html;
            });
            return this;
        },
        css: function (obj) {
            if (typeof obj === "undefined") {
                return this.element.style;
            }
            this.each(function (element) {
                for (var key in obj) {
                    element.style[key] = obj[key];
                }
            });
            return this;
        },
        hide: function () {
            this.each(function (element) {
                element.style.display = 'none';
            });
            return this;
        },
        show: function () {
            this.each(function (element) {
                element.style.display = '';
            });
            return this;
        },
        append: function (doc) {
            var type = this.checkIf(doc, "String");
            if (type) {
                this.each(function (element) {
                    element.insertAdjacentHTML('beforeend', doc);
                });
            } else {
                this.each(function (element) {
                    element.appendChild(doc.cloneNode(true));
                });
            }
            return this;

        },
        prepend: function (doc) {
            var type = this.checkIf(doc, "String");
            if (type) {
                this.each(function (element) {
                    element.insertAdjacentHTML('afterbegin', doc);
                });
            } else {
                this.each(function (element) {
                    element.insertBefore(doc.cloneNode(true), element.firstChild);
                });
            }
            return this;

        },
        remove: function () {
            this.each(function (element) {
                element.parentNode && element.parentNode.removeChild(element);
            });
            return this;
        },
        parent: function () {
            return (!this.checkIf(this.element, "Array")) ? this.element.parentNode : null;
        },
        get: function () {
            return this.element;
        },
        each: function (fun) {
            if (!Array.prototype.forEach) {
                Array.prototype.forEach = function (fn, scope) {
                    for (var i = 0, len = this.length; i < len; ++i) {
                        fn.call(scope, this[i], i, this);
                    }
                }
            }
            if (this.checkIf(this.element, "Array")) {
                this.element.forEach(fun,this);
            } else {
                fun(this.element);
            }
        },
        checkIf: function (obj, type) {
            return Object.prototype.toString.call(obj) === '[object ' + type + ']';
        }
    }
    window.$$ = function (a) {
        return new FasterDom(a);
    };

})();
<|endoftext|>


<commit_before>(function($) {

    $.fn.staticMenu = function() {
        var header = this;
        var menu = this.find('#menu');

        var menuHeight = menu.outerHeight(true);

        $(window).scroll(function() {
            if ($(window).scrollTop() > (header.outerHeight(true)-menuHeight)) {
                if (menu.find('.visible-desktop').is(':visible')) {
                    menu.addClass('static-menu');
                }
            } else {
                if (menu.hasClass('static-menu')) {
                    menu.removeClass('static-menu');
                }
            }
        });
    }

})(jQuery)
<commit_msg>Delete static menu<commit_after><|endoftext|>


<commit_before>goog.provide('lime.animation.Sequence');

goog.require('goog.math.Coordinate');
goog.require('lime.Sprite');
goog.require('lime.animation.Animation');

/**
 * Sequence of animations that are run after each other.
 * Also accepts more than two animations
 * @param {lime.animation.Animation} one First animation.
 * @param {lime.animation.Animation} two Second animation.
 * @constructor
 * @extends lime.animation.Animation
 */
lime.animation.Sequence = function(one, two) {

    lime.animation.Animation.call(this);

    var act = goog.array.toArray(arguments);
    if (goog.isArray(one)) act = one;

    if (act.length > 2) {

        var first = act.shift();
        this.actions = [first, new lime.animation.Sequence(act)];

    }
    else {
        this.actions = act;
    }

    this.setDuration(this.actions[0].duration_ + this.actions[1].duration_);

};
goog.inherits(lime.animation.Sequence, lime.animation.Animation);

/**
 * @inheritDoc
 * @see lime.animation.Animation#initTarget
 */
lime.animation.Sequence.prototype.initTarget = function(target) {
    lime.animation.Animation.prototype.initTarget.call(this, target);

    this.setDuration(this.actions[0].duration_ + this.actions[1].duration_);
    this.split_ = this.actions[0].duration_ / this.duration_;
    this.last_ = -1;
};

/**
 * @inheritDoc
 * @see lime.animation.Animation#stop
 */
lime.animation.Sequence.prototype.stop = function() {
    if (this.last_ != -1) {
        this.actions[this.last_].stop(this.targets);
    }
    lime.animation.Animation.prototype.stop.apply(this, arguments);
};

/**
 * @inheritDoc
 * @see lime.animation.Animation#updateAll
 */
lime.animation.Sequence.prototype.updateAll = function(t,targets) {
    if (this.status_ == 0) return;

    var i = targets.length;
    while (--i >= 0) {
        this.getTargetProp(targets[i]);
    }

    var found = 0,
        new_t = 0;

    if (t >= this.split_) {
        found = 1;
        if (this.split_ == 1) new_t = 1;
        else new_t = (t - this.split_) / (1 - this.split_);
    }
    else {
        found = 0;
        if (this.split_ != 0) new_t = t / this.split_;
        else new_t = 1;
    }

    if (this.last_ == -1 && found == 1) {
        this.actions[0].status_ = 1;
        //this.actions[0].initTarget(target);
        this.actions[0].updateAll(1, targets);
        this.actions[0].stop();
    }

    if (this.last_ != found) {
        if (this.last_ != -1) {
            this.actions[this.last_].updateAll(1, targets);
            this.actions[this.last_].stop();
        }
        this.actions[found].status_ = 1;
        //this.actions[found].initTarget(target);
    }

    this.actions[found].updateAll(new_t, targets);
    this.last_ = found;

    return t;
};

/**
 * @inheritDoc
 * @see lime.animation.Animation#reverse
 */
lime.animation.Sequence.prototype.reverse = function() {
    return new lime.animation.Sequence(this.actions[1].reverse(),
        this.actions[0].reverse());
};
<commit_msg>Made second parameter in sequence optinal, since first param can be an array.<commit_after>goog.provide('lime.animation.Sequence');

goog.require('goog.math.Coordinate');
goog.require('lime.Sprite');
goog.require('lime.animation.Animation');

/**
 * Sequence of animations that are run after each other.
 * Also accepts more than two animations
 * @param {Array.<lime.animation.Animation>|lime.animation.Animation} one First animation.
 * @param {lime.animation.Animation=} opt_two Second animation.
 * @constructor
 * @extends lime.animation.Animation
 */
lime.animation.Sequence = function(one, opt_two) {

    lime.animation.Animation.call(this);

    var act = goog.array.toArray(arguments);
    if (goog.isArray(one)) act = one;

    if (act.length > 2) {

        var first = act.shift();
        this.actions = [first, new lime.animation.Sequence(act)];

    }
    else {
        this.actions = act;
    }

    this.setDuration(this.actions[0].duration_ + this.actions[1].duration_);

};
goog.inherits(lime.animation.Sequence, lime.animation.Animation);

/**
 * @inheritDoc
 * @see lime.animation.Animation#initTarget
 */
lime.animation.Sequence.prototype.initTarget = function(target) {
    lime.animation.Animation.prototype.initTarget.call(this, target);

    this.setDuration(this.actions[0].duration_ + this.actions[1].duration_);
    this.split_ = this.actions[0].duration_ / this.duration_;
    this.last_ = -1;
};

/**
 * @inheritDoc
 * @see lime.animation.Animation#stop
 */
lime.animation.Sequence.prototype.stop = function() {
    if (this.last_ != -1) {
        this.actions[this.last_].stop(this.targets);
    }
    lime.animation.Animation.prototype.stop.apply(this, arguments);
};

/**
 * @inheritDoc
 * @see lime.animation.Animation#updateAll
 */
lime.animation.Sequence.prototype.updateAll = function(t,targets) {
    if (this.status_ == 0) return;

    var i = targets.length;
    while (--i >= 0) {
        this.getTargetProp(targets[i]);
    }

    var found = 0,
        new_t = 0;

    if (t >= this.split_) {
        found = 1;
        if (this.split_ == 1) new_t = 1;
        else new_t = (t - this.split_) / (1 - this.split_);
    }
    else {
        found = 0;
        if (this.split_ != 0) new_t = t / this.split_;
        else new_t = 1;
    }

    if (this.last_ == -1 && found == 1) {
        this.actions[0].status_ = 1;
        //this.actions[0].initTarget(target);
        this.actions[0].updateAll(1, targets);
        this.actions[0].stop();
    }

    if (this.last_ != found) {
        if (this.last_ != -1) {
            this.actions[this.last_].updateAll(1, targets);
            this.actions[this.last_].stop();
        }
        this.actions[found].status_ = 1;
        //this.actions[found].initTarget(target);
    }

    this.actions[found].updateAll(new_t, targets);
    this.last_ = found;

    return t;
};

/**
 * @inheritDoc
 * @see lime.animation.Animation#reverse
 */
lime.animation.Sequence.prototype.reverse = function() {
    return new lime.animation.Sequence(this.actions[1].reverse(),
        this.actions[0].reverse());
};
<|endoftext|>


<commit_before>import { walk } from 'estree-walker';
import Scope from './Scope.js';

const blockDeclarations = {
	'const': true,
	'let': true
};

export default function attachScopes ( statement ) {
	let { node, scope } = statement;

	walk( node, {
		enter ( node, parent ) {
			// function foo () {...}
			// class Foo {...}
			if ( /(Function|Class)Declaration/.test( node.type ) ) {
				scope.addDeclaration( node, false, false );
			}

			// var foo = 1
			if ( node.type === 'VariableDeclaration' ) {
				const isBlockDeclaration = blockDeclarations[ node.kind ];
				// only one declarator per block, because we split them up already
				scope.addDeclaration( node.declarations[0], isBlockDeclaration, true );
			}

			let newScope;

			// create new function scope
			if ( /Function/.test( node.type ) ) {
				newScope = new Scope({
					parent: scope,
					block: false,
					params: node.params
				});

				// named function expressions - the name is considered
				// part of the function's scope
				if ( node.type === 'FunctionExpression' && node.id ) {
					newScope.addDeclaration( node, false, false );
				}
			}

			// create new block scope
			if ( node.type === 'BlockStatement' && !/Function/.test( parent.type ) ) {
				newScope = new Scope({
					parent: scope,
					block: true
				});
			}

			// catch clause has its own block scope
			if ( node.type === 'CatchClause' ) {
				newScope = new Scope({
					parent: scope,
					params: [ node.param ],
					block: true
				});
			}

			if ( newScope ) {
				Object.defineProperty( node, '_scope', {
					value: newScope,
					configurable: true
				});

				scope = newScope;
			}
		},
		leave ( node ) {
			if ( node._scope ) {
				scope = scope.parent;
			}
		}
	});
}
<commit_msg>Include all declared variables.<commit_after>import { walk } from 'estree-walker';
import Scope from './Scope.js';

const blockDeclarations = {
	'const': true,
	'let': true
};

export default function attachScopes ( statement ) {
	let { node, scope } = statement;

	walk( node, {
		enter ( node, parent ) {
			// function foo () {...}
			// class Foo {...}
			if ( /(Function|Class)Declaration/.test( node.type ) ) {
				scope.addDeclaration( node, false, false );
			}

			// var foo = 1, bar = 2
			if ( node.type === 'VariableDeclaration' ) {
				const isBlockDeclaration = blockDeclarations[ node.kind ];
				node.declarations.forEach( declaration => scope.addDeclaration( declaration, isBlockDeclaration, true ) );
			}

			let newScope;

			// create new function scope
			if ( /Function/.test( node.type ) ) {
				newScope = new Scope({
					parent: scope,
					block: false,
					params: node.params
				});

				// named function expressions - the name is considered
				// part of the function's scope
				if ( node.type === 'FunctionExpression' && node.id ) {
					newScope.addDeclaration( node, false, false );
				}
			}

			// create new block scope
			if ( node.type === 'BlockStatement' && !/Function/.test( parent.type ) ) {
				newScope = new Scope({
					parent: scope,
					block: true
				});
			}

			// catch clause has its own block scope
			if ( node.type === 'CatchClause' ) {
				newScope = new Scope({
					parent: scope,
					params: [ node.param ],
					block: true
				});
			}

			if ( newScope ) {
				Object.defineProperty( node, '_scope', {
					value: newScope,
					configurable: true
				});

				scope = newScope;
			}
		},
		leave ( node ) {
			if ( node._scope ) {
				scope = scope.parent;
			}
		}
	});
}
<|endoftext|>


<commit_before>module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        browserify : {
            test : {
                src : ["src/p2.js"],
                dest : 'build/p2.js',
                options : {
                    standalone : "p2"
                }
            }
        },

        uglify : {
            build : {
                src : ['build/p2.js'],
                dest : 'build/p2.min.js'
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-browserify');
    grunt.registerTask('default', ['uglify', 'browserify']);

};
<commit_msg>gruntfile default build order fix<commit_after>module.exports = function(grunt) {

    grunt.initConfig({
        pkg: grunt.file.readJSON('package.json'),

        browserify : {
            test : {
                src : ["src/p2.js"],
                dest : 'build/p2.js',
                options : {
                    standalone : "p2"
                }
            }
        },

        uglify : {
            build : {
                src : ['build/p2.js'],
                dest : 'build/p2.min.js'
            }
        }
    });

    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-browserify');
    grunt.registerTask('default', ['browserify','uglify']);

};
<|endoftext|>


<commit_before>/**
	A control that activates a [moon.Tooltip](#moon.Tooltip). It surrounds a
	control such as a button and displays the tooltip when the control generates
	an _onEnter_ event:

		{kind: "moon.TooltipDecorator", components: [
			{kind: "moon.Button", content: "Tooltip"},
			{kind: "moon.Tooltip", content: "I'm a tooltip for a button."}
		]}

	Here's an example with a [moon.Input](#moon.Input) control and a decorator
	around the input:

		{kind: "moon.TooltipDecorator", components: [
			{kind: "moon.InputDecorator", components: [
				{kind: "moon.Input", placeholder: "Just an input..."}
			]},
			{kind: "moon.Tooltip", content: "I'm just a tooltip for an input."}
		]}

	Automatic hiding and showing of tooltips may be disabled by calling _mute()_
	or by bubbling the _onRequestMuteTooltip_ event; it may be re-enabled by
	calling _unmute()_ or by bubbling the _onRequestUnmuteTooltip_ event.
*/
enyo.kind({
	name: "moon.TooltipDecorator",
	//* @protected
	defaultKind: "moon.Button",
	classes: "moon-contextual-popup-decorator",
	handlers: {
		onenter: "enter",
		onleave: "leave",
		onSpotlightFocused: "spotFocused",
		onSpotlightBlur: "spotBlur",
		onRequestMuteTooltip: "mute",
		onRequestUnmuteTooltip: "unmute"
	},
	//* @public
	published: {
		/**
			Boolean indicating whether tooltips are automatically shown when the
			activator is hovered over
		*/
		autoShow: true
	},
	//* @public
	//* Disables automatic tooltip showing/hiding.
	mute: function() {
		this.setAutoShow(false);
	},
	//* Re-enables automatic tooltip showing/hiding after being muted.
	unmute: function() {
		this.setAutoShow(true);
	},
	//* @protected
	autoShowChanged: function() {
		if (!this.autoShow) {
			this.requestHideTooltip();
		}
	},
	enter: function() {
		this.requestShowTooltip();
	},
	leave: function() {
		this.requestHideTooltip();
	},
	spotFocused: function() {
		this.requestShowTooltip();
	},
	spotBlur: function() {
		this.requestHideTooltip();
	},
	tap: function() {
		this.requestHideTooltip();
	},
	requestShowTooltip: function() {
		if (this.autoShow) {
			this.waterfallDown("onRequestShowTooltip");
		}
	},
	requestHideTooltip: function() {
		this.waterfallDown("onRequestHideTooltip");
	}
});
<commit_msg>GF-58347: update moon.Tooltip not to appear when spotlight is freezed. Enyo-DCO-1.1-Signed-off-by: YoungMok Kim <ym1980.kim@lge.com><commit_after>/**
	A control that activates a [moon.Tooltip](#moon.Tooltip). It surrounds a
	control such as a button and displays the tooltip when the control generates
	an _onEnter_ event:

		{kind: "moon.TooltipDecorator", components: [
			{kind: "moon.Button", content: "Tooltip"},
			{kind: "moon.Tooltip", content: "I'm a tooltip for a button."}
		]}

	Here's an example with a [moon.Input](#moon.Input) control and a decorator
	around the input:

		{kind: "moon.TooltipDecorator", components: [
			{kind: "moon.InputDecorator", components: [
				{kind: "moon.Input", placeholder: "Just an input..."}
			]},
			{kind: "moon.Tooltip", content: "I'm just a tooltip for an input."}
		]}

	Automatic hiding and showing of tooltips may be disabled by calling _mute()_
	or by bubbling the _onRequestMuteTooltip_ event; it may be re-enabled by
	calling _unmute()_ or by bubbling the _onRequestUnmuteTooltip_ event.
*/
enyo.kind({
	name: "moon.TooltipDecorator",
	//* @protected
	defaultKind: "moon.Button",
	classes: "moon-contextual-popup-decorator",
	handlers: {
		onenter: "enter",
		onleave: "leave",
		onSpotlightFocused: "spotFocused",
		onSpotlightBlur: "spotBlur",
		onRequestMuteTooltip: "mute",
		onRequestUnmuteTooltip: "unmute"
	},
	//* @public
	published: {
		/**
			Boolean indicating whether tooltips are automatically shown when the
			activator is hovered over
		*/
		autoShow: true
	},
	//* @public
	//* Disables automatic tooltip showing/hiding.
	mute: function() {
		this.setAutoShow(false);
	},
	//* Re-enables automatic tooltip showing/hiding after being muted.
	unmute: function() {
		this.setAutoShow(true);
	},
	//* @protected
	autoShowChanged: function() {
		if (!this.autoShow) {
			this.requestHideTooltip();
		}
	},
	enter: function() {
		this.requestShowTooltip();
	},
	leave: function() {
		this.requestHideTooltip();
	},
	spotFocused: function() {
		this.requestShowTooltip();
	},
	spotBlur: function() {
		this.requestHideTooltip();
	},
	tap: function() {
		this.requestHideTooltip();
	},
	requestShowTooltip: function() {
		if (this.autoShow && !enyo.Spotlight.isFrozen()) {
			this.waterfallDown("onRequestShowTooltip");
		}
	},
	requestHideTooltip: function() {
		this.waterfallDown("onRequestHideTooltip");
	}
});
<|endoftext|>


<commit_before>
var jshintGlobals = require('jshint-globals')
  , compassRequires = ['susy', 'compass-placeholder', 'compass-retina-sprites', 'toolkit', 'animation', 'compass-h5bp'];

module.exports = function(grunt) {

  'use strict';

  // Project configuration.
  grunt.initConfig({

    jshint: {
      options: {
        maxlen : 100,
        strict : false,
        curly : false,
        eqeqeq : true,
        loopfunc : true,
        forin : false,
        immed : true,
        latedef : true,
        newcap : true,
        noarg : true,
        sub : true,
        undef : true,
        boss : true,
        eqnull : true,
        node : true,
        es5 : true,
        supernew : true,
        laxbreak : true,
        expr : true,
        laxcomma : true,
        unused : true,
        globals: jshintGlobals({
          lcf : true,
          pcf : true,
          cf : true,
          gt : true,
          tmpl : true,
          opt : true,
          Modernizr : true,
          jQuery : true,
          $ : true,
          requirejs : jshintGlobals.requirejs,
          mocha : jshintGlobals.mocha,
          browser : jshintGlobals.browser
        })
      },

      files: [
        'grunt.js',
        'app/**/*.js',
        'lib/**/*.js',
        '!app/build/tmpl.js',
        '!app/vendor/**',
        '!app/public/templates/**/*.js',
        'src/**/*.js'
      ]
    },

    compass : {
      documents : {
        options : {
          require : compassRequires,
          sassDir : 'interface/documents/styles',
          cssDir : 'interface/public/styles/documents',
          debugInfo : true,
          noLineComments : true,
          imagesDir : 'interface/public/images',
          relativeAssets : true
        }
      },

      content : {
        options : {
          require : compassRequires,
          sassDir : 'interface/content/styles',
          cssDir : 'interface/public/styles/content',
          debugInfo : true,
          noLineComments : true,
          imagesDir : 'interface/public/images',
          relativeAssets : true
        }
      }
    },

    modernizr : {
      dist : {
        devFile : 'interface/vendor/modernizr/modernizr.js',
        outputFile : 'interface/vendor/modernizr/build/modernizr.js', // we will revision this later
        extra : {
          shiv : true,
          printShiv : false,
          mq : true,
          cssclasses : true
        },
        extensibility : {
          addtest : true,
          prefixed : false,
          teststyles : false,
          testallprops : false,
          hasevents : false,
          prefixes : false,
          domprefixes : false,
        },
        uglify : true,
        parseFiles : true
      }
    },

    clean : {
      css: ['interface/public/styles/*']
    },

    dot : {
      core : {
        options : {
          variable : 'tmpl',
          requirejs : true,
          node : true
        },
        src : ['interface/core/**/*.dot'],
        dest : 'interface/public/templates/core/tmpl.js'
      },

      documents : {
        options : {
          variable : 'tmpl',
          requirejs : true,
          node : true
        },
        src : ['interface/documents/**/*.dot'],
        dest : 'interface/public/templates/documents/tmpl.js'
      },

      layouts : {
        options : {
          variable : 'tmpl',
          requirejs : true,
          node : true
        },
        src : ['interface/layouts/**/*.dot'],
        dest : 'interface/public/templates/layouts/tmpl.js'
      },

      content_app : {
        options : {
          variable : 'tmpl',
          requirejs : true,
          node : true
        },
        src : [
          'interface/content/translations/**/*.dot',
          'interface/content/search/**/*.dot',
          'interface/content/translation/**/*.dot'
        ],
        dest : 'interface/public/templates/content/app.js'
      },

      jsPlugin : {
        options : {
          variable : 'tmpl',
          requirejs : false,
          node : true
        },
        src : ['plugins/javascript/templates/*.{dot,part}'],
        dest : 'plugins/javascript/templates/build/tmpl.js'
      }
    },

    mocha: {
      test: {
        src: ['interface/specifications/*.html'],
        options: {
          run: false
        }
      },
    },

    watch: {
      templates: {
        files: [
          '**/*.dot',
          '**/*.part'
        ],
        tasks: ['dot']
      },

      jshint: {
        files: [
          '**/*.js',
          'Gruntfile.js',
          'bin/**/*.js',
          'tasks/**/*.js',
          '!**/node_modules/**/*.js'
        ],
        tasks: ['jshint']
      },

      styles_documents : {
        files : [
          'interface/layouts/**/*.scss',
          'interface/documents/styles/**/*.scss',
          'interface/components/**/*.scss'
        ],
        tasks : ['compass:documents']
      },

      styles_content_app : {
        files : [
          'interface/content/styles/app.scss',
          'interface/content/translations/**/*.scss',
          'interface/content/search/**/*.scss',
          'interface/content/edit/**/*.scss'
        ],
        tasks : ['compass:content']
      }
    },

    webp: {
      dev : {
        expand: true,
        cwd : 'interface/public/images',
        src : [
          '*.{jpg,png}'
        ],
        dest : 'interface/public/images-webp'
      },
      options: {
        lossless: true,
      }
    },

    requirejs: {
      default: {
        options: {
          optimize : 'uglify',
          preserveLicenseComments : false,
          // generateSourceMaps : true,
          baseUrl : 'interface',
          mainConfigFile : 'interface/documents/mains/app.js',
          out : 'interface/public/scripts/mains/app.js',
          name : 'documents/mains/app',
          paths : {
            'modernizr' : 'empty:'
          }
        }
      }
    }
  });

  // Load npm tasks
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-requirejs');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-webp');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-dot-compiler');
  grunt.loadNpmTasks('grunt-modernizr');
  grunt.loadNpmTasks('grunt-mocha');

};
<commit_msg>Added reporter spec<commit_after>
var jshintGlobals = require('jshint-globals')
  , compassRequires = ['susy', 'compass-placeholder', 'compass-retina-sprites', 'toolkit', 'animation', 'compass-h5bp'];

module.exports = function(grunt) {

  'use strict';

  // Project configuration.
  grunt.initConfig({

    jshint: {
      options: {
        maxlen : 100,
        strict : false,
        curly : false,
        eqeqeq : true,
        loopfunc : true,
        forin : false,
        immed : true,
        latedef : true,
        newcap : true,
        noarg : true,
        sub : true,
        undef : true,
        boss : true,
        eqnull : true,
        node : true,
        es5 : true,
        supernew : true,
        laxbreak : true,
        expr : true,
        laxcomma : true,
        unused : true,
        globals: jshintGlobals({
          lcf : true,
          pcf : true,
          cf : true,
          gt : true,
          tmpl : true,
          opt : true,
          Modernizr : true,
          jQuery : true,
          $ : true,
          requirejs : jshintGlobals.requirejs,
          mocha : jshintGlobals.mocha,
          browser : jshintGlobals.browser
        })
      },

      files: [
        'grunt.js',
        'app/**/*.js',
        'lib/**/*.js',
        '!app/build/tmpl.js',
        '!app/vendor/**',
        '!app/public/templates/**/*.js',
        'src/**/*.js'
      ]
    },

    compass : {
      documents : {
        options : {
          require : compassRequires,
          sassDir : 'interface/documents/styles',
          cssDir : 'interface/public/styles/documents',
          debugInfo : true,
          noLineComments : true,
          imagesDir : 'interface/public/images',
          relativeAssets : true
        }
      },

      content : {
        options : {
          require : compassRequires,
          sassDir : 'interface/content/styles',
          cssDir : 'interface/public/styles/content',
          debugInfo : true,
          noLineComments : true,
          imagesDir : 'interface/public/images',
          relativeAssets : true
        }
      }
    },

    modernizr : {
      dist : {
        devFile : 'interface/vendor/modernizr/modernizr.js',
        outputFile : 'interface/vendor/modernizr/build/modernizr.js', // we will revision this later
        extra : {
          shiv : true,
          printShiv : false,
          mq : true,
          cssclasses : true
        },
        extensibility : {
          addtest : true,
          prefixed : false,
          teststyles : false,
          testallprops : false,
          hasevents : false,
          prefixes : false,
          domprefixes : false,
        },
        uglify : true,
        parseFiles : true
      }
    },

    clean : {
      css: ['interface/public/styles/*']
    },

    dot : {
      core : {
        options : {
          variable : 'tmpl',
          requirejs : true,
          node : true
        },
        src : ['interface/core/**/*.dot'],
        dest : 'interface/public/templates/core/tmpl.js'
      },

      documents : {
        options : {
          variable : 'tmpl',
          requirejs : true,
          node : true
        },
        src : ['interface/documents/**/*.dot'],
        dest : 'interface/public/templates/documents/tmpl.js'
      },

      layouts : {
        options : {
          variable : 'tmpl',
          requirejs : true,
          node : true
        },
        src : ['interface/layouts/**/*.dot'],
        dest : 'interface/public/templates/layouts/tmpl.js'
      },

      content_app : {
        options : {
          variable : 'tmpl',
          requirejs : true,
          node : true
        },
        src : [
          'interface/content/translations/**/*.dot',
          'interface/content/search/**/*.dot',
          'interface/content/translation/**/*.dot'
        ],
        dest : 'interface/public/templates/content/app.js'
      },

      jsPlugin : {
        options : {
          variable : 'tmpl',
          requirejs : false,
          node : true
        },
        src : ['plugins/javascript/templates/*.{dot,part}'],
        dest : 'plugins/javascript/templates/build/tmpl.js'
      }
    },

    mocha: {
      test: {
        src: ['interface/specifications/*.html'],
        options: {
          run: false,
          reporter: './node_modules/mocha/lib/reporters/spec.js'
        }
      },
    },

    watch: {
      templates: {
        files: [
          '**/*.dot',
          '**/*.part'
        ],
        tasks: ['dot']
      },

      jshint: {
        files: [
          '**/*.js',
          'Gruntfile.js',
          'bin/**/*.js',
          'tasks/**/*.js',
          '!**/node_modules/**/*.js'
        ],
        tasks: ['jshint']
      },

      styles_documents : {
        files : [
          'interface/layouts/**/*.scss',
          'interface/documents/styles/**/*.scss',
          'interface/components/**/*.scss'
        ],
        tasks : ['compass:documents']
      },

      styles_content_app : {
        files : [
          'interface/content/styles/app.scss',
          'interface/content/translations/**/*.scss',
          'interface/content/search/**/*.scss',
          'interface/content/edit/**/*.scss'
        ],
        tasks : ['compass:content']
      }
    },

    webp: {
      dev : {
        expand: true,
        cwd : 'interface/public/images',
        src : [
          '*.{jpg,png}'
        ],
        dest : 'interface/public/images-webp'
      },
      options: {
        lossless: true,
      }
    },

    requirejs: {
      default: {
        options: {
          optimize : 'uglify',
          preserveLicenseComments : false,
          // generateSourceMaps : true,
          baseUrl : 'interface',
          mainConfigFile : 'interface/documents/mains/app.js',
          out : 'interface/public/scripts/mains/app.js',
          name : 'documents/mains/app',
          paths : {
            'modernizr' : 'empty:'
          }
        }
      }
    }
  });

  // Load npm tasks
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-requirejs');
  grunt.loadNpmTasks('grunt-contrib-compass');
  grunt.loadNpmTasks('grunt-contrib-clean');
  grunt.loadNpmTasks('grunt-webp');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-dot-compiler');
  grunt.loadNpmTasks('grunt-modernizr');
  grunt.loadNpmTasks('grunt-mocha');

};
<|endoftext|>


<commit_before>ret = db.feeds.createIndex({id: 1}, {unique: true }); checkret('feeds id', ret);

ret = db.labels.createIndex({ "semanticId" : 1 }, { unique: true }); checkret('labels semanticId', ret);
ret = db.labels.createIndex({ "when" : 1 }); checkret('labels when', ret);

ret = db.metadata.createIndex({ "semanticId" : 1 }); checkret('metadata semanticId', ret);
ret = db.metadata.createIndex({ "userId" : 1 }); checkret('metadata userId', ret);
ret = db.metadata.createIndex({ "semantic" : 1 }); checkret('metadata semantic', ret);
ret = db.metadata.createIndex({ "id" : 1 }, { unique : true }); checkret('metadata id', ret);
ret = db.metadata.createIndex({ "impressionTime" : -1 }); checkret('metadata impressionTime', ret);
ret = db.metadata.createIndex({ "linkedtime.postId" : 1 }); checkret('metadata linkedtime.postId', ret);

ret = db.semantics.createIndex({ "label" : 1 });
ret = db.semantics.createIndex({ "when" : 1 });
ret = db.semantics.createIndex({ "semanticId" : 1 });

ret = db.parsererrors.createIndex({ "id": 1 }); checkret('parsererror id', ret);

ret = db.aggregated.createIndex({ "hourId": 1 }, {unique: true}); checkret('aggregated hourId id', ret);

ret = db.summary.createIndex({ "id": 1 }, { unique: true }); checkret('summary id', ret);
ret = db.summary.createIndex({ "impressionTime": -1 }); checkret('summary id', ret);

function checkret(info, retval) {
    retval.info = info;
    printjson(retval);
};
<commit_msg>fix typos<commit_after>ret = db.feeds.createIndex({id: 1}, {unique: true }); checkret('feeds id', ret);

ret = db.labels.createIndex({ "semanticId" : 1 }, { unique: true }); checkret('labels semanticId', ret);
ret = db.labels.createIndex({ "when" : 1 }); checkret('labels when', ret);

ret = db.metadata.createIndex({ "semanticId" : 1 }); checkret('metadata semanticId', ret);
ret = db.metadata.createIndex({ "userId" : 1 }); checkret('metadata userId', ret);
ret = db.metadata.createIndex({ "semantic" : 1 }); checkret('metadata semantic', ret);
ret = db.metadata.createIndex({ "id" : 1 }, { unique : true }); checkret('metadata id', ret);
ret = db.metadata.createIndex({ "impressionTime" : -1 }); checkret('metadata impressionTime', ret);
ret = db.metadata.createIndex({ "linkedtime.postId" : 1 }); checkret('metadata linkedtime.postId', ret);

ret = db.semantics.createIndex({ "label" : 1 });
ret = db.semantics.createIndex({ "when" : 1 });
ret = db.semantics.createIndex({ "semanticId" : 1 });

ret = db.parsererrors.createIndex({ "id": 1 }); checkret('parsererror id', ret);

ret = db.aggregated.createIndex({ "hourId": 1 }, {unique: true}); checkret('aggregated hourId', ret);

ret = db.summary.createIndex({ "id": 1 }, { unique: true }); checkret('summary id', ret);
ret = db.summary.createIndex({ "impressionTime": -1 }); checkret('summary impressionTime', ret);

function checkret(info, retval) {
    retval.info = info;
    printjson(retval);
};
<|endoftext|>


<commit_before>/**
 *  Exports items, layers or whole projects as a svg
 *  Stetson Alpha - Paper.js
 *
 *  var NS="http://www.w3.org/2000/svg";
 *  var svg=document.createElementNS(NS,"svg");
 */

var ExportSVG = function()
{
	var svgObj = null; // xml dom object (svg typed)
	//var blarg = this;

	//initialize the svgObj and what ever else.
	/*function initialize()
	{
		var NS = "http://www.w3.org/2000/svg";
		svgObj = document.createElementNS(NS,"svg");

		console.log(svgObj);

	};*/

	/**
	 *
	 * Takes the whole project and parses
	 * all the layers to be put into svg groups and
	 * groups into svg groups making all the projects
	 * items into one svg.
	 *
	 * takes in a Paper.js Project
	 * returns svg object (xml dom)
	 */
    this.exportProject = function(project)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the layer and then parses all groups
	 * and items into one svg
	 *
	 * takes in a Paper.js Layer
	 * returns svg object (xml dom)
	 */
    this.exportLayer = function(layer)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the group and puts it's items
	 * in a svg file.
	 *
	 * takes in a Paper.js Group
	 * returns svg object (xml dom)
	 */
    this.exportGroup = function(group)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the item and puts it in
	 * a svg file.
	 *
	 * takes in a Paper.js Item
	 * returns svg object (xml dom)
	 */
    this.exportItem = function(item)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the path and puts it in
	 * a svg file.
	 *
	 * takes in a Paper.js Path
	 * returns svg object (xml dom)
	 */
    this.exportPath = function(path)
    {
    	//this.initialize();
    	//console.log(blarg.svgObj);
	var NS = "http://www.w3.org/2000/svg";
	svgObj = document.createElementNS(NS,"svg");
	svgRect = document.createElementNS(NS,"rect");
	svgRect.height.baseVal.value = 50;
	svgRect.width.baseVal.value = 60;
	svgRect.x.baseVal.value = 50;
	svgObj.appendChild(svgRect);

	svgPoint = document.createElementNS(NS,"point");
	svgPoint.setAttribute("x",50);
	svgPoint.setAttribute("y",100);
	svgObj.appendChild(svgPoint);

	svgPath = document.createElementNS(NS, "path");

    	console.log(svgObj);
	var pathClone = path.clone();
	var segArray = pathClone.getSegments();

	var pointArray = new Array();
	var handleInArray = new Array();
	var handleOutArray = new Array();
	for(i = 0; i < segArray.length; i++)
	{
		console.log(segArray[i].toString());
		pointArray[i] = segArray[i].getPoint();
		handleInArray[i] = segArray[i].getHandleIn();
		handleOutArray[i] = segArray[i].getHandleOut();

		console.log("point " + i + ": " + pointArray[i]);
		console.log("HI " + i + ": " + handleInArray[i]);
		console.log("HO " + i + ": " + handleOutArray[i]);
	}
	var pointString = "";
	for(i = 0; i < pointArray.length; i++)
	{
		var x = pointArray[i].getX();
		//x = x - (x % 1);
		var y = pointArray[i].getY();
		//y = y - (x % 1);
		if(i === 0)
		{
			pointString+= "M " + x + " " + y + " ";
		}
		else
		{
			pointString+= "L " + x + " " + y + " ";
		}
	}
	if(pathClone.getClosed())
	{
		pointString += "z";
	}

	svgPath.setAttribute("d",pointString);

	if(pathClone.strokeColor != undefined)
	{
		var strokeRed = pathClone.strokeColor.red;
		var strokeGreen = pathClone.strokeColor.green;
		var strokeBlue = pathClone.strokeColor.blue;
		var strokeRGB = RGBtoHex(strokeRed, strokeGreen, strokeBlue);
		svgPath.setAttribute("stroke", strokeRGB);
	}

	if(pathClone.fillColor != undefined)
	{
		var fillRed = pathClone.fillColor.red;
		var fillGreen = pathClone.fillColor.green;
		var fillBlue = pathClone.fillColor.blue;
		var fillRGB = RGBtoHex(fillRed, fillGreen, fillBlue);
		svgPath.setAttribute("fill", fillRGB);
	}

	//svgPath.setAttribute("d", pointString);
	//svgPath.setAttribute("stroke", strokeRGB);
	//svgPath.setAttribute("fill", fillRGB);
	svgPath.setAttribute("stroke-width",pathClone.strokeWidth);
	svgObj.appendChild(svgPath);

	console.log(svgObj);
	return svgObj;
    };

    function RGBConverter(deciColor)
    {
	var decColor = Math.round(deciColor * 255);
	var hexColor = decColor.toString(16);
	hexColor = hexColor.length > 1? hexColor : "0" + hexColor;
	return hexColor;
    };

    function RGBtoHex(red, green, blue)
    {
    	var redVal = RGBConverter(red);
	var greenVal = RGBConverter(green);
	var blueVal = RGBConverter(blue);
	return "#" + redVal + greenVal + blueVal;
    }

    //initialize(); // calls the init function after class is loaded
};
<commit_msg>Cleaned up ExportSVG for general purpose. Removed all lines written for testing purposes, saved them in a text document for possible future reference. Code should look a lot more clean and linear with all the stuff removed.<commit_after>/**
 *  Exports items, layers or whole projects as a svg
 *  Stetson Alpha - Paper.js
 *
 *  var NS="http://www.w3.org/2000/svg";
 *  var svg=document.createElementNS(NS,"svg");
 */

var ExportSVG = function()
{
	var svgObj = null; // xml dom object (svg typed)
	//var blarg = this;

	//initialize the svgObj and what ever else.
	/*function initialize()
	{
		var NS = "http://www.w3.org/2000/svg";
		svgObj = document.createElementNS(NS,"svg");

		console.log(svgObj);

	};*/

	/**
	 *
	 * Takes the whole project and parses
	 * all the layers to be put into svg groups and
	 * groups into svg groups making all the projects
	 * items into one svg.
	 *
	 * takes in a Paper.js Project
	 * returns svg object (xml dom)
	 */
    this.exportProject = function(project)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the layer and then parses all groups
	 * and items into one svg
	 *
	 * takes in a Paper.js Layer
	 * returns svg object (xml dom)
	 */
    this.exportLayer = function(layer)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the group and puts it's items
	 * in a svg file.
	 *
	 * takes in a Paper.js Group
	 * returns svg object (xml dom)
	 */
    this.exportGroup = function(group)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the item and puts it in
	 * a svg file.
	 *
	 * takes in a Paper.js Item
	 * returns svg object (xml dom)
	 */
    this.exportItem = function(item)
    {
    	return svgObj;
    };

	/**
	 *
	 * Takes the path and puts it in
	 * a svg file.
	 *
	 * takes in a Paper.js Path
	 * returns svg object (xml dom)
	 */
    this.exportPath = function(path)
    {
    	//this.initialize();
    	//console.log(blarg.svgObj);
	var pathClone = path.clone();
	var NS = "http://www.w3.org/2000/svg";
	svgObj = document.createElementNS(NS,"svg");
	svgPath = document.createElementNS(NS, "path");

	var segArray = pathClone.getSegments();

	var pointArray = new Array();
	var handleInArray = new Array();
	var handleOutArray = new Array();
	for(i = 0; i < segArray.length; i++)
	{
		console.log(segArray[i].toString());
		pointArray[i] = segArray[i].getPoint();
		handleInArray[i] = segArray[i].getHandleIn();
		handleOutArray[i] = segArray[i].getHandleOut();
	}
	var pointString = "";
	for(i = 0; i < pointArray.length; i++)
	{
		var x = pointArray[i].getX();
		//x = x - (x % 1);
		var y = pointArray[i].getY();
		//y = y - (x % 1);
		if(i === 0)
		{
			pointString+= "M " + x + " " + y + " ";
		}
		else
		{
			pointString+= "L " + x + " " + y + " ";
		}
	}
	if(pathClone.getClosed())
	{
		pointString += "z";
	}

	svgPath.setAttribute("d",pointString);

	if(pathClone.strokeColor != undefined)
	{
		var strokeRed = pathClone.strokeColor.red;
		var strokeGreen = pathClone.strokeColor.green;
		var strokeBlue = pathClone.strokeColor.blue;
		var strokeRGB = RGBtoHex(strokeRed, strokeGreen, strokeBlue);
		svgPath.setAttribute("stroke", strokeRGB);
	}

	if(pathClone.fillColor != undefined)
	{
		var fillRed = pathClone.fillColor.red;
		var fillGreen = pathClone.fillColor.green;
		var fillBlue = pathClone.fillColor.blue;
		var fillRGB = RGBtoHex(fillRed, fillGreen, fillBlue);
		svgPath.setAttribute("fill", fillRGB);
	}
	svgPath.setAttribute("stroke-width",pathClone.strokeWidth);
	svgObj.appendChild(svgPath);
	return svgObj;
    };

    function RGBConverter(deciColor)
    {
	var decColor = Math.round(deciColor * 255);
	var hexColor = decColor.toString(16);
	hexColor = hexColor.length > 1? hexColor : "0" + hexColor;
	return hexColor;
    };

    function RGBtoHex(red, green, blue)
    {
    	var redVal = RGBConverter(red);
	var greenVal = RGBConverter(green);
	var blueVal = RGBConverter(blue);
	return "#" + redVal + greenVal + blueVal;
    }

    //initialize(); // calls the init function after class is loaded
};
<|endoftext|>


<commit_before>'use strict';

var exec = require('child_process').exec;
var jsxTask = require('./grunt/tasks/jsx');
var browserifyTask = require('./grunt/tasks/browserify');
var populistTask = require('./grunt/tasks/populist');
var phantomTask = require('./grunt/tasks/phantom');
var webdriverJasmineTasks = require('./grunt/tasks/webdriver-jasmine.js');
var npmTask = require('./grunt/tasks/npm');
var releaseTasks = require('./grunt/tasks/release');

module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    copy: require('./grunt/config/copy'),
    jsx: require('./grunt/config/jsx/jsx'),
    browserify: require('./grunt/config/browserify'),
    populist: require('./grunt/config/populist'),
    phantom: require('./grunt/config/phantom'),
    connect: require('./grunt/config/server')(grunt),
    "webdriver-jasmine": require('./grunt/config/webdriver-jasmine.js'),
    npm: require('./grunt/config/npm'),
    clean: ['./build', './*.gem', './docs/_site', './examples/shared/*.js'],
    jshint: require('./grunt/config/jshint'),
    compare_size: require('./grunt/config/compare_size')
  });

  grunt.config.set('compress', require('./grunt/config/compress'));

  for (var key in grunt.file.readJSON("package.json").devDependencies) {
      if (key !== "grunt" && key.indexOf("grunt") === 0) grunt.loadNpmTasks(key);
  }

  // Alias 'jshint' to 'lint' to better match the workflow we know
  grunt.registerTask('lint', ['jshint']);

  // Register jsx:debug and :release tasks.
  grunt.registerMultiTask('jsx', jsxTask);

  // Our own browserify-based tasks to build a single JS file build
  grunt.registerMultiTask('browserify', browserifyTask);

  grunt.registerMultiTask('populist', populistTask);

  grunt.registerMultiTask('phantom', phantomTask);

  grunt.registerMultiTask('webdriver-jasmine', webdriverJasmineTasks);

  grunt.registerMultiTask('npm', npmTask);

  // Check that the version we're exporting is the same one we expect in the
  // package. This is not an ideal way to do this, but makes sure that we keep
  // them in sync.
  var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/;
  grunt.registerTask('version-check', function() {
    var version = reactVersionExp.exec(
      grunt.file.read('./build/modules/React.js')
    )[1];
    var expectedVersion = grunt.config.data.pkg.version;
    if (version !== expectedVersion) {
      grunt.log.error('Versions do not match. Expected %s, saw %s', expectedVersion, version);
      return false;
    }
  });

  grunt.registerTask('build:basic', ['jsx:debug', 'version-check', 'browserify:basic']);
  grunt.registerTask('build:addons', ['jsx:debug', 'browserify:addons']);
  grunt.registerTask('build:transformer', ['jsx:debug', 'browserify:transformer']);
  grunt.registerTask('build:min', ['jsx:release', 'version-check', 'browserify:min']);
  grunt.registerTask('build:addons-min', ['jsx:debug', 'browserify:addonsMin']);
  grunt.registerTask('build:test', [
    'jsx:jasmine',
    'jsx:test',
    'version-check',
    'populist:test'
  ]);

  grunt.registerTask('test:webdriver', [
    'connect',
    'webdriver-jasmine:local'
  ]);
  grunt.registerTask('test', ['build:test', 'build:basic', 'phantom:run']);
  grunt.registerTask('npm:test', ['build', 'npm:pack']);

  // Optimized build task that does all of our builds. The subtasks will be run
  // in order so we can take advantage of that and only run jsx:debug once.
  grunt.registerTask('build', [
    'jsx:debug',
    'version-check',
    'browserify:basic',
    'browserify:transformer',
    'browserify:addons',
    'jsx:release',
    'browserify:min',
    'browserify:addonsMin',
    'copy:react_docs',
    'compare_size'
  ]);

  // Automate the release!
  grunt.registerTask('release:setup', releaseTasks.setup);
  grunt.registerTask('release:bower', releaseTasks.bower);
  grunt.registerTask('release:docs', releaseTasks.docs);
  grunt.registerTask('release:msg', releaseTasks.msg);
  grunt.registerTask('release:starter', releaseTasks.starter);

  grunt.registerTask('release', [
    'release:setup',
    'clean',
    'build',
    'gem:only',
    'release:bower',
    'release:starter',
    'compress',
    'release:docs',
    'release:msg'
  ]);

  // `gem` task to build the react-source gem
  grunt.registerTask('gem', ['build', 'gem:only']);

  grunt.registerTask('gem:only', function() {
    var done = this.async();
    exec('gem build react-source.gemspec', done);
  });

  // The default task - build - to keep setup easy
  grunt.registerTask('default', ['build']);
};
<commit_msg>cleanup<commit_after>'use strict';

var exec = require('child_process').exec;
var jsxTask = require('./grunt/tasks/jsx');
var browserifyTask = require('./grunt/tasks/browserify');
var populistTask = require('./grunt/tasks/populist');
var phantomTask = require('./grunt/tasks/phantom');
var webdriverJasmineTasks = require('./grunt/tasks/webdriver-jasmine');
var npmTask = require('./grunt/tasks/npm');
var releaseTasks = require('./grunt/tasks/release');

module.exports = function(grunt) {

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    copy: require('./grunt/config/copy'),
    jsx: require('./grunt/config/jsx/jsx'),
    browserify: require('./grunt/config/browserify'),
    populist: require('./grunt/config/populist'),
    phantom: require('./grunt/config/phantom'),
    connect: require('./grunt/config/server')(grunt),
    "webdriver-jasmine": require('./grunt/config/webdriver-jasmine.js'),
    npm: require('./grunt/config/npm'),
    clean: ['./build', './*.gem', './docs/_site', './examples/shared/*.js'],
    jshint: require('./grunt/config/jshint'),
    compare_size: require('./grunt/config/compare_size')
  });

  grunt.config.set('compress', require('./grunt/config/compress'));

  for (var key in grunt.file.readJSON("package.json").devDependencies) {
      if (key !== "grunt" && key.indexOf("grunt") === 0) grunt.loadNpmTasks(key);
  }

  // Alias 'jshint' to 'lint' to better match the workflow we know
  grunt.registerTask('lint', ['jshint']);

  // Register jsx:debug and :release tasks.
  grunt.registerMultiTask('jsx', jsxTask);

  // Our own browserify-based tasks to build a single JS file build
  grunt.registerMultiTask('browserify', browserifyTask);

  grunt.registerMultiTask('populist', populistTask);

  grunt.registerMultiTask('phantom', phantomTask);

  grunt.registerMultiTask('webdriver-jasmine', webdriverJasmineTasks);

  grunt.registerMultiTask('npm', npmTask);

  // Check that the version we're exporting is the same one we expect in the
  // package. This is not an ideal way to do this, but makes sure that we keep
  // them in sync.
  var reactVersionExp = /\bReact\.version\s*=\s*['"]([^'"]+)['"];/;
  grunt.registerTask('version-check', function() {
    var version = reactVersionExp.exec(
      grunt.file.read('./build/modules/React.js')
    )[1];
    var expectedVersion = grunt.config.data.pkg.version;
    if (version !== expectedVersion) {
      grunt.log.error('Versions do not match. Expected %s, saw %s', expectedVersion, version);
      return false;
    }
  });

  grunt.registerTask('build:basic', ['jsx:debug', 'version-check', 'browserify:basic']);
  grunt.registerTask('build:addons', ['jsx:debug', 'browserify:addons']);
  grunt.registerTask('build:transformer', ['jsx:debug', 'browserify:transformer']);
  grunt.registerTask('build:min', ['jsx:release', 'version-check', 'browserify:min']);
  grunt.registerTask('build:addons-min', ['jsx:debug', 'browserify:addonsMin']);
  grunt.registerTask('build:test', [
    'jsx:jasmine',
    'jsx:test',
    'version-check',
    'populist:test'
  ]);

  grunt.registerTask('test:webdriver', [
    'connect',
    'webdriver-jasmine:local'
  ]);
  grunt.registerTask('test', ['build:test', 'build:basic', 'phantom:run']);
  grunt.registerTask('npm:test', ['build', 'npm:pack']);

  // Optimized build task that does all of our builds. The subtasks will be run
  // in order so we can take advantage of that and only run jsx:debug once.
  grunt.registerTask('build', [
    'jsx:debug',
    'version-check',
    'browserify:basic',
    'browserify:transformer',
    'browserify:addons',
    'jsx:release',
    'browserify:min',
    'browserify:addonsMin',
    'copy:react_docs',
    'compare_size'
  ]);

  // Automate the release!
  grunt.registerTask('release:setup', releaseTasks.setup);
  grunt.registerTask('release:bower', releaseTasks.bower);
  grunt.registerTask('release:docs', releaseTasks.docs);
  grunt.registerTask('release:msg', releaseTasks.msg);
  grunt.registerTask('release:starter', releaseTasks.starter);

  grunt.registerTask('release', [
    'release:setup',
    'clean',
    'build',
    'gem:only',
    'release:bower',
    'release:starter',
    'compress',
    'release:docs',
    'release:msg'
  ]);

  // `gem` task to build the react-source gem
  grunt.registerTask('gem', ['build', 'gem:only']);

  grunt.registerTask('gem:only', function() {
    var done = this.async();
    exec('gem build react-source.gemspec', done);
  });

  // The default task - build - to keep setup easy
  grunt.registerTask('default', ['build']);
};
<|endoftext|>


<commit_before>/*global define*/
define(['../Core/DeveloperError'], function(DeveloperError) {
    "use strict";

    /**
     * DOC_TBA
     * @alias SpringForce
     * @constructor
     *
     * @param {Object} template
     *
     * @exception {DeveloperError} template.particleOne and template.particleTwo are required.
     */
    var SpringForce = function(template) {
        template = template || {};

        if (!template.particleOne || !template.particleTwo) {
            throw new DeveloperError('template.particleOne and template.particleTwo are required.');
        }

        this.particleOne = template.particleOne;
        this.particleTwo = template.particleTwo;

        // TODO: Throw if these are negative

        this.restLength = (typeof template.restLength === 'undefined') ? 1.0 : template.restLength;
        this.springConstant = (typeof template.springConstant === 'undefined') ? 1.0 : template.springConstant;
        this.dampingConstant = (typeof template.dampingConstant === 'undefined') ? 1.0 : template.dampingConstant;
    };

    /**
     * DOC_TBA
     * @memberof SpringForce
     */
    SpringForce.prototype.apply = function(particles) {
        // The entire list of particles is not needed.  The force on
        // each of the two particles connected by this spring is computed.

        // Hook's law:

        var a = this.particleOne;
        var b = this.particleTwo;
        var l = a.position.subtract(b.position); // vector from b to a
        var dl = a.velocity.subtract(b.velocity); // time derivative of l
        var ml = l.magnitude(); // magnitude of l
        var nl = l.divideByScalar(ml); // normalized l vector

        var s = this.springConstant * (ml - this.restLength); // spring force magnitude
        var d = this.dampingConstant * (dl.dot(l) / ml); // damping force magnitude

        var f = nl.multiplyWithScalar(-(s + d));

        // Apply equal and opposite forces
        a.force = a.force.add(f);
        b.force = b.force.add(f.negate());
    };

    return SpringForce;
});<commit_msg>Added missing @exports tag to SpringForce.<commit_after>/*global define*/
/**
 * @exports Scene/SpringForce
 */
define(['../Core/DeveloperError'], function(DeveloperError) {
    "use strict";

    /**
     * DOC_TBA
     * @alias SpringForce
     * @constructor
     *
     * @param {Object} template
     *
     * @exception {DeveloperError} template.particleOne and template.particleTwo are required.
     */
    var SpringForce = function(template) {
        template = template || {};

        if (!template.particleOne || !template.particleTwo) {
            throw new DeveloperError('template.particleOne and template.particleTwo are required.');
        }

        this.particleOne = template.particleOne;
        this.particleTwo = template.particleTwo;

        // TODO: Throw if these are negative

        this.restLength = (typeof template.restLength === 'undefined') ? 1.0 : template.restLength;
        this.springConstant = (typeof template.springConstant === 'undefined') ? 1.0 : template.springConstant;
        this.dampingConstant = (typeof template.dampingConstant === 'undefined') ? 1.0 : template.dampingConstant;
    };

    /**
     * DOC_TBA
     * @memberof SpringForce
     */
    SpringForce.prototype.apply = function(particles) {
        // The entire list of particles is not needed.  The force on
        // each of the two particles connected by this spring is computed.

        // Hook's law:

        var a = this.particleOne;
        var b = this.particleTwo;
        var l = a.position.subtract(b.position); // vector from b to a
        var dl = a.velocity.subtract(b.velocity); // time derivative of l
        var ml = l.magnitude(); // magnitude of l
        var nl = l.divideByScalar(ml); // normalized l vector

        var s = this.springConstant * (ml - this.restLength); // spring force magnitude
        var d = this.dampingConstant * (dl.dot(l) / ml); // damping force magnitude

        var f = nl.multiplyWithScalar(-(s + d));

        // Apply equal and opposite forces
        a.force = a.force.add(f);
        b.force = b.force.add(f.negate());
    };

    return SpringForce;
});<|endoftext|>


<commit_before>import React, { Component } from 'react';
import propTypes from 'prop-types';
import hoistNonReactStatic from 'hoist-non-react-statics';

const atlas = (atlasRequestDescription, { options = {}, propName = 'request', auto = true } = {}) => (TargetComponent) => {
  class AtlasConnectedComponent extends Component {
    constructor(props, context) {
      super(props, context);
      this.state = {
        loading: auto,
        data: null,
        error: null,
      };
    }

    buildOptions() {
      if (typeof options === 'function') {
        return options(this.props);
      }
      return options;
    }

    fetchData(fetchOptions = {}) {
      const { client } = this.context;
      const finalOptions = {
        ...this.buildOptions(),
        ...fetchOptions,
      };
      this.setState({
        loading: true,
        data: null,
        error: null,
      });
      client.fetch(atlasRequestDescription, finalOptions)
      .then(
        response => this.setState({
          loading: false,
          data: response,
          error: null,
        }),
      )
      .catch(
        err => this.setState({
          loading: false,
          data: null,
          error: err,
        }),
      );
    }

    componentDidMount() {
      if (auto) {
        this.fetchData();
      }
    }

    render() {
      const props = {...this.props};
      props[propName] = {
        ...this.state,
        fetchData: this.fetchData,
      };
      return <TargetComponent {...props} />;
    }
  }

  AtlasConnectedComponent.contextTypes = {
    client: propTypes.object.isRequired,
  };

  hoistNonReactStatic(AtlasConnectedComponent, TargetComponent);

  return AtlasConnectedComponent;
}

export default atlas;
<commit_msg>add bindings<commit_after>import React, { Component } from 'react';
import propTypes from 'prop-types';
import hoistNonReactStatic from 'hoist-non-react-statics';

const atlas = (atlasRequestDescription, { options = {}, propName = 'request', auto = true } = {}) => (TargetComponent) => {
  class AtlasConnectedComponent extends Component {
    constructor(props, context) {
      super(props, context);
      this.state = {
        loading: auto,
        data: null,
        error: null,
      };

      this.buildOptions = this.buildOptions.bind(this);
      this.fetchData = this.fetchData.bind(this);
    }

    buildOptions() {
      if (typeof options === 'function') {
        return options(this.props);
      }
      return options;
    }

    fetchData(fetchOptions = {}) {
      const { client } = this.context;
      const finalOptions = {
        ...this.buildOptions(),
        ...fetchOptions,
      };
      this.setState({
        loading: true,
        data: null,
        error: null,
      });
      client.fetch(atlasRequestDescription, finalOptions)
      .then(
        response => this.setState({
          loading: false,
          data: response,
          error: null,
        }),
      )
      .catch(
        err => this.setState({
          loading: false,
          data: null,
          error: err,
        }),
      );
    }

    componentDidMount() {
      if (auto) {
        this.fetchData();
      }
    }

    render() {
      const props = {...this.props};
      props[propName] = {
        ...this.state,
        fetchData: this.fetchData,
      };
      return <TargetComponent {...props} />;
    }
  }

  AtlasConnectedComponent.contextTypes = {
    client: propTypes.object.isRequired,
  };

  hoistNonReactStatic(AtlasConnectedComponent, TargetComponent);

  return AtlasConnectedComponent;
}

export default atlas;
<|endoftext|>


<commit_before>/* Source: http://gruntjs.com/sample-gruntfile  */
module.exports = function(grunt){
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        //define a string to put between each file in the concatenated output
        separator: ';'
      },
      dist: {
        //the files to concatenate
        src: ['src/**/*.js'],
        //the location of the resulting JS file
        dest: 'dist/<%= pkg.name %>.js'
      }
    },
    uglify: {
      options: {
        //the banner is inserted at the top of the output
        banner: '/*! <%= pkg.author %> <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        files: {
          'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
        }
      }
    },
    jshint: {
      //define the files to lint
      files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js', 'test/**/*.spec.js', 'package.json'],
      //configure JSHint
      options: {
        //more options here if you want to override JSHint defaults
        globals: {
          jQuery: true,
          console: true,
          module: true
        }
      }
    },
    watch: {
      files: ['<%= jshint.files %>'],
      tasks: ['jshint']
    },
    mochaTest: {
      test: {
        options: {
          reporter: 'spec'
        },
        src: ['test/**/*.js']
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-mocha-test');

  //this would be run by typing "grunt test" on the command line
  grunt.registerTask('test', ['jshint']);
  //the default task can be run just by typing "grunt" on the command line
  grunt.registerTask('default', ['jshint', 'mochaTest', 'concat', 'uglify']);

};
<commit_msg>Comment test grunt task<commit_after>/* Source: http://gruntjs.com/sample-gruntfile  */
module.exports = function(grunt){
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concat: {
      options: {
        //define a string to put between each file in the concatenated output
        separator: ';'
      },
      dist: {
        //the files to concatenate
        src: ['src/**/*.js'],
        //the location of the resulting JS file
        dest: 'dist/<%= pkg.name %>.js'
      }
    },
    uglify: {
      options: {
        //the banner is inserted at the top of the output
        banner: '/*! <%= pkg.author %> <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        files: {
          'dist/<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
        }
      }
    },
    jshint: {
      //define the files to lint
      files: ['Gruntfile.js', 'src/**/*.js', 'test/**/*.js', 'test/**/*.spec.js', 'package.json'],
      //configure JSHint
      options: {
        //more options here if you want to override JSHint defaults
        globals: {
          jQuery: true,
          console: true,
          module: true
        }
      }
    },
    watch: {
      files: ['<%= jshint.files %>'],
      tasks: ['jshint']
    },
    mochaTest: {
      test: {
        options: {
          reporter: 'spec'
        },
        src: ['test/**/*.js']
      }
    }
  });

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-contrib-jshint');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-mocha-test');

  //this would be run by typing "grunt test" on the command line
  //grunt.registerTask('test', ['jshint']);
  //the default task can be run just by typing "grunt" on the command line
  grunt.registerTask('default', ['jshint', 'mochaTest', 'concat', 'uglify']);

};
<|endoftext|>