<commit_before>#!/usr/bin/env node

var nopt = require('nopt'),
    path = require('path'),
    fs = require('fs'),
    chokidar = require('chokidar');

var eustia = require('../index'),
    logger = require('../lib/logger'),
    util = require('../lib/util');

var knowOpts = {
        encoding: String,
        extension: Array,
        output: String,
        update: Boolean,
        namespace: String,
        ignore: Array,
        keyword: String,
        library: Array,
        exclude: Array,
        include: Array,
        format: String,
        title: String,
        watch: Boolean,
        debug: Boolean,
        description: String
    },
    shortHands = {
        o: '--output',
        i: '--include',
        k: '--keyword',
        l: '--library',
        e: '--exclude',
        n: '--namespace',
        f: '--format',
        t: '--title',
        w: '--watch',
        u: '--update',
        d: '--description'
    },
    options = nopt(knowOpts, shortHands, process.argv, 2),
    remain = options.argv.remain;

logger.enable();
options.enableLog = true;
options.errLog = true;

var cmd = getCmd();
cmd ? useCmdLine() : useCfg();

function getCmd()
{
    var i, len, ret;

    for (i = 0, len = remain.length; i < len; i++)
    {
        if (util.has(eustia, remain[i]))
        {
            ret = remain[i];
            remain.splice(i, 1);
            break;
        }
    }

    return ret;
}

function useCfg()
{
    var cfgPath = path.resolve(process.cwd(), '.eustia');

    fs.exists(cfgPath, function (exists)
    {
        if (exists)
        {
            logger.tpl({data: cfgPath}, 'CONFIGURATION FILE {{#cyan}}{{{data}}}{{/cyan}}');

            return fs.readFile(cfgPath, 'utf-8', function (err, data)
            {
                var configs;

                try {
                    configs = JSON.parse(data);
                } catch (e)
                {
                    configs = require(cfgPath);
                }

                var isSingle = util.some(configs, function (option)
                {
                    return !util.isObj(option);
                });
                if (isSingle)
                {
                    util.extend(configs, options);
                    return eustia.build(configs);
                }

                buildAll(configs);
            });
        }

        eustia.help(options);
    });
}

function useCmdLine()
{
    var hasRemain = !util.isEmpty(remain);

    switch (cmd)
    {
        case 'build': options.files = remain; break;
        case 'search':
            if (hasRemain) options.keyword = remain[0];
            break;
        case 'help':
            if (hasRemain) options.command = remain[0];
            break;
        case 'doc':
            if (hasRemain) options.input = remain[0];
            break;
        case 'install': options.modules = remain; break;
        case 'cache':
            if (hasRemain) options.subCmd = remain[0];
            break;
    }

    eustia[cmd](options);
}

function buildAll(configs)
{
    var isTaskSpecified = remain.length > 0 && configs[remain[0]];

    if (isTaskSpecified)
    {
        logger.tpl({}, 'Run task {{#cyan}}"' + remain[0] + '"{{/cyan}}:');

        return eustia['build'](util.extend(configs[remain[0]], options));
    }

    var cfgArr = [],
        watch = options.watch;
    options.watch = false;

    util.each(configs, function (val, key)
    {
        val.taskName = key;
        cfgArr.push(val);
        configs[key] = util.extend(val, options);
    });

    var cfgLen = cfgArr.length, i = 0;

    function build(config, isWatching)
    {
        logger.tpl({}, 'Run task {{#cyan}}"' + config.taskName + '"{{/cyan}}:');

        eustia.build(config, function ()
        {
            if (++i < cfgLen) return build(cfgArr[i], isWatching);

            if (!isWatching && watch) beginWatch();
        });
    }
    build(cfgArr[i]);

    /* Watching files with multiple tasks, the log will be mixed together.
     * That's why we need to extract another watch code here.
     */
    function beginWatch()
    {
        var watchPaths = [], outputs = [];

        util.each(cfgArr, function (config)
        {
            outputs = outputs.concat(config.output);
            watchPaths = watchPaths.concat(config.files);
            watchPaths = watchPaths.concat(config.libPaths);
        });

        chokidar.watch(watchPaths, {
            persistent: true,
            ignored: outputs,
            ignoreInitial : true,
            followSymlinks: true,
            usePolling: true,
            alwaysStat: false,
            interval: 100,
            atomic: true,
            ignorePermissionErrors: false
        }).on('change', function ()
        {
            i = 0;
            build(cfgArr[i], true);
        });
    }
}

<commit_msg>Add: Config option<commit_after>#!/usr/bin/env node

var nopt = require('nopt'),
    path = require('path'),
    fs = require('fs'),
    chokidar = require('chokidar');

var eustia = require('../index'),
    logger = require('../lib/logger'),
    util = require('../lib/util');

var knowOpts = {
        encoding: String,
        extension: Array,
        output: String,
        update: Boolean,
        namespace: String,
        ignore: Array,
        keyword: String,
        library: Array,
        exclude: Array,
        include: Array,
        format: String,
        title: String,
        config: String,
        watch: Boolean,
        debug: Boolean,
        description: String
    },
    shortHands = {
        o: '--output',
        i: '--include',
        k: '--keyword',
        l: '--library',
        e: '--exclude',
        n: '--namespace',
        f: '--format',
        t: '--title',
        w: '--watch',
        u: '--update',
        c: '--config',
        d: '--description'
    },
    options = nopt(knowOpts, shortHands, process.argv, 2),
    remain = options.argv.remain;

logger.enable();
options.enableLog = true;
options.errLog = true;

var cmd = getCmd();
cmd ? useCmdLine() : useCfg();

function getCmd()
{
    var i, len, ret;

    for (i = 0, len = remain.length; i < len; i++)
    {
        if (util.has(eustia, remain[i]))
        {
            ret = remain[i];
            remain.splice(i, 1);
            break;
        }
    }

    return ret;
}

function useCfg()
{
    var cfgPath = path.resolve(process.cwd(), options.config || '.eustia');

    fs.exists(cfgPath, function (exists)
    {
        if (exists)
        {
            logger.tpl({data: cfgPath}, 'CONFIGURATION FILE {{#cyan}}{{{data}}}{{/cyan}}');

            return fs.readFile(cfgPath, 'utf-8', function (err, data)
            {
                var configs;

                try {
                    configs = JSON.parse(data);
                } catch (e)
                {
                    configs = require(cfgPath);
                }

                var isSingle = util.some(configs, function (option)
                {
                    return !util.isObj(option);
                });
                if (isSingle)
                {
                    util.extend(configs, options);
                    return eustia.build(configs);
                }

                buildAll(configs);
            });
        }

        eustia.help(options);
    });
}

function useCmdLine()
{
    var hasRemain = !util.isEmpty(remain);

    switch (cmd)
    {
        case 'build': options.files = remain; break;
        case 'search':
            if (hasRemain) options.keyword = remain[0];
            break;
        case 'help':
            if (hasRemain) options.command = remain[0];
            break;
        case 'doc':
            if (hasRemain) options.input = remain[0];
            break;
        case 'install': options.modules = remain; break;
        case 'cache':
            if (hasRemain) options.subCmd = remain[0];
            break;
    }

    eustia[cmd](options);
}

function buildAll(configs)
{
    var isTaskSpecified = remain.length > 0 && configs[remain[0]];

    if (isTaskSpecified)
    {
        logger.tpl({}, 'Run task {{#cyan}}"' + remain[0] + '"{{/cyan}}:');

        return eustia['build'](util.extend(configs[remain[0]], options));
    }

    var cfgArr = [],
        watch = options.watch;
    options.watch = false;

    util.each(configs, function (val, key)
    {
        val.taskName = key;
        cfgArr.push(val);
        configs[key] = util.extend(val, options);
    });

    var cfgLen = cfgArr.length, i = 0;

    function build(config, isWatching)
    {
        logger.tpl({}, 'Run task {{#cyan}}"' + config.taskName + '"{{/cyan}}:');

        eustia.build(config, function ()
        {
            if (++i < cfgLen) return build(cfgArr[i], isWatching);

            if (!isWatching && watch) beginWatch();
        });
    }
    build(cfgArr[i]);

    /* Watching files with multiple tasks, the log will be mixed together.
     * That's why we need to extract another watch code here.
     */
    function beginWatch()
    {
        var watchPaths = [], outputs = [];

        util.each(cfgArr, function (config)
        {
            outputs = outputs.concat(config.output);
            watchPaths = watchPaths.concat(config.files);
            watchPaths = watchPaths.concat(config.libPaths);
        });

        chokidar.watch(watchPaths, {
            persistent: true,
            ignored: outputs,
            ignoreInitial : true,
            followSymlinks: true,
            usePolling: true,
            alwaysStat: false,
            interval: 100,
            atomic: true,
            ignorePermissionErrors: false
        }).on('change', function ()
        {
            i = 0;
            build(cfgArr[i], true);
        });
    }
}

<|endoftext|>


<commit_before>import { Meteor }             from 'meteor/meteor';
import { check }              from 'meteor/check';
import { ImportedItems }      from '../imported_items';
import { ImportedItemCrumbs } from '../imported_item_crumbs';

Meteor.publish('integration_imported_items', function (integrationId, start, limit) {
  console.log('Publish: integration_imported_items', integrationId, start, limit);
  if (this.userId) {
    check(integrationId, String);
    start = start || 0;
    limit = limit || 100;
    return ImportedItems.find({ integrationId: integrationId }, {
      limit: limit,
      skip : start
    });
  } else {
    this.ready();
    return [];
  }
});

Meteor.publish('integration_imported_item_crumbs', function (integrationId) {
  console.log('Publish: integration_imported_item_crumbs', integrationId);
  if (this.userId && integrationId) {
    return ImportedItemCrumbs.find({ integrationId: integrationId });
  } else {
    this.ready();
    return [];
  }
});

Meteor.publish('imported_item_query', function (query, options) {
  console.log('Publish: imported_item_query');
  if (this.userId && query && _.isObject(query)) {
    return ImportedItems.find(query, options);
  } else {
    this.ready();
    return [];
  }
});

Meteor.publish('imported_item_crumb_query', function (query) {
  console.log('Publish: imported_item_crumb_query');
  if (this.userId && query && _.isObject(query)) {
    return ImportedItemCrumbs.find(query);
  } else {
    this.ready();
    return [];
  }
});

Meteor.publish('team_imported_item_crumbs', function (teamId) {
  console.log('Publish: team_imported_item_crumbs', teamId);
  if (this.userId && teamId) {
    return ImportedItemCrumbs.find({ teamId: teamId });
  } else {
    this.ready();
    return [];
  }
});

Meteor.publish('integration_imported_item_count', function (integrationId) {
  console.log('Publish: integration_imported_item_count', integrationId);

  if (!this.userId) {
    this.ready();
    return [];
  }

  let self         = this,
      count        = 0,
      initializing = true,
      handle       = ImportedItems.find({ integrationId: integrationId }).observeChanges({
        added  : function (id) {
          count++;
          if (!initializing) {
            self.changed('imported_item_counts', integrationId, { count: count });
          }
        },
        removed: function (id) {
          count--;
          self.changed('imported_item_counts', integrationId, { count: count });
        }
      });

  initializing = false;
  self.added('imported_item_counts', integrationId, { count: count });
  self.ready();

  self.onStop(function () {
    handle.stop();
  });
});<commit_msg>Added a publication for a single imported item<commit_after>import { Meteor }             from 'meteor/meteor';
import { check }              from 'meteor/check';
import { ImportedItems }      from '../imported_items';
import { ImportedItemCrumbs } from '../imported_item_crumbs';

Meteor.publish('integration_imported_items', function (integrationId, start, limit) {
  console.log('Publish: integration_imported_items', integrationId, start, limit);
  if (this.userId) {
    check(integrationId, String);
    start = start || 0;
    limit = limit || 100;
    return ImportedItems.find({ integrationId: integrationId }, {
      limit: limit,
      skip : start
    });
  } else {
    this.ready();
    return []
  }
});

Meteor.publish('integration_imported_item_crumbs', function (integrationId) {
  console.log('Publish: integration_imported_item_crumbs', integrationId);
  if (this.userId && integrationId) {
    return ImportedItemCrumbs.find({ integrationId: integrationId });
  } else {
    this.ready();
    return []
  }
});

Meteor.publish('imported_item', function (itemId) {
  console.log('Publish: imported_item', itemId);
  if (this.userId && itemId) {
    return ImportedItems.find({ _id: itemId })
  } else {
    this.ready();
    return []
  }
});

Meteor.publish('imported_item_query', function (query, options) {
  console.log('Publish: imported_item_query');
  if (this.userId && query && _.isObject(query)) {
    return ImportedItems.find(query, options);
  } else {
    this.ready();
    return []
  }
});

Meteor.publish('imported_item_crumb_query', function (query) {
  console.log('Publish: imported_item_crumb_query');
  if (this.userId && query && _.isObject(query)) {
    return ImportedItemCrumbs.find(query);
  } else {
    this.ready();
    return []
  }
});

Meteor.publish('team_imported_item_crumbs', function (teamId) {
  console.log('Publish: team_imported_item_crumbs', teamId);
  if (this.userId && teamId) {
    return ImportedItemCrumbs.find({ teamId: teamId });
  } else {
    this.ready();
    return []
  }
});

Meteor.publish('integration_imported_item_count', function (integrationId) {
  console.log('Publish: integration_imported_item_count', integrationId);

  if (!this.userId) {
    this.ready();
    return []
  }

  let self         = this,
      count        = 0,
      initializing = true,
      handle       = ImportedItems.find({ integrationId: integrationId }).observeChanges({
        added  : function (id) {
          count++;
          if (!initializing) {
            self.changed('imported_item_counts', integrationId, { count: count });
          }
        },
        removed: function (id) {
          count--;
          self.changed('imported_item_counts', integrationId, { count: count });
        }
      });

  initializing = false;
  self.added('imported_item_counts', integrationId, { count: count });
  self.ready();

  self.onStop(function () {
    handle.stop();
  });
});<|endoftext|>


<commit_before>/*jslint browser: true, for: true */
/*global dashjs, flowplayer, MediaPlayer, window */

/*!

   MPEG-DASH engine plugin for Flowplayer HTML5

   Copyright (c) 2015-2016, Flowplayer Oy

   Released under the MIT License:
   http://www.opensource.org/licenses/mit-license.php

   Includes hls.js
   Copyright (c) 2015 Dailymotion (http://www.dailymotion.com)
   https://github.com/dailymotion/hls.js/blob/master/LICENSE

   Includes es5.js
   https://github.com/inexorabletash/polyfill/blob/master/es5.js
   for compatibility with legacy browsers

   Requires Flowplayer HTML5 version 6.x
   $GIT_DESC$

*/
(function () {
    "use strict";
    var extension = function (dashjs, flowplayer) {
        var engineName = "dash",
            mse = window.MediaSource || window.WebKitMediaSource,
            common = flowplayer.common,
            extend = flowplayer.extend,
            version = flowplayer.version,
            coreV6 = version.indexOf("6.") === 0,
            dashconf,

            dashCanPlay = function (sourceType, dashType, dashCodecs) {
                return sourceType.toLowerCase() === "application/dash+xml" &&
                        mse.isTypeSupported(dashType + ';codecs="' + dashCodecs + '"') &&
                        // Android MSE advertises he-aac, but fails
                        (dashCodecs.indexOf("mp4a.40.5") < 0 || navigator.userAgent.indexOf("Android") < 0);
            },

            engineImpl = function dashjsEngine(player, root) {
                var bean = flowplayer.bean,
                    mediaPlayer,
                    videoTag,
                    bc,
                    has_bg,

                    engine = {
                        engineName: engineName,

                        pick: function (sources) {
                            var i,
                                source,
                                dashType,
                                dashCodecs;

                            for (i = 0; i < sources.length; i += 1) {
                                source = sources[i];
                                dashType = source.dashType || dashconf.type;
                                dashCodecs = source.dashCodecs || dashconf.codecs;
                                if (dashCanPlay(source.type, dashType, dashCodecs)) {
                                    if (typeof source.src === 'string') {
                                        source.src = common.createAbsoluteUrl(source.src);
                                    }
                                    return source;
                                }
                            }
                        },

                        load: function (video) {
                            var conf = player.conf,
                                dashUpdatedConf = extend(dashconf, conf.dash, conf.clip.dash),
                                EVENTS = {
                                    ended: "finish",
                                    loadeddata: "ready",
                                    pause: "pause",
                                    play: "resume",
                                    progress: "buffer",
                                    ratechange: "speed",
                                    seeked: "seek",
                                    timeupdate: "progress",
                                    volumechange: "volume"
                                },
                                DASHEVENTS = dashjs.MediaPlayer.events,
                                autoplay = !!video.autoplay || !!conf.autoplay,
                                posterClass = "is-poster",
                                livestartpos = 0;

                            if (!mediaPlayer) {
                                common.removeNode(common.findDirect("video", root)[0]
                                        || common.find(".fp-player > video", root)[0]);
                                // dash.js enforces preload="auto" and
                                // autoplay depending on initialization
                                // so setting the attributes here will have no effect
                                videoTag = common.createElement("video", {
                                    "class": "fp-engine " + engineName + "-engine",
                                    "volume": player.volumeLevel,
                                    "x-webkit-airplay": "allow"
                                });

                                Object.keys(EVENTS).forEach(function (key) {
                                    var flow = EVENTS[key],
                                        type = key + "." + engineName,
                                        arg;

                                    bean.on(videoTag, type, function (e) {
                                        if (conf.debug && flow.indexOf("progress") < 0) {
                                            console.log(type, "->", flow, e.originalEvent);
                                        }

                                        var ct = videoTag.currentTime,
                                            buffer = 0,
                                            buffend = 0,
                                            buffered,
                                            i;

                                        switch (flow) {
                                        case "ready":
                                            arg = extend(player.video, {
                                                duration: mediaPlayer.duration(),
                                                seekable: videoTag.seekable.end(null),
                                                width: videoTag.videoWidth,
                                                height: videoTag.videoHeight,
                                                url: player.video.src
                                            });
                                            break;
                                        case "resume":
                                            if (coreV6 && player.poster) {
                                                common.removeClass(root, posterClass);
                                                player.poster = false;
                                            }
                                            break;
                                        case "seek":
                                            arg = mediaPlayer.time();
                                            break;
                                        case "progress":
                                            if (player.live && !livestartpos && ct > 0) {
                                                livestartpos = ct;
                                            }
                                            arg = !player.live
                                                ? ct
                                                : livestartpos
                                                    ? ct - livestartpos
                                                    : 0;
                                            break;
                                        case "speed":
                                            arg = videoTag.playbackRate;
                                            break;
                                        case "volume":
                                            arg = videoTag.volume;
                                            break;
                                        case "buffer":
                                            try {
                                                // cycle through time ranges to obtain buffer
                                                // nearest current time
                                                if (ct) {
                                                    buffered = videoTag.buffered;
                                                    for (i = buffered.length - 1; i > -1; i -= 1) {
                                                        buffend = buffered.end(i);

                                                        if (buffend >= ct) {
                                                            buffer = buffend;
                                                        }
                                                    }
                                                }
                                            } catch (ignore) {}
                                            video.buffer = buffer;
                                            arg = buffer;
                                            break;
                                        }

                                        player.trigger(flow, [player, arg]);
                                    });
                                });

                                if (coreV6 && conf.poster) {
                                    var posterHack = function (e) {
                                        if (e.type === "stop" || !autoplay) {
                                            setTimeout(function () {
                                                if (!player.poster) {
                                                    common.addClass(root, posterClass);
                                                    player.poster = true;
                                                }
                                            });
                                        }
                                    };

                                    player.one("ready." + engineName, posterHack).on("stop." + engineName, posterHack);
                                }
                                player.on("error." + engineName, function () {
                                    if (mediaPlayer) {
                                        mediaPlayer.reset();
                                        mediaPlayer = 0;
                                    }
                                });

                                mediaPlayer = dashjs.MediaPlayer().create();
                                player.engine[engineName] = mediaPlayer;

                                // new ABR algo
                                mediaPlayer.enableBufferOccupancyABR(dashUpdatedConf.bufferOccupancyABR);
                                // caching can cause failures in playlists
                                // for the moment disable entirely
                                mediaPlayer.enableLastBitrateCaching(false);
                                // for seeking in paused state
                                mediaPlayer.setScheduleWhilePaused(true);
                                mediaPlayer.getDebug().setLogToBrowserConsole(dashUpdatedConf.debug);

                                Object.keys(DASHEVENTS).forEach(function (key) {
                                    var etype = DASHEVENTS[key],
                                        fpEventType = engineName + etype.charAt(0).toUpperCase() + etype.slice(1),
                                        listeners = dashUpdatedConf.listeners,
                                        expose = listeners && listeners.indexOf(fpEventType) > -1;

                                    mediaPlayer.on(etype, function (e) {
                                        var data = extend({}, e),
                                            src = player.video.src,
                                            fperr,
                                            errobj;

                                        delete data.type;
                                        switch (key) {
                                        case "ERROR":
                                            switch (data.error) {
                                            case "download":
                                                fperr = 4;
                                                break;
                                            case "manifestError":
                                                fperr = 5;
                                                break;
                                            case "mediasource":
                                                switch (e.event) {
                                                case "MEDIA_ERR_DECODE":
                                                    fperr = 3;
                                                    break;
                                                case "MEDIA_ERR_SRC_NOT_SUPPORTED":
                                                    fperr = 5;
                                                    break;
                                                case "MEDIA_ERR_NETWORK":
                                                    fperr = 2;
                                                    break;
                                                case "MEDIA_ERR_ABORTED":
                                                    fperr = 1;
                                                    break;
                                                }
                                                break;
                                            }
                                            if (fperr) {
                                                errobj = {code: fperr};
                                                if (fperr > 2) {
                                                    errobj.video = extend(video, {
                                                        src: src,
                                                        url: data.event.url || src
                                                    });
                                                }
                                                player.trigger('error', [player, errobj]);
                                                return;
                                            }
                                            break;
                                        }

                                        if (expose) {
                                            player.trigger(fpEventType, [player, data]);
                                        }
                                    });
                                });

                                common.prepend(common.find(".fp-player", root)[0], videoTag);
                                mediaPlayer.initialize(videoTag, video.src, autoplay);

                            } else {
                                if ((player.video.src && video.src !== player.video.src) || video.index) {
                                    mediaPlayer.setAutoPlay(true);
                                }
                                mediaPlayer.attachSource(video.src);

                            }

                            // update video object before ready
                            player.video = video;

                            // devices not allowing autoplay:
                            // detect videoTag.paused and nudge videoTag
                            // to avoid complaint about lacking user gesture
                            // before initializing dashjs playback
                            if (videoTag.paused && autoplay) {
                                if (flowplayer.support.firstframe) {
                                    mediaPlayer.play();
                                } else {
                                    videoTag.play();
                                    videoTag.pause();
                                    mediaPlayer.play();
                                }
                            }
                        },

                        resume: function () {
                            mediaPlayer.play();
                        },

                        pause: function () {
                            mediaPlayer.pause();
                        },

                        seek: function (time) {
                            mediaPlayer.seek(time);
                        },

                        volume: function (level) {
                            if (videoTag) {
                                videoTag.volume = level;
                            }
                        },

                        speed: function (val) {
                            videoTag.playbackRate = val;
                            player.trigger('speed', [player, val]);
                        },

                        unload: function () {
                            if (mediaPlayer) {
                                var listeners = "." + engineName;

                                mediaPlayer.reset();
                                mediaPlayer = 0;
                                player.off(listeners);
                                bean.off(root, listeners);
                                bean.off(videoTag, listeners);
                                common.removeNode(videoTag);
                                videoTag = 0;
                            }
                        }
                    };

                // pre 6.0.4: no boolean api.conf.poster and no poster with autoplay
                if (/^6\.0\.[0-3]$/.test(version) &&
                        !player.conf.splash && !player.conf.poster && !player.conf.autoplay) {
                    bc = common.css(root, 'backgroundColor');
                    // spaces in rgba arg mandatory for recognition
                    has_bg = common.css(root, 'backgroundImage') !== "none" ||
                            (bc && bc !== "rgba(0, 0, 0, 0)" && bc !== "transparent");
                    if (has_bg) {
                        player.conf.poster = true;
                    }
                }

                return engine;
            };

        if (mse && typeof mse.isTypeSupported === "function" && version.indexOf("5.") !== 0) {
            // only load engine if it can be used
            engineImpl.engineName = engineName; // must be exposed
            engineImpl.canPlay = function (type, conf) {
                /*
                  WARNING: MediaSource.isTypeSupported very inconsistent!
                  e.g. Safari ignores codecs entirely, even bogus, like codecs="XYZ"
                  example avc3 main level 3.1 + aac_he: avc3.4d401f; mp4a.40.5
                  example avc1 high level 4.1 + aac_lc: avc1.640029; mp4a.40.2
                  default: avc1 baseline level 3.0 + aac_lc
                */
                // inject dash conf at earliest opportunity
                dashconf = extend({
                    type: "video/mp4",
                    codecs: "avc1.42c01e,mp4a.40.2"
                }, flowplayer.conf[engineName], conf[engineName], conf.clip[engineName]);

                return dashCanPlay(type, dashconf.type, dashconf.codecs);
            };

            // put on top of engine stack
            // so mpegedash is tested before html5
            flowplayer.engines.unshift(engineImpl);

        }

    };
    if (typeof module === 'object' && module.exports) {
        module.exports = extension.bind(undefined, require('dashjs'));
    } else if (window.dashjs && window.flowplayer) {
        extension(window.dashjs, window.flowplayer);
    }
}());
<commit_msg>Ensure substituted video tag is dead<commit_after>/*jslint browser: true, for: true */
/*global dashjs, flowplayer, MediaPlayer, window */

/*!

   MPEG-DASH engine plugin for Flowplayer HTML5

   Copyright (c) 2015-2016, Flowplayer Oy

   Released under the MIT License:
   http://www.opensource.org/licenses/mit-license.php

   Includes hls.js
   Copyright (c) 2015 Dailymotion (http://www.dailymotion.com)
   https://github.com/dailymotion/hls.js/blob/master/LICENSE

   Includes es5.js
   https://github.com/inexorabletash/polyfill/blob/master/es5.js
   for compatibility with legacy browsers

   Requires Flowplayer HTML5 version 6.x
   $GIT_DESC$

*/
(function () {
    "use strict";
    var extension = function (dashjs, flowplayer) {
        var engineName = "dash",
            mse = window.MediaSource || window.WebKitMediaSource,
            common = flowplayer.common,
            extend = flowplayer.extend,
            version = flowplayer.version,
            coreV6 = version.indexOf("6.") === 0,
            dashconf,

            dashCanPlay = function (sourceType, dashType, dashCodecs) {
                return sourceType.toLowerCase() === "application/dash+xml" &&
                        mse.isTypeSupported(dashType + ';codecs="' + dashCodecs + '"') &&
                        // Android MSE advertises he-aac, but fails
                        (dashCodecs.indexOf("mp4a.40.5") < 0 || navigator.userAgent.indexOf("Android") < 0);
            },

            engineImpl = function dashjsEngine(player, root) {
                var bean = flowplayer.bean,
                    mediaPlayer,
                    videoTag,
                    bc,
                    has_bg,

                    engine = {
                        engineName: engineName,

                        pick: function (sources) {
                            var i,
                                source,
                                dashType,
                                dashCodecs;

                            for (i = 0; i < sources.length; i += 1) {
                                source = sources[i];
                                dashType = source.dashType || dashconf.type;
                                dashCodecs = source.dashCodecs || dashconf.codecs;
                                if (dashCanPlay(source.type, dashType, dashCodecs)) {
                                    if (typeof source.src === 'string') {
                                        source.src = common.createAbsoluteUrl(source.src);
                                    }
                                    return source;
                                }
                            }
                        },

                        load: function (video) {
                            var conf = player.conf,
                                dashUpdatedConf = extend(dashconf, conf.dash, conf.clip.dash),
                                EVENTS = {
                                    ended: "finish",
                                    loadeddata: "ready",
                                    pause: "pause",
                                    play: "resume",
                                    progress: "buffer",
                                    ratechange: "speed",
                                    seeked: "seek",
                                    timeupdate: "progress",
                                    volumechange: "volume"
                                },
                                DASHEVENTS = dashjs.MediaPlayer.events,
                                autoplay = !!video.autoplay || !!conf.autoplay,
                                posterClass = "is-poster",
                                livestartpos = 0;

                            if (!mediaPlayer) {
                                videoTag = common.findDirect("video", root)[0]
                                        || common.find(".fp-player > video", root)[0];

                                if (videoTag) {
                                    // destroy video tag
                                    // otherwise <video autoplay> continues to play
                                    common.find("source", videoTag).forEach(function (source) {
                                        source.removeAttribute("src");
                                    });
                                    videoTag.removeAttribute("src");
                                    videoTag.load();
                                    common.removeNode(videoTag);
                                }

                                // dash.js enforces preload="auto" and
                                // autoplay depending on initialization
                                // so setting the attributes here will have no effect
                                videoTag = common.createElement("video", {
                                    "class": "fp-engine " + engineName + "-engine",
                                    "volume": player.volumeLevel,
                                    "x-webkit-airplay": "allow"
                                });

                                Object.keys(EVENTS).forEach(function (key) {
                                    var flow = EVENTS[key],
                                        type = key + "." + engineName,
                                        arg;

                                    bean.on(videoTag, type, function (e) {
                                        if (conf.debug && flow.indexOf("progress") < 0) {
                                            console.log(type, "->", flow, e.originalEvent);
                                        }

                                        var ct = videoTag.currentTime,
                                            buffer = 0,
                                            buffend = 0,
                                            buffered,
                                            i;

                                        switch (flow) {
                                        case "ready":
                                            arg = extend(player.video, {
                                                duration: mediaPlayer.duration(),
                                                seekable: videoTag.seekable.end(null),
                                                width: videoTag.videoWidth,
                                                height: videoTag.videoHeight,
                                                url: player.video.src
                                            });
                                            break;
                                        case "resume":
                                            if (coreV6 && player.poster) {
                                                common.removeClass(root, posterClass);
                                                player.poster = false;
                                            }
                                            break;
                                        case "seek":
                                            arg = mediaPlayer.time();
                                            break;
                                        case "progress":
                                            if (player.live && !livestartpos && ct > 0) {
                                                livestartpos = ct;
                                            }
                                            arg = !player.live
                                                ? ct
                                                : livestartpos
                                                    ? ct - livestartpos
                                                    : 0;
                                            break;
                                        case "speed":
                                            arg = videoTag.playbackRate;
                                            break;
                                        case "volume":
                                            arg = videoTag.volume;
                                            break;
                                        case "buffer":
                                            try {
                                                // cycle through time ranges to obtain buffer
                                                // nearest current time
                                                if (ct) {
                                                    buffered = videoTag.buffered;
                                                    for (i = buffered.length - 1; i > -1; i -= 1) {
                                                        buffend = buffered.end(i);

                                                        if (buffend >= ct) {
                                                            buffer = buffend;
                                                        }
                                                    }
                                                }
                                            } catch (ignore) {}
                                            video.buffer = buffer;
                                            arg = buffer;
                                            break;
                                        }

                                        player.trigger(flow, [player, arg]);
                                    });
                                });

                                if (coreV6 && conf.poster) {
                                    var posterHack = function (e) {
                                        if (e.type === "stop" || !autoplay) {
                                            setTimeout(function () {
                                                if (!player.poster) {
                                                    common.addClass(root, posterClass);
                                                    player.poster = true;
                                                }
                                            });
                                        }
                                    };

                                    player.one("ready." + engineName, posterHack).on("stop." + engineName, posterHack);
                                }
                                player.on("error." + engineName, function () {
                                    if (mediaPlayer) {
                                        mediaPlayer.reset();
                                        mediaPlayer = 0;
                                    }
                                });

                                mediaPlayer = dashjs.MediaPlayer().create();
                                player.engine[engineName] = mediaPlayer;

                                // new ABR algo
                                mediaPlayer.enableBufferOccupancyABR(dashUpdatedConf.bufferOccupancyABR);
                                // caching can cause failures in playlists
                                // for the moment disable entirely
                                mediaPlayer.enableLastBitrateCaching(false);
                                // for seeking in paused state
                                mediaPlayer.setScheduleWhilePaused(true);
                                mediaPlayer.getDebug().setLogToBrowserConsole(dashUpdatedConf.debug);

                                Object.keys(DASHEVENTS).forEach(function (key) {
                                    var etype = DASHEVENTS[key],
                                        fpEventType = engineName + etype.charAt(0).toUpperCase() + etype.slice(1),
                                        listeners = dashUpdatedConf.listeners,
                                        expose = listeners && listeners.indexOf(fpEventType) > -1;

                                    mediaPlayer.on(etype, function (e) {
                                        var data = extend({}, e),
                                            src = player.video.src,
                                            fperr,
                                            errobj;

                                        delete data.type;
                                        switch (key) {
                                        case "ERROR":
                                            switch (data.error) {
                                            case "download":
                                                fperr = 4;
                                                break;
                                            case "manifestError":
                                                fperr = 5;
                                                break;
                                            case "mediasource":
                                                switch (e.event) {
                                                case "MEDIA_ERR_DECODE":
                                                    fperr = 3;
                                                    break;
                                                case "MEDIA_ERR_SRC_NOT_SUPPORTED":
                                                    fperr = 5;
                                                    break;
                                                case "MEDIA_ERR_NETWORK":
                                                    fperr = 2;
                                                    break;
                                                case "MEDIA_ERR_ABORTED":
                                                    fperr = 1;
                                                    break;
                                                }
                                                break;
                                            }
                                            if (fperr) {
                                                errobj = {code: fperr};
                                                if (fperr > 2) {
                                                    errobj.video = extend(video, {
                                                        src: src,
                                                        url: data.event.url || src
                                                    });
                                                }
                                                player.trigger('error', [player, errobj]);
                                                return;
                                            }
                                            break;
                                        }

                                        if (expose) {
                                            player.trigger(fpEventType, [player, data]);
                                        }
                                    });
                                });

                                common.prepend(common.find(".fp-player", root)[0], videoTag);
                                mediaPlayer.initialize(videoTag, video.src, autoplay);

                            } else {
                                if ((player.video.src && video.src !== player.video.src) || video.index) {
                                    mediaPlayer.setAutoPlay(true);
                                }
                                mediaPlayer.attachSource(video.src);

                            }

                            // update video object before ready
                            player.video = video;

                            // devices not allowing autoplay:
                            // detect videoTag.paused and nudge videoTag
                            // to avoid complaint about lacking user gesture
                            // before initializing dashjs playback
                            if (videoTag.paused && autoplay) {
                                if (flowplayer.support.firstframe) {
                                    mediaPlayer.play();
                                } else {
                                    videoTag.play();
                                    videoTag.pause();
                                    mediaPlayer.play();
                                }
                            }
                        },

                        resume: function () {
                            mediaPlayer.play();
                        },

                        pause: function () {
                            mediaPlayer.pause();
                        },

                        seek: function (time) {
                            mediaPlayer.seek(time);
                        },

                        volume: function (level) {
                            if (videoTag) {
                                videoTag.volume = level;
                            }
                        },

                        speed: function (val) {
                            videoTag.playbackRate = val;
                            player.trigger('speed', [player, val]);
                        },

                        unload: function () {
                            if (mediaPlayer) {
                                var listeners = "." + engineName;

                                mediaPlayer.reset();
                                mediaPlayer = 0;
                                player.off(listeners);
                                bean.off(root, listeners);
                                bean.off(videoTag, listeners);
                                common.removeNode(videoTag);
                                videoTag = 0;
                            }
                        }
                    };

                // pre 6.0.4: no boolean api.conf.poster and no poster with autoplay
                if (/^6\.0\.[0-3]$/.test(version) &&
                        !player.conf.splash && !player.conf.poster && !player.conf.autoplay) {
                    bc = common.css(root, 'backgroundColor');
                    // spaces in rgba arg mandatory for recognition
                    has_bg = common.css(root, 'backgroundImage') !== "none" ||
                            (bc && bc !== "rgba(0, 0, 0, 0)" && bc !== "transparent");
                    if (has_bg) {
                        player.conf.poster = true;
                    }
                }

                return engine;
            };

        if (mse && typeof mse.isTypeSupported === "function" && version.indexOf("5.") !== 0) {
            // only load engine if it can be used
            engineImpl.engineName = engineName; // must be exposed
            engineImpl.canPlay = function (type, conf) {
                /*
                  WARNING: MediaSource.isTypeSupported very inconsistent!
                  e.g. Safari ignores codecs entirely, even bogus, like codecs="XYZ"
                  example avc3 main level 3.1 + aac_he: avc3.4d401f; mp4a.40.5
                  example avc1 high level 4.1 + aac_lc: avc1.640029; mp4a.40.2
                  default: avc1 baseline level 3.0 + aac_lc
                */
                // inject dash conf at earliest opportunity
                dashconf = extend({
                    type: "video/mp4",
                    codecs: "avc1.42c01e,mp4a.40.2"
                }, flowplayer.conf[engineName], conf[engineName], conf.clip[engineName]);

                return dashCanPlay(type, dashconf.type, dashconf.codecs);
            };

            // put on top of engine stack
            // so mpegedash is tested before html5
            flowplayer.engines.unshift(engineImpl);

        }

    };
    if (typeof module === 'object' && module.exports) {
        module.exports = extension.bind(undefined, require('dashjs'));
    } else if (window.dashjs && window.flowplayer) {
        extension(window.dashjs, window.flowplayer);
    }
}());
<|endoftext|>


<commit_before>(function() {
	VISAN.Plots.ParallelCoordinates = function(options, container, stepModule, visan) {
		var _ = this;

		this._padding = 25;

		this._stage = new Kinetic.Stage({
			container: container.get(0),
			width: options.width || 500,
			height: options.height || 500
		});

		this._shapeLayer = new Kinetic.Layer();
		this._stage.add(this._shapeLayer);

		this._options = options;
		this._stepModule = stepModule;

		this._scales = {};
		this._options.axes.forEach(function(axis) {
			var dim = stepModule._dataManager.getDimension(function(d) { return d[axis]; });
			var max = dim.top(1)[0][axis];
			var min = dim.bottom(1)[0][axis];
			_._scales[axis] = new VISAN.Scale({
				range: [_._stage.getHeight() - _._padding, _._padding],
				domain: [min, max],
				debug: true
			});
		});

		this.draw();
	};

	VISAN.Plots.ParallelCoordinates.renderPlotCreateOptions = function(optionsContainer) {
		optionsContainer.append($("<p />").text("Please select all the axes to display:"));
		optionsContainer.append($("<select />").addClass("parallel-coordinates-axes").addClass("axis").attr("multiple", "multiple").attr("size", 6));

		return function(plotOptions, optionsContainer) {
			var selected = optionsContainer.find("select.parallel-coordinates-axes").val();
			plotOptions.axes = selected;
		};
	};

	VISAN.Plots.ParallelCoordinates.prototype = {
		draw: function() {
			var _ = this;

			var dataManager = this._stepModule._dataManager;
			var axes = this._options.axes;
			var numberOfAxes = axes.length;

			// axis positions
			var padding = this._padding;
			var width = this._stage.getWidth();
			var posDelta = (width - 2 * padding) / (numberOfAxes - 1);

			this._shapeLayer.clear();
			var context = this._shapeLayer.getContext("2d");

			dataManager.getData().forEach(function(cur) {
				context.beginPath();
				axes.forEach(function(item, index) {
					var x = padding + index * posDelta;
					var y = _._scales[item].get(cur[item]);
					if(index == 0) {
						context.moveTo(x, y);
					} else {
						context.lineTo(x, y);
					}
				});

				if(cur._selected) {
					context.strokeStyle = "rgba(255, 0, 0, 1.0)";
				} else {
					context.strokeStyle = "rgba(0, 0, 0, 0.2)";
				}
				context.stroke();
			});
		}
	};
})();<commit_msg>Variable name refactor<commit_after>(function() {
	VISAN.Plots.ParallelCoordinates = function(options, container, stepModule, visan) {
		var _ = this;

		this._padding = 25;

		this._stage = new Kinetic.Stage({
			container: container.get(0),
			width: options.width || 500,
			height: options.height || 500
		});

		this._shapeLayer = new Kinetic.Layer();
		this._stage.add(this._shapeLayer);

		this._options = options;
		this._stepModule = stepModule;

		this._scales = {};
		this._options.axes.forEach(function(axis) {
			var dim = stepModule._dataManager.getDimension(function(d) { return d[axis]; });
			var max = dim.top(1)[0][axis];
			var min = dim.bottom(1)[0][axis];
			_._scales[axis] = new VISAN.Scale({
				range: [_._stage.getHeight() - _._padding, _._padding],
				domain: [min, max]
			});
		});

		this.draw();
	};

	VISAN.Plots.ParallelCoordinates.renderPlotCreateOptions = function(optionsContainer) {
		optionsContainer.append($("<p />").text("Please select all the axes to display:"));
		optionsContainer.append($("<select />").addClass("parallel-coordinates-axes").addClass("axis").attr("multiple", "multiple").attr("size", 6));

		return function(plotOptions, optionsContainer) {
			var selected = optionsContainer.find("select.parallel-coordinates-axes").val();
			plotOptions.axes = selected;
		};
	};

	VISAN.Plots.ParallelCoordinates.prototype = {
		draw: function() {
			var _ = this;

			var dataManager = this._stepModule._dataManager;
			var axes = this._options.axes;
			var numberOfAxes = axes.length;

			// axis positions
			var padding = this._padding;
			var width = this._stage.getWidth();
			var posDelta = (width - 2 * padding) / (numberOfAxes - 1);

			this._shapeLayer.clear();
			var context = this._shapeLayer.getContext("2d");

			dataManager.getData().forEach(function(cur) {
				context.beginPath();
				axes.forEach(function(axis, index) {
					var x = padding + index * posDelta;
					var y = _._scales[axis].get(cur[axis]);
					if(index == 0) {
						context.moveTo(x, y);
					} else {
						context.lineTo(x, y);
					}
				});

				if(cur._selected) {
					context.strokeStyle = "rgba(255, 0, 0, 1.0)";
				} else {
					context.strokeStyle = "rgba(0, 0, 0, 0.2)";
				}
				context.stroke();
			});
		}
	};
})();<|endoftext|>


<commit_before>var _,
    csv,
    download,
    downloads,
    destination,
    filename,
    fs,
    mongoose,
    processRats,
    processRescues,
    Rat,
    ratSheet,
    removeArchives,
    winston

// Node Modules
_ = require( 'underscore' )
csv = require( 'csv' )
download = require( 'download' )
fs = require( 'fs' )
mongoose = require( 'mongoose' )
winston = require( 'winston' )

// Mongoose Models
Rat = require( '../api/models/rat' )
Rescue = require( '../api/models/rescue' )

mongoose.Promise = global.Promise

// Google Sheet URLs
spreadsheets = {
  rats: {
    workbookId: '1JoTrC3TmBNFkEtU6lWcGhOZkUaRr9YUY24kLA5LQnoc',
    sheetId: '445147052'
  },
  rescues: {
    workbookId: '1JoTrC3TmBNFkEtU6lWcGhOZkUaRr9YUY24kLA5LQnoc',
    sheetId: '1657880365'
  },
  rescueDrilledRats: {
    workbookId: '1_e0kJcMqjzoDfB2qRPYRIdR3naeEA19Y-ZzmYHo6yzE',
    sheetId: '72806282'
  },
  dispatchDrilledRats: {
    workbookId: '1_e0kJcMqjzoDfB2qRPYRIdR3naeEA19Y-ZzmYHo6yzE',
    sheetId: '84232353'
  }
}

// Config options
destinationFolder = 'data'

// Array to store our download promises in
downloads = []

mongoose.connect( 'mongodb://localhost/fuelrats' )

processRats = function ( ratData, rescueDrills, dispatchDrills ) {
  winston.info( 'Processing rats' )

  return new Promise( function ( resolve, reject ) {
    var rats

    rats = []

    ratData.forEach( function ( ratDatum, index, ratData ) {
      var dispatchDrill, rat, rescueDrill

      rat = {
        archive: true,
        drilled: {
          dispatch: false,
          rescue: false
        },
        joined: new Date( ratDatum[0] ) || new Date,
        rescues: []
      }

      if ( dispatchDrill = _.findWhere( dispatchDrills, { 3: ratDatum[2] } ) ) {
        rat.drilled.dispatch = dispatchDrill[4].toLowerCase() === 'pass'
      }

      if ( rescueDrill = _.findWhere( rescueDrills, { 3: ratDatum[2] } ) ) {
        rat.drilled.rescue = rescueDrill[4].toLowerCase() === 'pass'
      }

      if ( ratDatum[1] === 'CMDR' || ratDatum[1] === 'GameTag' ) {
        rat.CMDRname = ratDatum[2]
      }

      if ( ratDatum[1] === 'GameTag' ) {
        rat.platform = 'xb'
      }

      if ( rat.CMDRname ) {
        rats.push( Rat.create( rat ) )
      }
    })

    Promise.all( rats )
    .then( resolve )
    .catch( reject )
  })
}

processRescues = function ( rescuesData ) {
  winston.info( 'Processing rescues' )

  return new Promise( function ( resolve, reject ) {
    var rescues

    rescues = []

    rescuesData.forEach( function ( rescueDatum, index, rescuesData ) {
      var rescue

      rescue = {
        archive: true,
        createdAt: new Date( rescueDatum[0] ),
        notes: rescueDatum[4],
        open: false,
        rats: [],
        unidentifiedRats: [rescueDatum[1]],
        successful: rescueDatum[3].toLowerCase() === 'successful' ? true : false,
        system: rescueDatum[2]
      }

      rescues.push( Rescue.create( rescue ) )
    })

    Promise.all( rescues )
    .then( resolve )
    .catch( reject )
  })
}

removeArchives = function removeArchives ( models ) {
  winston.info( 'Removing archives' )

  return new Promise( function ( resolve, reject ) {
    var promises

    promises = []

    models.forEach( function ( model, index, models ) {
      promises.push( model.remove( { archive: true } ) )
    })

    Promise.all( promises )
    .then( resolve )
    .catch( reject )
  })
}

// Download all of the spreadsheets
winston.info( 'Downloading spreadsheets' )
Object.keys( spreadsheets ).forEach( function ( name, index, names ) {
  var url, spreadsheet

  spreadsheet = spreadsheets[name]
  url = 'https://docs.google.com/spreadsheets/d/' + spreadsheet.workbookId + '/export?gid=' + spreadsheet.sheetId + '&format=csv'

  downloads.push( new Promise( function ( resolve, reject ) {
    download()
    .get( url )
    .dest( destinationFolder )
    .rename( name + '.csv' )
    .run( function ( error ) {
      if ( error ) {
        reject( error )
      } else {
        winston.info( 'Parsing spreadsheet:', name )
        csv.parse( fs.readFileSync( destinationFolder + '/' + name + '.csv' ), function ( error, data ) {
          if ( error ) {
            reject( error )
          } else {
            spreadsheets[name].data = data
            resolve()
          }
        })
      }
    })
  }))
})

Promise.all( downloads )
.then( function () {
  var dispatchDrills, promises, rats, removals, rescues, rescueDrills

  promises = []

  dispatchDrills = spreadsheets.dispatchDrilledRats.data
  rats = spreadsheets.rats.data
  rescues = spreadsheets.rescues.data
  rescueDrills = spreadsheets.rescueDrilledRats.data

  rats.shift()
  rescues.shift()

  // Clear out the archives
  removeArchives( [ Rat, Rescue ] )
  .then( function () {
    var promises

    promises = []

    promises.push( processRats( rats, rescueDrills, dispatchDrills ) )
    promises.push( processRescues( rescues ) )

    Promise.all( promises )
    .then( function () {
      var promises

      promises = []

      promises.push( Rat.count({}) )
      promises.push( Rescue.count({}) )

      Promise.all( promises )
      .then( function ( results ) {
        var newRatCount, newRescuesCount, oldRatCount, oldRescuesCount

        newRatCount = rats.length
        newRescuesCount = rescues.length
        oldRatCount = results[0]
        oldRescuesCount = results[1]

        winston.info( 'Created', newRatCount, 'rats,', oldRatCount, 'total' )
        winston.info( 'Created', newRescuesCount, 'rescues,', oldRescuesCount, 'total' )

        mongoose.disconnect()
      })
      .catch( function ( error ) {
        winston.error( error )
      })
    })
    .catch( function ( error ) {
      winston.error( error )
    })
  })
  .catch( function ( error ) {
    winston.error( error )
  })
})
.catch( function ( error ) {
  winston.error( error )
})
<commit_msg>[Fix #27] Import script now only removes a rat or rescue if it has not been claimed from the archives<commit_after>var _,
    csv,
    download,
    downloads,
    destination,
    filename,
    fs,
    mongoose,
    processRats,
    processRescues,
    Rat,
    ratSheet,
    removeArchives,
    winston

// Node Modules
_ = require( 'underscore' )
csv = require( 'csv' )
download = require( 'download' )
fs = require( 'fs' )
mongoose = require( 'mongoose' )
winston = require( 'winston' )

// Mongoose Models
Rat = require( '../api/models/rat' )
Rescue = require( '../api/models/rescue' )

mongoose.Promise = global.Promise

// Google Sheet URLs
spreadsheets = {
  rats: {
    workbookId: '1JoTrC3TmBNFkEtU6lWcGhOZkUaRr9YUY24kLA5LQnoc',
    sheetId: '445147052'
  },
  rescues: {
    workbookId: '1JoTrC3TmBNFkEtU6lWcGhOZkUaRr9YUY24kLA5LQnoc',
    sheetId: '1657880365'
  },
  rescueDrilledRats: {
    workbookId: '1_e0kJcMqjzoDfB2qRPYRIdR3naeEA19Y-ZzmYHo6yzE',
    sheetId: '72806282'
  },
  dispatchDrilledRats: {
    workbookId: '1_e0kJcMqjzoDfB2qRPYRIdR3naeEA19Y-ZzmYHo6yzE',
    sheetId: '84232353'
  }
}

// Config options
destinationFolder = 'data'

// Array to store our download promises in
downloads = []

mongoose.connect( 'mongodb://localhost/fuelrats' )

processRats = function ( ratData, rescueDrills, dispatchDrills ) {
  winston.info( 'Processing rats' )

  return new Promise( function ( resolve, reject ) {
    var rats

    rats = []

    ratData.forEach( function ( ratDatum, index, ratData ) {
      var dispatchDrill, rat, rescueDrill

      rat = {
        archive: true,
        drilled: {
          dispatch: false,
          rescue: false
        },
        joined: new Date( ratDatum[0] ) || new Date,
        platform: 'pc',
        rescues: []
      }

      if ( dispatchDrill = _.findWhere( dispatchDrills, { 3: ratDatum[2] } ) ) {
        rat.drilled.dispatch = dispatchDrill[4].toLowerCase() === 'pass'
      }

      if ( rescueDrill = _.findWhere( rescueDrills, { 3: ratDatum[2] } ) ) {
        rat.drilled.rescue = rescueDrill[4].toLowerCase() === 'pass'
      }

      if ( ratDatum[1] === 'CMDR' || ratDatum[1] === 'GameTag' ) {
        rat.CMDRname = ratDatum[2]
      }

      if ( ratDatum[1] === 'GameTag' ) {
        rat.platform = 'xb'
      }

      if ( rat.CMDRname ) {
        rats.push( new Promise( function ( resolve, reject ) {
          Rat.find({
            CMDRname: rat.CMDRname,
            platform: rat.platform
          })
          .then( function ( rats ) {
            if ( !rats.length ) {
              Rat.create( rat )
              .then( resolve )
              .catch( reject )
            } else {
              resolve()
            }
          })
          .catch( reject )
        }))
      }
    })

    Promise.all( rats )
    .then( resolve )
    .catch( reject )
  })
}

processRescues = function ( rescuesData ) {
  winston.info( 'Processing rescues' )

  return new Promise( function ( resolve, reject ) {
    var rescues

    rescues = []

    rescuesData.forEach( function ( rescueDatum, index, rescuesData ) {
      var rescue

      rescue = {
        archive: true,
        createdAt: new Date( rescueDatum[0] ),
        notes: rescueDatum[4],
        open: false,
        rats: [],
        unidentifiedRats: [rescueDatum[1]],
        successful: rescueDatum[3].toLowerCase() === 'successful' ? true : false,
        system: rescueDatum[2]
      }

      rescues.push( Rescue.create( rescue ) )
    })

    Promise.all( rescues )
    .then( resolve )
    .catch( reject )
  })
}

removeArchives = function removeArchives ( models ) {
  winston.info( 'Removing archives' )

  return new Promise( function ( resolve, reject ) {
    var promises

    promises = []

    models.forEach( function ( model, index, models ) {
      promises.push( model.remove( { archive: true } ) )
    })

    Promise.all( promises )
    .then( resolve )
    .catch( reject )
  })
}

// Download all of the spreadsheets
winston.info( 'Downloading spreadsheets' )
Object.keys( spreadsheets ).forEach( function ( name, index, names ) {
  var url, spreadsheet

  spreadsheet = spreadsheets[name]
  url = 'https://docs.google.com/spreadsheets/d/' + spreadsheet.workbookId + '/export?gid=' + spreadsheet.sheetId + '&format=csv'

  downloads.push( new Promise( function ( resolve, reject ) {
    download()
    .get( url )
    .dest( destinationFolder )
    .rename( name + '.csv' )
    .run( function ( error ) {
      if ( error ) {
        reject( error )
      } else {
        winston.info( 'Parsing spreadsheet:', name )
        csv.parse( fs.readFileSync( destinationFolder + '/' + name + '.csv' ), function ( error, data ) {
          if ( error ) {
            reject( error )
          } else {
            spreadsheets[name].data = data
            resolve()
          }
        })
      }
    })
  }))
})

Promise.all( downloads )
.then( function () {
  var dispatchDrills, promises, rats, removals, rescues, rescueDrills

  promises = []

  dispatchDrills = spreadsheets.dispatchDrilledRats.data
  rats = spreadsheets.rats.data
  rescues = spreadsheets.rescues.data
  rescueDrills = spreadsheets.rescueDrilledRats.data

  rats.shift()
  rescues.shift()

  // Clear out the archives
  removeArchives( [ Rat, Rescue ] )
  .then( function () {
    var promises

    promises = []

    promises.push( processRats( rats, rescueDrills, dispatchDrills ) )
    promises.push( processRescues( rescues ) )

    Promise.all( promises )
    .then( function () {
      var promises

      promises = []

      promises.push( Rat.count({}) )
      promises.push( Rescue.count({}) )

      Promise.all( promises )
      .then( function ( results ) {
        var newRatCount, newRescuesCount, oldRatCount, oldRescuesCount

        newRatCount = rats.length
        newRescuesCount = rescues.length
        oldRatCount = results[0]
        oldRescuesCount = results[1]

        winston.info( 'Created', newRatCount, 'rats,', oldRatCount, 'total' )
        winston.info( 'Created', newRescuesCount, 'rescues,', oldRescuesCount, 'total' )

        mongoose.disconnect()
      })
      .catch( function ( error ) {
        winston.error( error )
      })
    })
    .catch( function ( error ) {
      winston.error( error )
    })
  })
  .catch( function ( error ) {
    winston.error( error )
  })
})
.catch( function ( error ) {
  winston.error( error )
})
<|endoftext|>


<commit_before>$(document).ready(function(){
    var pubnub = PUBNUB.init({
        publish_key: 'demo',
        subscribe_key: 'demo'
    });
    gliderino(pubnub);

    pubnub.subscribe({
        channel: 'pongnub_lobby',
        callback: function(m) {console.log(m)},
        connect: function() {
            pubnub.here_now({
                channel: 'pongnub_lobby',
                callback: function(m) {
                    $("#spinner").hide();
                    if (m.occupancy >= 999) { // Change 999 to 2
                        $("#full").show();
                        pubnub.unsubscribe({
                            channel: "pongnub_lobby"
                        });
                    }
                    else {
                        $("#setup").show();
                        $("#login").click(function() {
                            var name = $("#name").val();
                            if (name.length > 0) {
                                $("#setup").hide();
                                $("#title").hide();
                                $("#controls").show();
                                pubnub.subscribe({
                                    channel: "pongnub_game",
                                    callback: function(m) {console.log(m)},
                                    state: {
                                        side: window.side,
                                        name: name
                                    }
                                });
                            }
                        });
                        $("#name").keypress(function(e) {
                            if (e.which === 13) {
                                $("#login").click();
                            }
                        });
                    }
                }
            });
        },
    heartbeat: 10
    });
});

$("#controls").css("font-size", ($(window).height() - 95) + "px");
$("#controls").css("margin-top", "-" + ($(window).height()/6) + "px");
$("#controls").css("height", ($(window).height() + ($(window).height()/6)) + "px");

$(window).resize(function() {
    $("#controls").css("font-size", ($(window).height() - 95) + "px");
    $("#controls").css("margin-top", "-" + ($(window).height()/6) + "px");
    $("#controls").css("height", ($(window).height() + ($(window).height()/6)) + "px");
});

var gliderino = function (p) {
    var IDLE_TIME = 2000;
    var THROTTLE_TIME = 100;

    function throttle(fn, delay) {
        var interval = 0;
        var last = 0;

        return function () {
            var now = Date.now();
            if (now - last < delay) {
                clearTimeout(interval);
                interval = setTimeout(throttled, delay);
            }
            else {
                last = now;
                fn.apply(this, arguments);
            }
        };
    }

    var globe = {
        "interval" : -1,
        "scale" : 1,
        "gesture" : false,

        "touch" : {
            "x" : 0,
            "y" : 0
        },
        "pos" : {
            "x" : 0,
            "y" : 0
        },
        "delta" : {
            "x" : 0,
            "y" : 0
        },

        "copytouch" : function (touch) {
            return {
                "x" : touch.pageX,
                "y" : touch.pageY
            };
        },

        "touchstart" : function (e) {
            if (globe.interval >= 0) {
                return;
            }
            alert("STUFF IS HAPPENING");

            globe.touch = globe.copytouch(e.touches[0]);
            globe.pos.x = globe.touch.x;
            globe.pos.y = globe.touch.y;
            globe.delta.x = 0;
            globe.delta.y = 0;

            // Continuously pause idle animation
            globe.interval = setInterval(globe.publish, IDLE_TIME);
        },

        "touchend" : function (e) {
            // Allow idle animation to continue
            clearInterval(globe.interval);
            globe.interval = -1;
        },

        "touchmove" : function (e) {
            e.preventDefault();

            if (globe.gesture) {
                return;
            }

            globe.touch = globe.copytouch(e.touches[0]);
            globe.delta.x = globe.pos.x - globe.touch.x;
            globe.delta.y = globe.pos.y - globe.touch.y;

            globe.publish();
        },

        "gesturestart" : function (e) {
            globe.gesture = true;
        },

        "gesturechange" : function (e) {
            globe.gesture = true;
        },

        "gestureend" : function (e) {
            globe.gesture = false;
        },

        "publish" : throttle(function () {
            p.publish({
                "channel"   : "pongnub_game",
                "message"   : {
                    "type"      : "move",
                    "x"         : globe.delta.x,
                    "y"         : globe.delta.y
                }
            });

            globe.pos.x = globe.touch.x;
            globe.pos.y = globe.touch.y;
            globe.delta.x = 0;
            globe.delta.y = 0;
        }, THROTTLE_TIME)
    };

    document.addEventListener("DOMContentLoaded", function () {
        document.addEventListener("touchstart",  globe.touchstart, false);
        document.addEventListener("touchend",    globe.touchend,   false);
        document.addEventListener("touchleave",  globe.touchend,   false);
        document.addEventListener("touchcancel", globe.touchend,   false);
        document.addEventListener("touchmove",   globe.touchmove,  false);

        document.addEventListener("gesturestart",  globe.gesturestart,  false);
        document.addEventListener("gestureend",    globe.gestureend,    false);
        document.addEventListener("gesturechange", globe.gesturechange, false);

    }, false);
}<commit_msg>Added touchstart alert<commit_after>$(document).ready(function(){
    var pubnub = PUBNUB.init({
        publish_key: 'demo',
        subscribe_key: 'demo'
    });
    gliderino(pubnub);

    pubnub.subscribe({
        channel: 'pongnub_lobby',
        callback: function(m) {console.log(m)},
        connect: function() {
            pubnub.here_now({
                channel: 'pongnub_lobby',
                callback: function(m) {
                    $("#spinner").hide();
                    if (m.occupancy >= 999) { // Change 999 to 2
                        $("#full").show();
                        pubnub.unsubscribe({
                            channel: "pongnub_lobby"
                        });
                    }
                    else {
                        $("#setup").show();
                        $("#login").click(function() {
                            var name = $("#name").val();
                            if (name.length > 0) {
                                $("#setup").hide();
                                $("#title").hide();
                                $("#controls").show();
                                pubnub.subscribe({
                                    channel: "pongnub_game",
                                    callback: function(m) {console.log(m)},
                                    state: {
                                        side: window.side,
                                        name: name
                                    }
                                });
                            }
                        });
                        $("#name").keypress(function(e) {
                            if (e.which === 13) {
                                $("#login").click();
                            }
                        });
                    }
                }
            });
        },
    heartbeat: 10
    });
});

$("#controls").css("font-size", ($(window).height() - 95) + "px");
$("#controls").css("margin-top", "-" + ($(window).height()/6) + "px");
$("#controls").css("height", ($(window).height() + ($(window).height()/6)) + "px");

$(window).resize(function() {
    $("#controls").css("font-size", ($(window).height() - 95) + "px");
    $("#controls").css("margin-top", "-" + ($(window).height()/6) + "px");
    $("#controls").css("height", ($(window).height() + ($(window).height()/6)) + "px");
});

var gliderino = function (p) {
    var IDLE_TIME = 2000;
    var THROTTLE_TIME = 100;

    function throttle(fn, delay) {
        var interval = 0;
        var last = 0;

        return function () {
            var now = Date.now();
            if (now - last < delay) {
                clearTimeout(interval);
                interval = setTimeout(throttled, delay);
            }
            else {
                last = now;
                fn.apply(this, arguments);
            }
        };
    }

    var globe = {
        "interval" : -1,
        "scale" : 1,
        "gesture" : false,

        "touch" : {
            "x" : 0,
            "y" : 0
        },
        "pos" : {
            "x" : 0,
            "y" : 0
        },
        "delta" : {
            "x" : 0,
            "y" : 0
        },

        "copytouch" : function (touch) {
            return {
                "x" : touch.pageX,
                "y" : touch.pageY
            };
        },

        "touchstart" : function (e) {
            if (globe.interval >= 0) {
                return;
            }

            globe.touch = globe.copytouch(e.touches[0]);
            globe.pos.x = globe.touch.x;
            globe.pos.y = globe.touch.y;
            globe.delta.x = 0;
            globe.delta.y = 0;

            // Continuously pause idle animation
            globe.interval = setInterval(globe.publish, IDLE_TIME);
        },

        "touchend" : function (e) {
            // Allow idle animation to continue
            clearInterval(globe.interval);
            globe.interval = -1;
        },

        "touchmove" : function (e) {
            e.preventDefault();

            if (globe.gesture) {
                return;
            }

            globe.touch = globe.copytouch(e.touches[0]);
            globe.delta.x = globe.pos.x - globe.touch.x;
            globe.delta.y = globe.pos.y - globe.touch.y;

            globe.publish();
        },

        "gesturestart" : function (e) {
            globe.gesture = true;
        },

        "gesturechange" : function (e) {
            globe.gesture = true;
        },

        "gestureend" : function (e) {
            globe.gesture = false;
        },

        "publish" : throttle(function () {
            p.publish({
                "channel"   : "pongnub_game",
                "message"   : {
                    "type"      : "move",
                    "x"         : globe.delta.x,
                    "y"         : globe.delta.y
                }
            });

            globe.pos.x = globe.touch.x;
            globe.pos.y = globe.touch.y;
            globe.delta.x = 0;
            globe.delta.y = 0;
        }, THROTTLE_TIME)
    };

    document.addEventListener("DOMContentLoaded", function () {
        document.addEventListener("touchstart",  globe.touchstart, false);
        document.addEventListener("touchend",    globe.touchend,   false);
        document.addEventListener("touchleave",  globe.touchend,   false);
        document.addEventListener("touchcancel", globe.touchend,   false);
        document.addEventListener("touchmove",   globe.touchmove,  false);

        document.addEventListener("gesturestart",  globe.gesturestart,  false);
        document.addEventListener("gestureend",    globe.gestureend,    false);
        document.addEventListener("gesturechange", globe.gesturechange, false);

    }, false);
}

document.addEventListener("touchstart", function() {alert("STUFF IS HAPPENING");}, false);<|endoftext|>


<commit_before>$(function () {
    'use strict';
    var EXCLUDE = ['..', 'doc', 'stable', 'beta', 'experimental']
    $('.hero-unit [data-channel]').click(function () {
        $('#models').hide();
        var path = '/'+$(this).attr('data-channel')+'/factory/';
        $.get(path, function (data) {
            var routers = {},
                links = $(data).find('a[href$=".bin"]');
            links.each(function () {
                var link = path+$(this).attr('href'),//.split('/').slice(-1)[0],
                    router = link.split('-').slice(4).join('-').split('.')[0],
                    split = router.split('-'),
                    model,
                    hwversion;
                if (split.slice(-1)[0][0] === 'v') {
                    model = split.slice(0, -1).join('-');
                    hwversion = split.slice(-1)[0];
                } else if (split.slice(-2, -1)[0] === 'rev') {
                    model = split.slice(0, -2).join('-');
                    hwversion = split.slice(-1)[0];
                } else {
                    model = router;
                    hwversion = 'alle';
                }
                if (!routers[model]) {
                    routers[model] = [];
                }
                routers[model].push([hwversion, link]);
            });
            links.first().each(function () {
                var link = $(this).attr('href').split('/').slice(-1)[0],
                    split = link.split('-', 4).slice(2);
                $('#version').html(split[0].replace('%7E', '~'));
                $('#versiondate').html(renderDate(split[1]));
            });
            $('tbody').html(renderRouters(routers));
            $('#models').fadeIn(500);
            document.location.hash = 'models';
        }, 'html');
    });
    $.get('/raw/', function (data) {
      var links = $(data).find('a[href$="/"]');
      links.each(function () {
        var target = $(this).attr('href');
        target = target.substring(0, target.length - 1);
        if (EXCLUDE.indexOf(target) == -1) {
          $('#allversions').append('
'+target+'
');
        }
      });
    }, 'html');
});

var renderRouters = function (routers) {
    'use strict';
    var model, i, versions, out = '';
    for (model in routers) {
        versions = routers[model];
        out += '
' + model + '	';
        for (i in versions) {
            out += '' + versions[i][0] + '

';
        }
        out += '
';
    }
    return out;
};

var renderDate = function (date) {
    'use strict';
    return date.substr(6) + '.' + date.substr(4, 2) + '.' + date.substr(0, 4);
};
<commit_msg>improved version and date parsing<commit_after>$(function () {
    'use strict';
    var EXCLUDE = ['..', 'doc', 'stable', 'beta', 'experimental']
    $('.hero-unit [data-channel]').click(function () {
        $('#models').hide();
        var path = '/'+$(this).attr('data-channel')+'/factory/';
        $.get(path, function (data) {
            var routers = {},
                links = $(data).find('a[href$=".bin"]');
            links.each(function () {
                var link = path+$(this).attr('href'),//.split('/').slice(-1)[0],
                    router = link.split('-').slice(4).join('-').split('.')[0],
                    split = router.split('-'),
                    model,
                    hwversion;
                if (split.slice(-1)[0][0] === 'v') {
                    model = split.slice(0, -1).join('-');
                    hwversion = split.slice(-1)[0];
                } else if (split.slice(-2, -1)[0] === 'rev') {
                    model = split.slice(0, -2).join('-');
                    hwversion = split.slice(-1)[0];
                } else {
                    model = router;
                    hwversion = 'alle';
                }
                if (!routers[model]) {
                    routers[model] = [];
                }
                routers[model].push([hwversion, link]);
            });
            links.first().each(function () {
                var link = $(this).attr('href').split('/').slice(-1)[0],
                match = link.match(/gluon-[a-zA-Z]+-([0-9.]+~[a-zA-Z]+)-?([0-9]+)-/);
                $('#version').html(match[1].replace('%7E', '~'));
                $('#versiondate').html(renderDate(match[2]));
            });
            $('tbody').html(renderRouters(routers));
            $('#models').fadeIn(500);
            document.location.hash = 'models';
        }, 'html');
    });
    $.get('/raw/', function (data) {
      var links = $(data).find('a[href$="/"]');
      links.each(function () {
        var target = $(this).attr('href');
        target = target.substring(0, target.length - 1);
        if (EXCLUDE.indexOf(target) == -1) {
          $('#allversions').append('
'+target+'
');
        }
      });
    }, 'html');
});

var renderRouters = function (routers) {
    'use strict';
    var model, i, versions, out = '';
    for (model in routers) {
        versions = routers[model];
        out += '
' + model + '	';
        for (i in versions) {
            out += '' + versions[i][0] + '

';
        }
        out += '
';
    }
    return out;
};

var renderDate = function (date) {
    'use strict';
    return date.substr(6) + '.' + date.substr(4, 2) + '.' + date.substr(0, 4);
};
<|endoftext|>


<commit_before>#!/bin/env node

var argv = require('nomnom')
  .option('verbose', {
    abbr: 'v',
    flag: true,
    help: 'Print the logs to console'
  })
  .option('version', {
    flag: true,
    help: 'Print current ldnode version',
    callback: function () {
      fs.readFile(path.resolve(__dirname, '../package.json'), 'utf-8', function(err, file) {
        console.log(JSON.parse(file).version);
      });
    }
  })
  .option('uriBase', {
    full: 'uri',
    abbr: 'u',
    metavar: 'URI',
    help: 'Default address of the server (e.g. http[s]://host:port/path)'
  })
  .option('fileBase', {
    abbr: 'b',
    metavar: 'PATH',
    full: 'path',
    help: 'Base location to serve resources'
  })
  .option('port', {
    abbr: 'p',
    help: 'Port to use'
  })
  .option('cache', {
    abbr: 'c',
    help: 'Set cache time (in seconds), 0 for no cache'
  })
  .option('noSsl', {
    help: 'Run ldnode with without ssl, so in http',
    full: 'no-ssl',
    flag: true
  })
  .option('sslKey', {
    help: 'Path to the ssl key',
    abbr: 'K',
    full: 'ssl-key'
  })
  .option('ssl-cert', {
    help: 'Path to the ssl cert',
    abbr: 'C'
  })
  .option('noWebid', {
    help: 'Path to the ssl key',
    full: 'no-webid',
    flag: true
  })
  .option('webidKey', {
    help: 'Path to the webid key',
    full: 'webid-key',
    abbr: 'k'
  })
  .option('webidCert', {
    help: 'Path to the webid cert',
    full: 'webid-cert',
    abbr: 'c'
  })
  .parse();

argv.webid = !argv.noWebid;
process.env.DEBUG = argv.verbose ? 'ldnode:*' : false;
var debug = require('../logging').server;
var ldnode = require('../index');

// Signal handling
if (process.platform !== 'win32') {
    // Signal handlers don't work on Windows.
    process.on('SIGINT', function() {
        debug("LDP stopped.");
        process.exit();
    });
}

// Starting ldnode
var app = ldnode.createServer(argv);
app.listen(argv.p, function() {
    debug('LDP started on port ' + argv.p);
});

<commit_msg>fixing --version starting ldp<commit_after>#!/bin/env node

var fs = require('fs');
var path = require('path');

var argv = require('nomnom')
  .option('verbose', {
    abbr: 'v',
    flag: true,
    help: 'Print the logs to console'
  })
  .option('version', {
    flag: true,
    help: 'Print current ldnode version',
    callback: function () {
      fs.readFile(path.resolve(__dirname, '../package.json'), 'utf-8', function(err, file) {
        console.log(JSON.parse(file).version);
      });
    }
  })
  .option('uriBase', {
    full: 'uri',
    abbr: 'u',
    metavar: 'URI',
    help: 'Default address of the server (e.g. http[s]://host:port/path)'
  })
  .option('fileBase', {
    abbr: 'b',
    metavar: 'PATH',
    full: 'path',
    help: 'Base location to serve resources'
  })
  .option('port', {
    abbr: 'p',
    help: 'Port to use'
  })
  .option('cache', {
    abbr: 'c',
    help: 'Set cache time (in seconds), 0 for no cache'
  })
  .option('noSsl', {
    help: 'Run ldnode with without ssl, so in http',
    full: 'no-ssl',
    flag: true
  })
  .option('sslKey', {
    help: 'Path to the ssl key',
    abbr: 'K',
    full: 'ssl-key'
  })
  .option('ssl-cert', {
    help: 'Path to the ssl cert',
    abbr: 'C'
  })
  .option('noWebid', {
    help: 'Path to the ssl key',
    full: 'no-webid',
    flag: true
  })
  .option('webidKey', {
    help: 'Path to the webid key',
    full: 'webid-key',
    abbr: 'k'
  })
  .option('webidCert', {
    help: 'Path to the webid cert',
    full: 'webid-cert',
    abbr: 'c'
  })
  .parse();

if (argv.version) {
  return;
}

argv.webid = !argv.noWebid;
process.env.DEBUG = argv.verbose ? 'ldnode:*' : false;
var debug = require('../logging').server;
var ldnode = require('../index');

// Signal handling
if (process.platform !== 'win32') {
    // Signal handlers don't work on Windows.
    process.on('SIGINT', function() {
        debug("LDP stopped.");
        process.exit();
    });
}

// Starting ldnode
var app = ldnode.createServer(argv);
app.listen(argv.p, function() {
    debug('LDP started on port ' + argv.p);
});

<|endoftext|>