<commit_before>'use strict';
/*jshint browser: true */

var _ = require('lodash');
var hat = require('hat');
var Vimeo = require('@vimeo/player');

function urlAttrs(obj) {
    return _.chain(obj)
        .pairs()
        .map(function (v) {
            return v[0] + '=' + v[1].toString();
        })
        .join('&');
}
function checkDisplayRatio(width, height) {
    var iframeH, iframeW;

    //Scaling the window to 40% of the screen size
    iframeH = height * 0.40;
    iframeW = width * 0.40;
    //Tranforming it the video size to 16:9 ration
    if (width >= height) {
        iframeW = (iframeH * 16) / 9;
        return {height:iframeH,width:iframeW};
    } else {
        iframeH = (iframeW / 16) * 9;
        return {height:iframeH,width:iframeW};
    }
}

function makeElement(tagName, attributes) {
    var el = document.createElement(tagName);
    _.each(attributes, function (value, key) {
        el.setAttribute(key, value);
    });

    return el;
}

var players = {};
function registerPlayer(id, player) {
    players[id] = player;
}

function unregisterPlayer(id) {
    delete players[id];
}

function onMessageRecieved(event) {
    //APEP 3/10/16 - Chrome dev tools + react dev tools cause events to be sent to player
    var data = JSON.parse(event.data);
    players[data.player_id].handleEvent(data);
}

// check for window, we won't have it if we are running headless tests
if (typeof window !== 'undefined') {
    if (window.addEventListener) {
        window.addEventListener('message', onMessageRecieved, false);
    } else {
        window.attachEvent('onmessage', onMessageRecieved, false);
    }
}

function getTranscodedUrl(mediaObjectUrl) {
    var dashUrl = mediaObjectUrl.replace("raw", "transcoded/dash");

    var trailingSlash = dashUrl.lastIndexOf("/");
    dashUrl = dashUrl.substring(0, trailingSlash);
    dashUrl += '/video_manifest.mpd';

    return dashUrl;
}

function EmbeddedVimeoPlayer(isVimeo, videoUrl) {
    this._ready = false;
    this.id = hat();
    this.isVimeo = isVimeo;

    registerPlayer(this.id, this);

    if(isVimeo)
        this.setupAsVimeoPlayer(videoUrl);
    else
        this.setupAsRawPlayer(getTranscodedUrl(videoUrl));

    this.url = this._element.attributes.src.value.split('?')[0];

    document.body.appendChild(this._element);

    //https://github.com/vimeo/player.js
    if(isVimeo) {
        this.vimeo_player = new Vimeo(this._element);
    } else {
        console.log("EmbeddedVimeoPlayer _element: ", this._element);
        var url = getTranscodedUrl(videoUrl);
        //var url = "Transcoding_3/video_manifest.mpd"; //APEP see other comment (_getRawPlayerForMediaObject)
        var player = dashjs.MediaPlayer().create();
        player.getDebug().setLogToBrowserConsole(false);
        player.initialize(this._element, url, true);
        this.raw_player = player;
        this.player_url = url;
    }

    return this;
}

EmbeddedVimeoPlayer.prototype.setupAsVimeoPlayer = function(vimeoId) {
    var urlAttrsStr = urlAttrs({
            api: 1,
            player_id: this.id,
            title: 0,
            autoplay: 0
        }),
        playerUrl = 'https://player.vimeo.com/video/' + vimeoId + '?' + urlAttrsStr;
    try {
        var dimensions = checkDisplayRatio(window.innerWidth, window.innerHeight);
        this._element = makeElement('iframe', {
            src: playerUrl,
            id: this.id,
            width: dimensions.width,
            height: dimensions.height,
            frameborder: 0,
            class: 'media-object embedded-vimeo-player'
        });
    }
    catch (e) {
        console.log(e)
    }
};

EmbeddedVimeoPlayer.prototype.setupAsRawPlayer = function(videoUrl) {
    this._element = makeElement('video', {
        src: videoUrl,
        id: this.id,
        class: 'media-object embedded-vimeo-player',
        'data-dashjs-player': 'data-dashjs-player',
    });

    var dimensions = checkDisplayRatio(window.innerWidth, window.innerHeight);

    this._element.style.width = dimensions.width + 'px';
    this._element.style.height = dimensions.height + 'px';

    this._element.controls = true;
    this._element.autoplay = false;
    this._element.looping = true; //should be some logic
};

EmbeddedVimeoPlayer.prototype.postMessage = function (action, value) {
    var data = {
        method: action
    };

    if (value) {
        data.value = value;
    }

    var msg = JSON.stringify(data);

    console.log("postMessage: ", msg);

    this._element.contentWindow.postMessage(data, this.url);
};

EmbeddedVimeoPlayer.prototype.onPlayProgress = function (cb) {
    this._playProgressHandler = cb;
};

EmbeddedVimeoPlayer.prototype.onReady = function (cb) {
    this._readyHandler = cb;
};

EmbeddedVimeoPlayer.prototype.handleEvent = function (data) {
    switch (data.event) {
        case 'ready':
            this.postMessage('addEventListener', 'playProgress');
            if (this._readyHandler) {
                this._readyHandler(this._element);
            }

            break;
        case 'playProgress':
            if (this._playProgressHandler) {
                this._playProgressHandler(data.data);
            }
            break;
    }
};

EmbeddedVimeoPlayer.prototype.remove = function () {
    unregisterPlayer(this.id);
};

module.exports = EmbeddedVimeoPlayer;
<commit_msg>Within the embedded ensure no controls are an option.<commit_after>'use strict';
/*jshint browser: true */

var _ = require('lodash');
var hat = require('hat');
var Vimeo = require('@vimeo/player');

function urlAttrs(obj) {
    return _.chain(obj)
        .pairs()
        .map(function (v) {
            return v[0] + '=' + v[1].toString();
        })
        .join('&');
}
function checkDisplayRatio(width, height) {
    var iframeH, iframeW;

    //Scaling the window to 40% of the screen size
    iframeH = height * 0.40;
    iframeW = width * 0.40;
    //Tranforming it the video size to 16:9 ration
    if (width >= height) {
        iframeW = (iframeH * 16) / 9;
        return {height:iframeH,width:iframeW};
    } else {
        iframeH = (iframeW / 16) * 9;
        return {height:iframeH,width:iframeW};
    }
}

function makeElement(tagName, attributes) {
    var el = document.createElement(tagName);
    _.each(attributes, function (value, key) {
        el.setAttribute(key, value);
    });

    return el;
}

var players = {};
function registerPlayer(id, player) {
    players[id] = player;
}

function unregisterPlayer(id) {
    delete players[id];
}

function onMessageRecieved(event) {
    //APEP 3/10/16 - Chrome dev tools + react dev tools cause events to be sent to player
    var data = JSON.parse(event.data);
    players[data.player_id].handleEvent(data);
}

// check for window, we won't have it if we are running headless tests
if (typeof window !== 'undefined') {
    if (window.addEventListener) {
        window.addEventListener('message', onMessageRecieved, false);
    } else {
        window.attachEvent('onmessage', onMessageRecieved, false);
    }
}

function getTranscodedUrl(mediaObjectUrl) {
    var dashUrl = mediaObjectUrl.replace("raw", "transcoded/dash");

    var trailingSlash = dashUrl.lastIndexOf("/");
    dashUrl = dashUrl.substring(0, trailingSlash);
    dashUrl += '/video_manifest.mpd';

    return dashUrl;
}

function EmbeddedVimeoPlayer(isVimeo, videoUrl) {
    this._ready = false;
    this.id = hat();
    this.isVimeo = isVimeo;

    registerPlayer(this.id, this);

    if(isVimeo)
        this.setupAsVimeoPlayer(videoUrl);
    else
        this.setupAsRawPlayer(getTranscodedUrl(videoUrl));

    this.url = this._element.attributes.src.value.split('?')[0];

    document.body.appendChild(this._element);

    //https://github.com/vimeo/player.js
    if(isVimeo) {
        this.vimeo_player = new Vimeo(this._element);
    } else {
        console.log("EmbeddedVimeoPlayer _element: ", this._element);
        var url = getTranscodedUrl(videoUrl);
        //var url = "Transcoding_3/video_manifest.mpd"; //APEP see other comment (_getRawPlayerForMediaObject)
        var player = dashjs.MediaPlayer().create();
        player.getDebug().setLogToBrowserConsole(false);
        player.initialize(this._element, url, true);
        this.raw_player = player;
        this.player_url = url;
    }

    return this;
}

EmbeddedVimeoPlayer.prototype.setupAsVimeoPlayer = function(vimeoId) {
    var urlAttrsStr = urlAttrs({
            api: 1,
            player_id: this.id,
            title: 0,
            autoplay: 0
        }),
        playerUrl = 'https://player.vimeo.com/video/' + vimeoId + '?' + urlAttrsStr;
    try {
        var dimensions = checkDisplayRatio(window.innerWidth, window.innerHeight);
        this._element = makeElement('iframe', {
            src: playerUrl,
            id: this.id,
            width: dimensions.width,
            height: dimensions.height,
            frameborder: 0,
            class: 'media-object embedded-vimeo-player'
        });
    }
    catch (e) {
        console.log(e)
    }
};

EmbeddedVimeoPlayer.prototype.setupAsRawPlayer = function(videoUrl) {
    this._element = makeElement('video', {
        src: videoUrl,
        id: this.id,
        class: 'media-object embedded-vimeo-player',
        'data-dashjs-player': 'data-dashjs-player',
    });

    var dimensions = checkDisplayRatio(window.innerWidth, window.innerHeight);

    this._element.style.width = dimensions.width + 'px';
    this._element.style.height = dimensions.height + 'px';

    this._element.controls = false;
    this._element.autoplay = false;
    this._element.looping = true; //should be some logic
};

EmbeddedVimeoPlayer.prototype.postMessage = function (action, value) {
    var data = {
        method: action
    };

    if (value) {
        data.value = value;
    }

    var msg = JSON.stringify(data);

    console.log("postMessage: ", msg);

    this._element.contentWindow.postMessage(data, this.url);
};

EmbeddedVimeoPlayer.prototype.onPlayProgress = function (cb) {
    this._playProgressHandler = cb;
};

EmbeddedVimeoPlayer.prototype.onReady = function (cb) {
    this._readyHandler = cb;
};

EmbeddedVimeoPlayer.prototype.handleEvent = function (data) {
    switch (data.event) {
        case 'ready':
            this.postMessage('addEventListener', 'playProgress');
            if (this._readyHandler) {
                this._readyHandler(this._element);
            }

            break;
        case 'playProgress':
            if (this._playProgressHandler) {
                this._playProgressHandler(data.data);
            }
            break;
    }
};

EmbeddedVimeoPlayer.prototype.remove = function () {
    unregisterPlayer(this.id);
};

module.exports = EmbeddedVimeoPlayer;
<|endoftext|>


<commit_before>"use strict";

var Base = require('./base');

exports = module.exports = (mocha_parser) => DatadogReporter;

// Basically copied the JSON reporter
// Added interface to receive JSON (besides stdout)

// jsonInterface must have write method
function DatadogReporter(runner, jsonInterface) {
    Base.call(this, runner);

    var results = {
        stats:"",
        tests:[],
        passes: [],
        failures:[],
        pending:[]
    };

    runner.on("test end", function(test) {
        results.tests.push(test);
    });

    runner.on("pass", function (test) {
        results.passes.push(test);
    });

    runner.on("fail", function (test) {
        results.failures.push(test);
    });

    runner.on("pending", function (test) {
        results.pending.push(test);
    });

    runner.on('end', function() {
        var data = {
            stats: this.stats,
            passes: results.passes.map(strip_test),
            failures: results.failures.map(strip_test),
            pending: results.pending.map(strip_test)
        };

        runner.testResults = data;

        var json = JSON.stringify(data, null,  2);

        process.stdout.write(json);

        jsonInterface.write(json);
    });

    function strip_test(test) {
        return {
            title: test.title,
            fullTitle: test.fullTitle(),
            duration: test.duration,
            err: JSON.stringify(test.err || {})
        };
    }

}<commit_msg>Moved reporter class out<commit_after><|endoftext|>


<commit_before>/**
  * Copyright (c) 2013 Ivo Wetzel.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a copy
  * of this software and associated documentation files (the "Software"), to deal
  * in the Software without restriction, including without limitation the rights
  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  * copies of the Software, and to permit persons to whom the Software is
  * furnished to do so, subject to the following conditions:
  *
  * The above copyright notice and this permission notice shall be included in
  * all copies or substantial portions of the Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
var Server = require('./server/Server').Server,
    PersonaAuth = require('./auth/Persona').Auth,
    util = require('util');

var srv = new Server({

    session: {
        tickRate: 100,
        tickBuffer: 3
    },

    auth: {
        Manager: PersonaAuth,
        config: {
            host: 'localhost'
        }
    }

});

srv.listen(4444, 'localhost', true);

process.on('SIGINT', function() {
    console.log('RECEIVED SIGINT');
    srv.shutdown();
    process.exit();
});

<commit_msg>red color stuff<commit_after>/**
  * Copyright (c) 2013 Ivo Wetzel.
  *
  * Permission is hereby granted, free of charge, to any person obtaining a copy
  * of this software and associated documentation files (the "Software"), to deal
  * in the Software without restriction, including without limitation the rights
  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  * copies of the Software, and to permit persons to whom the Software is
  * furnished to do so, subject to the following conditions:
  *
  * The above copyright notice and this permission notice shall be included in
  * all copies or substantial portions of the Software.
  *
  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  * THE SOFTWARE.
  */
var Server = require('./server/Server').Server,
    PersonaAuth = require('./auth/Persona').Auth,
    is = require('./lib/is').is,
    util = require('util');

var srv = new Server({

    session: {
        tickRate: 100,
        tickBuffer: 3
    },

    auth: {
        Manager: PersonaAuth,
        config: {
            audience: 'localhost'
        }
    }

});

srv.listen(4444, 'localhost', true);

process.on('SIGINT', function() {
    is.error('============= RECEIVED SIGINT =============');
    srv.shutdown();
    process.exit();
});

<|endoftext|>


<commit_before>/* eslint-disable @typescript-eslint/no-var-requires */
const pleaseUpgradeNode = require('please-upgrade-node')
const pkg = require('./package.json')

// Node version isn't supported, skip
pleaseUpgradeNode(pkg, {
  message(requiredVersion) {
    return 'Husky requires Node ' + requiredVersion + ", can't run Git hook."
  }
})

// Node version is supported, continue
require('./lib/runner/bin')
<commit_msg>Add shebang to run.js (#528)<commit_after>#!/usr/bin/env node
/* eslint-disable @typescript-eslint/no-var-requires */
const pleaseUpgradeNode = require('please-upgrade-node')
const pkg = require('./package.json')

// Node version isn't supported, skip
pleaseUpgradeNode(pkg, {
  message(requiredVersion) {
    return 'Husky requires Node ' + requiredVersion + ", can't run Git hook."
  }
})

// Node version is supported, continue
require('./lib/runner/bin')
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

//dependencies
var watchr = require('watchr'),
    path = require('path'),
    findit = require('findit2'),
    fs = require('fs'),
    cp = require('child_process');

//our app object
var app = {
  process: undefined,
  start: function() {
    app.process = cp.fork('./app.js');
    console.log('RUN [✔] App started');
    app.process.on('close', function(code, signal) {
      console.log('RUN {!} Attempting to restart app...');
      app.restart();
    });
  },
  restartLog: [],
  restart: function() {
    app.restartLog.push(new Date());
    app.start();
    setTimeout(function() {
      if (app.restartLog.length >= 3) {
        console.log('RUN {#} Mayday relay: app is sickly.');
        app.process.kill();
        process.exit(1);
      }
      else {
        app.restartLog = [];
      }
    }, 1000);
  }
};

//are there any special commands to run?
if (process.argv.length > 2) {
  var command = process.argv[2];

  if ('build' === command) {
    console.log('RUN {!} Roger that! Running the build...');
    var filterToBuild = function(filePath, stat) {
      var isLESS = /\.less/.test(filePath);
      var isJS = /\.js/.test(filePath) && !/\.min\.js/.test(filePath);
      if (isLESS || isJS) { build(filePath); }
    };
    findit.find('public/layouts').on('file', filterToBuild);
    findit.find('public/views').on('file', filterToBuild);
  }
  else if ('clean' === command) {
    console.log('RUN {!} Roger that! Cleaning build files...');
    var filterToDelete = function(filePath, stat) {
      var isCSS = /\.min\.css/.test(filePath);
      var isJS = /\.min\.js/.test(filePath);
      if (isCSS || isJS) {
        fs.unlink(filePath);
        console.log('RUN [✔] Deleted: '+ filePath);
      }
    };
    findit.find('public/layouts').on('file', filterToDelete);
    findit.find('public/views').on('file', filterToDelete);
  }
  else {
    console.log('RUN {!} Sorry. I\'m not sure what you mean.');
  }
}
//no special commands
else {
  //first time starting up
  app.start();

  //listen to changes in public asset files
  watchr.watch({
    paths: [
      'public/layouts/',
      'public/views/',
      'public/less/'
    ],
    ignoreCustomPatterns: /\.min\.js|\.min\.css/i,
    listener: function(changeType, filePath, fileCurrentStat, filePreviousStat){
      if ('delete' === changeType) { return; }
      console.log('RUN {*} Change detected: '+ filePath);
      build(filePath);
    }
  });

  //listen to changes in app files
  watchr.watch({
    paths: [
      'app.js',
      'layouts/',
      'models.js',
      'passport.js',
      'routes.js',
      'schema/',
      'utilities/',
      'utilities.js',
      'views/'
    ],
    listener: function(changeType, filePath, fileCurrentStat, filePreviousStat) {
      if ('delete' === changeType) { return; }
      console.log('RUN {*} Change detected: '+ filePath);

      //kill the app when script files change
      if (/\.js/.test(filePath)) {
        lintJS(filePath, function() {
          console.log('RUN {!} Killing app...');
          app.process.kill();
        });
      }
    }
  });
}

//a function that handles building assets
var build = function(filePath) {
  //just lint if it's our less tools
  if (/public\/less/.test(filePath)) {
    return lintLESS(filePath);
  }

  //add dependencies for core styles
  var dependencies;
  if (/public\/layouts\/core\.less/.test(filePath)) {
    dependencies = [
      'public/less/bootstrap-build.less',
      'public/vendor/font-awesome/less/font-awesome.less'
    ];
  }

  //add dependencies for core js
  if (/public\/layouts\/core\.js/.test(filePath)) {
    dependencies = [
      'public/vendor/jquery/jquery-1.10.2.js',
      'public/vendor/underscore/underscore.js',
      'public/vendor/backbone/backbone.js',
      'public/vendor/bootstrap/js/affix.js',
      'public/vendor/bootstrap/js/alert.js',
      'public/vendor/bootstrap/js/button.js',
      'public/vendor/bootstrap/js/carousel.js',
      'public/vendor/bootstrap/js/collapse.js',
      'public/vendor/bootstrap/js/dropdown.js',
      'public/vendor/bootstrap/js/modal.js',
      'public/vendor/bootstrap/js/tooltip.js',
      'public/vendor/bootstrap/js/popover.js',
      'public/vendor/bootstrap/js/scrollspy.js',
      'public/vendor/bootstrap/js/tab.js',
      'public/vendor/bootstrap/js/transition.js',
      'public/vendor/moment/moment.js'
    ];
  }

  //build less files
  if (/\.less/.test(filePath)) {
    lintLESS(filePath);
    compileLESS(filePath, dependencies);
  }

  //build js files
  if (/\.js/.test(filePath)) {
    lintJS(filePath);
    compileJS(filePath, dependencies);
  }
};

//a function that lints less files
var lintLESS = function(filePath, cb) {
  var lesscmd = cp.spawn(createCommand('node_modules/.bin/recess'), [filePath, '--noSummary', '--strictPropertyOrder', 'false']);
  lesscmd.stdout.on('data', function(d) { process.stdout.write(d); });
  lesscmd.stderr.on('data', function(d) { process.stderr.write(d); });
  lesscmd.on('close', function (code) {
    console.log('RUN [✔] Linted: '+ filePath);
    if (cb) { cb(); }
  });
};

//a function that compiles less files
var compileLESS = function(filePath, dependencyPaths) {
  if (!dependencyPaths) { dependencyPaths = []; }
  var args = ['--compress'];
  args = args.concat(dependencyPaths, filePath);

  var basePath = path.dirname(filePath) +'/';
  var lessBaseName = path.basename(filePath, '.less');
  var lessMinName = lessBaseName + '.min.css';
  var lessMinPath = basePath + lessMinName;

  var cssStream = fs.createWriteStream(lessMinPath);
  var lesscmd = cp.spawn(createCommand('node_modules/.bin/recess'), args);
  lesscmd.stdout.on('data', function(d) { cssStream.write(d); });
  lesscmd.stderr.on('data', function(d) { process.stderr.write(d); });
  lesscmd.on('close', function (code) {
    cssStream.end();
    console.log('RUN [✔] Compiled: '+ filePath +' > '+ lessMinName);
  });
};

//a function that lints javascript files
var lintJS = function(filePath, cb) {
  var configFile = './.jshintrc-client';
  if (!/public\//.test(filePath)) {
    configFile = './.jshintrc-server';
  }
  var hintcmd = cp.spawn(createCommand('node_modules/.bin/jshint'), [filePath, '--config', configFile]);
  hintcmd.stdout.on('data', function(d) { process.stdout.write(d); });
  hintcmd.stderr.on('data', function(d) { process.stderr.write(d); });
  hintcmd.on('close', function (code) {
    console.log('RUN [✔] Linted: '+ filePath);
    if (cb) { cb(); }
  });
};

//a function that compiles javascript files
var compileJS = function(filePath, dependencyPaths) {
  var basePath = path.dirname(filePath) +'/';
  var jsBaseName = path.basename(filePath, '.js');
  var jsMinName = jsBaseName + '.min.js';
  var jsMinPath = basePath + jsMinName;
  var jsMapName = jsMinName + '.map';
  var jsMapPath = basePath + jsMapName;

  var args = dependencyPaths || [];
  args = args.concat([
    filePath,
    '--output', jsMinPath,
    '--source-map', jsMapPath,
    '--source-map-root', '/',
    '--prefix', '1',
    '--source-map-url', jsMapName
  ]);

  var uglycmd = cp.spawn(createCommand('node_modules/.bin/uglifyjs'), args);
  uglycmd.stdout.on('data', function(d) { process.stdout.write(d); });
  uglycmd.stderr.on('data', function(d) { process.stderr.write(d); });
  uglycmd.on('close', function (code) {
    console.log('RUN [✔] Compiled: '+ filePath +' > '+ jsMinName);
  });
};

// Create the proper command for Windows environments
var createCommand = function(command) {
  if (!!process.platform.match(/^win/)) {
    return command.replace(/\//g, '\\') + '.cmd';
  }
  return command;
}<commit_msg>Updates based on feedback.<commit_after>#!/usr/bin/env node
'use strict';

//dependencies
var watchr = require('watchr'),
    path = require('path'),
    findit = require('findit2'),
    fs = require('fs'),
    cp = require('child_process');

//our app object
var app = {
  process: undefined,
  start: function() {
    app.process = cp.fork('./app.js');
    console.log('RUN [✔] App started');
    app.process.on('close', function(code, signal) {
      console.log('RUN {!} Attempting to restart app...');
      app.restart();
    });
  },
  restartLog: [],
  restart: function() {
    app.restartLog.push(new Date());
    app.start();
    setTimeout(function() {
      if (app.restartLog.length >= 3) {
        console.log('RUN {#} Mayday relay: app is sickly.');
        app.process.kill();
        process.exit(1);
      }
      else {
        app.restartLog = [];
      }
    }, 1000);
  }
};

//are there any special commands to run?
if (process.argv.length > 2) {
  var command = process.argv[2];

  if ('build' === command) {
    console.log('RUN {!} Roger that! Running the build...');
    var filterToBuild = function(filePath, stat) {
      var isLESS = /\.less/.test(filePath);
      var isJS = /\.js/.test(filePath) && !/\.min\.js/.test(filePath);
      if (isLESS || isJS) { build(filePath); }
    };
    findit.find('public/layouts').on('file', filterToBuild);
    findit.find('public/views').on('file', filterToBuild);
  }
  else if ('clean' === command) {
    console.log('RUN {!} Roger that! Cleaning build files...');
    var filterToDelete = function(filePath, stat) {
      var isCSS = /\.min\.css/.test(filePath);
      var isJS = /\.min\.js/.test(filePath);
      if (isCSS || isJS) {
        fs.unlink(filePath);
        console.log('RUN [✔] Deleted: '+ filePath);
      }
    };
    findit.find('public/layouts').on('file', filterToDelete);
    findit.find('public/views').on('file', filterToDelete);
  }
  else {
    console.log('RUN {!} Sorry. I\'m not sure what you mean.');
  }
}
//no special commands
else {
  //first time starting up
  app.start();

  //listen to changes in public asset files
  watchr.watch({
    paths: [
      'public/layouts/',
      'public/views/',
      'public/less/'
    ],
    ignoreCustomPatterns: /\.min\.js|\.min\.css/i,
    listener: function(changeType, filePath, fileCurrentStat, filePreviousStat){
      if ('delete' === changeType) { return; }
      console.log('RUN {*} Change detected: '+ filePath);
      build(filePath);
    }
  });

  //listen to changes in app files
  watchr.watch({
    paths: [
      'app.js',
      'layouts/',
      'models.js',
      'passport.js',
      'routes.js',
      'schema/',
      'utilities/',
      'utilities.js',
      'views/'
    ],
    listener: function(changeType, filePath, fileCurrentStat, filePreviousStat) {
      if ('delete' === changeType) { return; }
      console.log('RUN {*} Change detected: '+ filePath);

      //kill the app when script files change
      if (/\.js/.test(filePath)) {
        lintJS(filePath, function() {
          console.log('RUN {!} Killing app...');
          app.process.kill();
        });
      }
    }
  });
}

//a function that handles building assets
var build = function(filePath) {
  //just lint if it's our less tools
  if (/public\/less/.test(filePath)) {
    return lintLESS(filePath);
  }

  //add dependencies for core styles
  var dependencies;
  if (/public\/layouts\/core\.less/.test(filePath)) {
    dependencies = [
      'public/less/bootstrap-build.less',
      'public/vendor/font-awesome/less/font-awesome.less'
    ];
  }

  //add dependencies for core js
  if (/public\/layouts\/core\.js/.test(filePath)) {
    dependencies = [
      'public/vendor/jquery/jquery-1.10.2.js',
      'public/vendor/underscore/underscore.js',
      'public/vendor/backbone/backbone.js',
      'public/vendor/bootstrap/js/affix.js',
      'public/vendor/bootstrap/js/alert.js',
      'public/vendor/bootstrap/js/button.js',
      'public/vendor/bootstrap/js/carousel.js',
      'public/vendor/bootstrap/js/collapse.js',
      'public/vendor/bootstrap/js/dropdown.js',
      'public/vendor/bootstrap/js/modal.js',
      'public/vendor/bootstrap/js/tooltip.js',
      'public/vendor/bootstrap/js/popover.js',
      'public/vendor/bootstrap/js/scrollspy.js',
      'public/vendor/bootstrap/js/tab.js',
      'public/vendor/bootstrap/js/transition.js',
      'public/vendor/moment/moment.js'
    ];
  }

  //build less files
  if (/\.less/.test(filePath)) {
    lintLESS(filePath);
    compileLESS(filePath, dependencies);
  }

  //build js files
  if (/\.js/.test(filePath)) {
    lintJS(filePath);
    compileJS(filePath, dependencies);
  }
};

//a function that lints less files
var lintLESS = function(filePath, cb) {
  var lesscmd = cp.spawn(createCommand('node_modules/.bin/recess'), [filePath, '--noSummary', '--strictPropertyOrder', 'false']);
  lesscmd.stdout.on('data', function(d) { process.stdout.write(d); });
  lesscmd.stderr.on('data', function(d) { process.stderr.write(d); });
  lesscmd.on('close', function (code) {
    console.log('RUN [✔] Linted: '+ filePath);
    if (cb) { cb(); }
  });
};

//a function that compiles less files
var compileLESS = function(filePath, dependencyPaths) {
  if (!dependencyPaths) { dependencyPaths = []; }
  var args = ['--compress'];
  args = args.concat(dependencyPaths, filePath);

  var basePath = path.dirname(filePath) +'/';
  var lessBaseName = path.basename(filePath, '.less');
  var lessMinName = lessBaseName + '.min.css';
  var lessMinPath = basePath + lessMinName;

  var cssStream = fs.createWriteStream(lessMinPath);
  var lesscmd = cp.spawn(createCommand('node_modules/.bin/recess'), args);
  lesscmd.stdout.on('data', function(d) { cssStream.write(d); });
  lesscmd.stderr.on('data', function(d) { process.stderr.write(d); });
  lesscmd.on('close', function (code) {
    cssStream.end();
    console.log('RUN [✔] Compiled: '+ filePath +' > '+ lessMinName);
  });
};

//a function that lints javascript files
var lintJS = function(filePath, cb) {
  var configFile = './.jshintrc-client';
  if (!/public\//.test(filePath)) {
    configFile = './.jshintrc-server';
  }
  var hintcmd = cp.spawn(createCommand('node_modules/.bin/jshint'), [filePath, '--config', configFile]);
  hintcmd.stdout.on('data', function(d) { process.stdout.write(d); });
  hintcmd.stderr.on('data', function(d) { process.stderr.write(d); });
  hintcmd.on('close', function (code) {
    console.log('RUN [✔] Linted: '+ filePath);
    if (cb) { cb(); }
  });
};

//a function that compiles javascript files
var compileJS = function(filePath, dependencyPaths) {
  var basePath = path.dirname(filePath) +'/';
  var jsBaseName = path.basename(filePath, '.js');
  var jsMinName = jsBaseName + '.min.js';
  var jsMinPath = basePath + jsMinName;
  var jsMapName = jsMinName + '.map';
  var jsMapPath = basePath + jsMapName;

  var args = dependencyPaths || [];
  args = args.concat([
    filePath,
    '--output', jsMinPath,
    '--source-map', jsMapPath,
    '--source-map-root', '/',
    '--prefix', '1',
    '--source-map-url', jsMapName
  ]);

  var uglycmd = cp.spawn(createCommand('node_modules/.bin/uglifyjs'), args);
  uglycmd.stdout.on('data', function(d) { process.stdout.write(d); });
  uglycmd.stderr.on('data', function(d) { process.stderr.write(d); });
  uglycmd.on('close', function (code) {
    console.log('RUN [✔] Compiled: '+ filePath +' > '+ jsMinName);
  });
};

//create the proper command for Windows environments
var createCommand = function(command) {
  if (/^win/.test(process.platform)) {
    return command.replace(/\//g, '\\') + '.cmd';
  }
  return command;
};
<|endoftext|>


<commit_before>// Requires
const Discord = require('discord.js')
const fs = require('fs')
const config = require('./config.json');
// Create an instance of a Discord client
const client = new Discord.Client()
// The bot is ready
client.on('ready', () => {
  console.log('Bot Started')
})

client.on('message', (message) => {// when message is sent
  // Set the prefix
  let prefix = config.prefix;

  // Exit and stop if it's not there
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  if (message.content ===("<>")){ // when message is <>
      message.channel.send("Shinies!"); // send running message into the channel where the message was sent
  }

  else if(message.content.startsWith(config.prefix + 'prefix'))
  {
    // if it's not me it won't work
    if(message.author.id !== config.ownerID) return;
  // Gets the prefix from the command (eg. "!prefix +" it will take the "+" from it)
  let newPrefix = message.content.split(' ').slice(1, 2)[0];
  // change the configuration in memory
  config.prefix = newPrefix;

  // Now we have to save the file.
  fs.writeFile('./config.json', JSON.stringify(config));
}
  else if(message.content.startsWith(config.prefix + 'waifu'))
  {
    // if it's not me it won't work
    if(message.author.id !== config.ownerID)
    {
      message.channel.send('Not AA-senpai go away');
    }
    else
    {
    message.channel.send('AA-senpai!');
    }

  }
  else if(message.content.startsWith(config.prefix + 'terracolor'))
  {
      if(message.author.id !== '227596952852758528')
      {
        message.channel.send('Not Terra-senpai go away');
      }
      else
      {
        let args = message.content.split(' ').slice(1);
        let cleaned = args.split('#').slice(1);
          let terracolor = '#'+cleaned[0];

        message.guild.roles.find('name', 'Terra').setColor(terracolor);
        message.channel.send('Here you go~!');
      }

  }
  var commands=[
  ['help','I don\'t know what to help with yet!'],
  ['idoruu','http://i.imgur.com/Emk9LEb.png'],
  ['ruumove','http://i.imgur.com/49dk6gD.png'],
  ['heruusy','http://i.imgur.com/Hdcsu8e.jpg'],
  ['ruuyear','http://i.imgur.com/c6cfRd1.png']
];
  for( i =  0; i<commands.length;i++)
  {
    if (message.content.startsWith(prefix + commands[i][0]))
    {
      message.channel.send(commands[i][1]);
    }

  }
})
client.login(process.env.BOT_TOKEN)
<commit_msg>Updated help command<commit_after>// Requires
const Discord = require('discord.js')
const fs = require('fs')
const config = require('./config.json');
// Create an instance of a Discord client
const client = new Discord.Client()
// The bot is ready
client.on('ready', () => {
  console.log('Bot Started')
})

client.on('message', (message) => {// when message is sent
  // Set the prefix
  let prefix = config.prefix;

  // Exit and stop if it's not there
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  if (message.content ===("<>")){ // when message is <>
      message.channel.send("Shinies!"); // send running message into the channel where the message was sent
  }

  else if(message.content.startsWith(config.prefix + 'prefix'))
  {
    // if it's not me it won't work
    if(message.author.id !== config.ownerID) return;
  // Gets the prefix from the command (eg. "!prefix +" it will take the "+" from it)
  let newPrefix = message.content.split(' ').slice(1, 2)[0];
  // change the configuration in memory
  config.prefix = newPrefix;

  // Now we have to save the file.
  fs.writeFile('./config.json', JSON.stringify(config));
}
  else if(message.content.startsWith(config.prefix + 'waifu'))
  {
    // if it's not me it won't work
    if(message.author.id !== config.ownerID)
    {
      message.channel.send('Not AA-senpai go away');
    }
    else
    {
    message.channel.send('AA-senpai!');
    }

  }
  else if(message.content.startsWith(config.prefix + 'terracolor'))
  {
      if(message.author.id !== '227596952852758528')
      {
        message.channel.send('Not Terra-senpai go away');
      }
      else
      {
        let args = message.content.split(' ').slice(1);
        let cleaned = args.split('#').slice(1);
          let terracolor = '#'+cleaned[0];

        message.guild.roles.find('name', 'Terra').setColor(terracolor);
        message.channel.send('Here you go~!');
      }

  }
  var commands=[
  ['help','I don\'t know what to help with yet! For now, though, I think I can: *idoruu*, *ruumove*,*heruusy*, and *ruuyear*!'],
  ['idoruu','http://i.imgur.com/Emk9LEb.png'],
  ['ruumove','http://i.imgur.com/49dk6gD.png'],
  ['heruusy','http://i.imgur.com/Hdcsu8e.jpg'],
  ['ruuyear','http://i.imgur.com/c6cfRd1.png']
];
  for( i =  0; i<commands.length;i++)
  {
    if (message.content.startsWith(prefix + commands[i][0]))
    {
      message.channel.send(commands[i][1]);
    }

  }
})
client.login(process.env.BOT_TOKEN)
<|endoftext|>


<commit_before>var fs = require('fs')
var http = require("http")
var https = require("https")
var spawn = require('child_process').spawn

var log = function(message){
    console.log('---------', new Date(), '---------')
    console.log(message)
    console.log()
    //TODO write to a log file
}

/*
 * settings.json looks something like this:
{
    "verboseResponses" : "true",
    "secretKey" : "sha1=somelonghashstringthatrepresentsyoursecretkey",
	"ssl" : "true",
	"sslOptions" : {},
    "repositories": [
        {
            "name": "aarongreenwald/grouper",
            "scriptDirectory": "sci/scripts/",
            "script": "grouper.sh"
        },
        {
            "name": "aarongreenwald/sci",
            "scriptDirectory": "sci/scripts/",
            "script": "sci.sh"
        }
    ],
    "port" : 31242
}
*
* port will default to 31242 if ommitted
* verboseSettings will default to false if ommitted
 */

log('sci server starting...')

try {
    var settings = JSON.parse(fs.readFileSync('sci/settings.json', 'utf8'))
}
catch (ex){
    log('Cannot parse settings file: ' + ex)
    throw ex
}

var repositories = settings.repositories
var port = settings.port || 31242

var requestListener = function(request, response) {

    var handleError = function(ex, response){
        response.writeHead(500, {"Content-Type": "text/plain"})
        if (settings.verboseResponses){
            response.write(ex.message || ex ||  'An uknown error occurred')
        }
        else {
            response.write('That didn\'t work. Try again.')
        }
        log(ex.message || ex || 'An unknown error occurred.') //TODO I should log more than this
    }

    var body = ' '
    request.on('data', function (data) {
        body += data
    })

    request.on('end', function () {
        try {
            if (request.headers['user-agent'].indexOf('GitHub-Hookshot/') === -1){
                throw 'This request does not appear to originate from github. If you\'re going to try to break the system, at least try harder.'
            }

            if (request.headers['x-hub-signature'] && request.headers['x-hub-signature'] !== settings.secretKey){
                throw 'You don\'t seem to be who you say you are. You need the key to enter!!'
            }

            if (request.method !== 'POST') {
                throw 'Only POST requests are processed by this server.'
            }

            if (request.headers['x-github-event'] !== 'push'){
                throw 'Only push events are processed by this server.'
            }

            try {
                var payload = JSON.parse(body)
            } catch (ex) {
                throw   {
                            message: 'Unable to parse payload: '
                                    + body
                                    + '\n\nError: ' + ex
                        }
            }

            var found = false
            for (var i = 0; i < repositories.length; i++){
                var repository = repositories[i]
                if (payload.repository.full_name === repository.name){
                    spawn('sh', [ repository.script ], {
                        cwd: repository.scriptDirectory
                    })
                    found = true
                    break
                }
            }
            if (found){
                response.writeHead(200, {"Content-Type": "text/plain"})
                var message = 'Successfully processed continuous integration script for repository: ' + repository.name
                response.write(message)
                log(message) //log more than this
            }
            else {
                throw 'Invalid repository name.'
            }
        } catch (ex) {
            handleError(ex, response)
        }
        finally {
            response.end()
        }
    })
}

log('Listening for POST requests on port ' + port + '...')

if (!settings.ssl){
	http.createServer(requestListener).listen(port)
} else {
	https.createServer(settings.sslOptions || { }, requestListener).listen(port)
}
<commit_msg>use dirname in path to settings file<commit_after>var fs = require('fs')
var http = require("http")
var https = require("https")
var spawn = require('child_process').spawn

var log = function(message){
    console.log('---------', new Date(), '---------')
    console.log(message)
    console.log()
    //TODO write to a log file
}

/*
 * settings.json looks something like this:
{
    "verboseResponses" : "true",
    "secretKey" : "sha1=somelonghashstringthatrepresentsyoursecretkey",
	"ssl" : "true",
	"sslOptions" : {},
    "repositories": [
        {
            "name": "aarongreenwald/grouper",
            "scriptDirectory": "sci/scripts/",
            "script": "grouper.sh"
        },
        {
            "name": "aarongreenwald/sci",
            "scriptDirectory": "sci/scripts/",
            "script": "sci.sh"
        }
    ],
    "port" : 31242
}
*
* port will default to 31242 if ommitted
* verboseSettings will default to false if ommitted
 */

log('sci server starting...')

try {
    var settings = JSON.parse(fs.readFileSync(__dirname + '/settings.json', 'utf8'))
}
catch (ex){
    log('Cannot parse settings file: ' + ex)
    throw ex
}

var repositories = settings.repositories
var port = settings.port || 31242

var requestListener = function(request, response) {

    var handleError = function(ex, response){
        response.writeHead(500, {"Content-Type": "text/plain"})
        if (settings.verboseResponses){
            response.write(ex.message || ex ||  'An uknown error occurred')
        }
        else {
            response.write('That didn\'t work. Try again.')
        }
        log(ex.message || ex || 'An unknown error occurred.') //TODO I should log more than this
    }

    var body = ' '
    request.on('data', function (data) {
        body += data
    })

    request.on('end', function () {
        try {
            if (request.headers['user-agent'].indexOf('GitHub-Hookshot/') === -1){
                throw 'This request does not appear to originate from github. If you\'re going to try to break the system, at least try harder.'
            }

            if (request.headers['x-hub-signature'] && request.headers['x-hub-signature'] !== settings.secretKey){
                throw 'You don\'t seem to be who you say you are. You need the key to enter!!'
            }

            if (request.method !== 'POST') {
                throw 'Only POST requests are processed by this server.'
            }

            if (request.headers['x-github-event'] !== 'push'){
                throw 'Only push events are processed by this server.'
            }

            try {
                var payload = JSON.parse(body)
            } catch (ex) {
                throw   {
                            message: 'Unable to parse payload: '
                                    + body
                                    + '\n\nError: ' + ex
                        }
            }

            var found = false
            for (var i = 0; i < repositories.length; i++){
                var repository = repositories[i]
                if (payload.repository.full_name === repository.name){
                    spawn('sh', [ repository.script ], {
                        cwd: repository.scriptDirectory
                    })
                    found = true
                    break
                }
            }
            if (found){
                response.writeHead(200, {"Content-Type": "text/plain"})
                var message = 'Successfully processed continuous integration script for repository: ' + repository.name
                response.write(message)
                log(message) //log more than this
            }
            else {
                throw 'Invalid repository name.'
            }
        } catch (ex) {
            handleError(ex, response)
        }
        finally {
            response.end()
        }
    })
}

log('Listening for POST requests on port ' + port + '...')

if (!settings.ssl){
	http.createServer(requestListener).listen(port)
} else {
	https.createServer(settings.sslOptions || { }, requestListener).listen(port)
}
<|endoftext|>


<commit_before>/**
 * This file/module contains all configuration for the build process.
 */
module.exports = {
  /**
   * The `build_dir` folder is where our projects are compiled during
   * development and the `compile_dir` folder is where our app resides once it's
   * completely built.
   */
  build_dir: 'build',
  compile_dir: 'bin',
  api_dir: '../doubtfire-api',
  temp_scss_file: 'tmp.scss',

  /**
   * This controls which files need preprocessing. This allows us to have
   * compile-time changes. For now this is just the environment but in the future
   * it might be more complex. Even though it's called preprocessing, I feel like
   * it might be a good idea to try and keep it on the build directory to ensure it's
   * as unobtrusive as possible, and not confuse which files to compile/overwrite
   * actual source code.
   */
  preprocess: {
    api: {
      src: ['build/src/app/api/api-url.js','build/src/app/common/services/configuration-service.js'],
      options: {
        inline: true
      }
    }
  },

  /**
   * This is a collection of file patterns that refer to our app code (the
   * stuff in `src/`). These file paths are used in the configuration of
   * build tasks. `js` is all project javascript, sass tests. `ctpl` contains
   * our reusable components' (`src/common`) template HTML files, while
   * `atpl` contains the same, but for our app's code. `html` is just our
   * main HTML file, `sass` is our main stylesheet, and `unit` contains our
   * app's unit tests.
   */
  app_files: {
    js: [
      'src/**/*.js',
      '!src/**/*.spec.js'
    ],
    jsunit: [
      'src/**/*.spec.js'
    ],

    coffee: [
      'src/**/*.coffee',
      '!src/**/*.spec.coffee'
    ],
    coffeeunit: [
      'src/**/*.spec.coffee'
    ],

    atpl: [
      'src/app/**/*.tpl.html'
    ],
    ctpl: [
      'src/common/**/*.tpl.html'
    ],

    html: [
      'src/index.html'
    ],

    scss: [
      // Do not modify the order
      'src/styles/mixins/**/*.scss',
      'src/styles/common/**/*.scss',
      'src/styles/modules/**/*.scss',
      'src/app/**/*.scss'
    ]
  },

  /**
   * This is the same as `app_files`, except it contains patterns that
   * reference vendor code (`vendor/`) that we need to place into the build
   * process somewhere. While the `app_files` property ensures all
   * standardized files are collected for compilation, it is the user's job
   * to ensure non-standardized (i.e. vendor-related) files are handled
   * appropriately in `vendor_files`.
   *
   * The `vendor_files.compile` holds files that will compile JavaScript
   * or SCSS files into compile vendor files into `doubtfire.{js,css}`.
   * These files are to be automatically concatenated and minified with
   * our project source files.
   *
   * Anything insider `vendor_files.copy` will copy files into the `assets/`
   * directory under the same directory structure (i.e., under `vendor/.../`)
   */
  vendor_files: {
    compile: {
      js: [
        'vendor/jquery/jquery.js',
        'vendor/angular/angular.js',
        'vendor/angular-cookies/angular-cookies.js',
        'vendor/angular-local-storage/angular-local-storage.js',
        'vendor/angular-resource/angular-resource.js',
        'vendor/angular-bootstrap/ui-bootstrap-tpls.js',
        'vendor/angular-ui-router/release/angular-ui-router.js',
        'vendor/d3/d3.js',
        'vendor/angular-charts/dist/angular-charts.js',
        'vendor/flashular/bin/flashular.js',
        'vendor/ngprogress/ngProgress.js',
        'vendor/lodash/lodash.js',
        'vendor/underscore.string/dist/underscore.string.min.js',
        'vendor/momentjs/moment.js',
        'vendor/d3/d3.js',
        'vendor/nvd3/build/nv.d3.js',
        'vendor/angular-nvd3/dist/angular-nvd3.js',
        'vendor/angular-file-upload/angular-file-upload.js',
        'vendor/ng-file-upload/ng-file-upload-all.min.js',
        'vendor/es5-shim/es5-shim.js',
        'vendor/angular-sanitize/angular-sanitize.js',
        'vendor/ng-csv/build/ng-csv.js',
        'vendor/angular-xeditable/dist/js/xeditable.js',
        'vendor/angular-filter/dist/angular-filter.js',
        'vendor/codemirror/lib/codemirror.js',
        'vendor/codemirror/addon/display/placeholder.js',
        'vendor/codemirror/mode/markdown/markdown.js',
        'vendor/angular-ui-codemirror/ui-codemirror.js',
        'vendor/showdown/dist/showdown.js',
        'vendor/angular-markdown-filter/markdown.js',
        'vendor/angular-ui-select/dist/select.js',
        'vendor/angulartics/dist/angulartics.min.js',
        'vendor/angulartics-google-analytics/lib/angulartics-google-analytics.js'
      ],
      jsmap: [
        'vendor/showdown/dist/showdown.js.map'
      ],
      scss: [
        'vendor/bootstrap-sass/**/_bootstrap.scss',
        'vendor/font-awesome/**/font-awesome.scss'
      ],
    },
    copy: {
      js: [

      ],
      jsmap: [
        'vendor/showdown/dist/showdown.js.map'
      ],
      css: [
        "vendor/nvd3/build/nv.d3.css",
        "vendor/angular-xeditable/dist/css/xeditable.css",
        "vendor/codemirror/lib/codemirror.css",
        "vendor/codemirror/theme/xq-light.css"
      ]
    }
  }
};
<commit_msg>QUALITY: Seperate api to name and src<commit_after>/**
 * This file/module contains all configuration for the build process.
 */
module.exports = {
  /**
   * The `build_dir` folder is where our projects are compiled during
   * development and the `compile_dir` folder is where our app resides once it's
   * completely built.
   */
  build_dir: 'build',
  compile_dir: 'bin',
  api_dir: '../doubtfire-api',
  temp_scss_file: 'tmp.scss',

  /**
   * This controls which files need preprocessing. This allows us to have
   * compile-time changes. For now this is just the environment but in the future
   * it might be more complex. Even though it's called preprocessing, I feel like
   * it might be a good idea to try and keep it on the build directory to ensure it's
   * as unobtrusive as possible, and not confuse which files to compile/overwrite
   * actual source code.
   */
  preprocess: {
    api: {
      src: ['build/src/app/api/api-url.js'],
      name: ['build/src/app/common/services/configuration-service.js'],
      options: {
        inline: true
      }
    }
  },

  /**
   * This is a collection of file patterns that refer to our app code (the
   * stuff in `src/`). These file paths are used in the configuration of
   * build tasks. `js` is all project javascript, sass tests. `ctpl` contains
   * our reusable components' (`src/common`) template HTML files, while
   * `atpl` contains the same, but for our app's code. `html` is just our
   * main HTML file, `sass` is our main stylesheet, and `unit` contains our
   * app's unit tests.
   */
  app_files: {
    js: [
      'src/**/*.js',
      '!src/**/*.spec.js'
    ],
    jsunit: [
      'src/**/*.spec.js'
    ],

    coffee: [
      'src/**/*.coffee',
      '!src/**/*.spec.coffee'
    ],
    coffeeunit: [
      'src/**/*.spec.coffee'
    ],

    atpl: [
      'src/app/**/*.tpl.html'
    ],
    ctpl: [
      'src/common/**/*.tpl.html'
    ],

    html: [
      'src/index.html'
    ],

    scss: [
      // Do not modify the order
      'src/styles/mixins/**/*.scss',
      'src/styles/common/**/*.scss',
      'src/styles/modules/**/*.scss',
      'src/app/**/*.scss'
    ]
  },

  /**
   * This is the same as `app_files`, except it contains patterns that
   * reference vendor code (`vendor/`) that we need to place into the build
   * process somewhere. While the `app_files` property ensures all
   * standardized files are collected for compilation, it is the user's job
   * to ensure non-standardized (i.e. vendor-related) files are handled
   * appropriately in `vendor_files`.
   *
   * The `vendor_files.compile` holds files that will compile JavaScript
   * or SCSS files into compile vendor files into `doubtfire.{js,css}`.
   * These files are to be automatically concatenated and minified with
   * our project source files.
   *
   * Anything insider `vendor_files.copy` will copy files into the `assets/`
   * directory under the same directory structure (i.e., under `vendor/.../`)
   */
  vendor_files: {
    compile: {
      js: [
        'vendor/jquery/jquery.js',
        'vendor/angular/angular.js',
        'vendor/angular-cookies/angular-cookies.js',
        'vendor/angular-local-storage/angular-local-storage.js',
        'vendor/angular-resource/angular-resource.js',
        'vendor/angular-bootstrap/ui-bootstrap-tpls.js',
        'vendor/angular-ui-router/release/angular-ui-router.js',
        'vendor/d3/d3.js',
        'vendor/angular-charts/dist/angular-charts.js',
        'vendor/flashular/bin/flashular.js',
        'vendor/ngprogress/ngProgress.js',
        'vendor/lodash/lodash.js',
        'vendor/underscore.string/dist/underscore.string.min.js',
        'vendor/momentjs/moment.js',
        'vendor/d3/d3.js',
        'vendor/nvd3/build/nv.d3.js',
        'vendor/angular-nvd3/dist/angular-nvd3.js',
        'vendor/angular-file-upload/angular-file-upload.js',
        'vendor/ng-file-upload/ng-file-upload-all.min.js',
        'vendor/es5-shim/es5-shim.js',
        'vendor/angular-sanitize/angular-sanitize.js',
        'vendor/ng-csv/build/ng-csv.js',
        'vendor/angular-xeditable/dist/js/xeditable.js',
        'vendor/angular-filter/dist/angular-filter.js',
        'vendor/codemirror/lib/codemirror.js',
        'vendor/codemirror/addon/display/placeholder.js',
        'vendor/codemirror/mode/markdown/markdown.js',
        'vendor/angular-ui-codemirror/ui-codemirror.js',
        'vendor/showdown/dist/showdown.js',
        'vendor/angular-markdown-filter/markdown.js',
        'vendor/angular-ui-select/dist/select.js',
        'vendor/angulartics/dist/angulartics.min.js',
        'vendor/angulartics-google-analytics/lib/angulartics-google-analytics.js'
      ],
      jsmap: [
        'vendor/showdown/dist/showdown.js.map'
      ],
      scss: [
        'vendor/bootstrap-sass/**/_bootstrap.scss',
        'vendor/font-awesome/**/font-awesome.scss'
      ],
    },
    copy: {
      js: [

      ],
      jsmap: [
        'vendor/showdown/dist/showdown.js.map'
      ],
      css: [
        "vendor/nvd3/build/nv.d3.css",
        "vendor/angular-xeditable/dist/css/xeditable.css",
        "vendor/codemirror/lib/codemirror.css",
        "vendor/codemirror/theme/xq-light.css"
      ]
    }
  }
};
<|endoftext|>


<commit_before>/**
 * This file/module contains all configuration for the build process.
 */

var join = require('path').join,
    bowerrc = JSON.parse(require('fs').readFileSync('./.bowerrc', {encoding: 'utf8'})),
    bower = require(bowerrc.json.replace(/^\.?\/?/, './')),
    pkg = require('./package.json'),

    /**
     * The `buildDir` folder is where our projects are compiled during
     * development and the `compileDir` folder is where our app resides once it's
     * completely built.
     */
    buildDir = 'build',
    compileDir = 'compile',
    vendorDir = bowerrc.directory,
    templatesDir = 'templates',
    indexFile = 'index.html',
    jsDir = 'js',
    cssDir = 'css',
    assetsDir = 'assets';

module.exports = {
    buildDir: buildDir,
    compileDir: compileDir,

    // Relative paths to core files and folders for input and output
    indexFile: indexFile,
    jsDir: jsDir,
    cssDir: cssDir,
    assetsDir: assetsDir,
    vendorDir: vendorDir,
    templatesDir: templatesDir,

    // allows settings reuse from package.json and bower.json
    bower: bower,
    pkg: pkg,

    /**
     * Settings for the server task
     * When run, this task will start a connect server on
     * your build directory, great for livereload
     */
    server: {
        port: 8081, // 0 = random port
        host: null, // null/falsy means listen to all, but will auto open localhost

        // Enable disable default auto open
        // false: run with --open to open
        // true: run with --no-open to not open, recommended if port is 0
        openByDefault: false,

        // set to false to prevent request logging
        // set to any non-`true` value to configure the logger
        log: false,

        // Live Reload server port
        lrPort: 35729
    },

    taskOptions: {
        csso: false, // set to true to prevent structural modifications
        jshint: {
            eqeqeq: true,
            camelcase: true,
            freeze: true,
            immed: true,
            latedef: true,
            newcap: true,
            undef: true,
            unused: 'vars',
            //strict: true,
            browser: true,
            globals: {
                angular: false,
                console: false,
                bootbox: false,
                '_': false,
                RESTQuery: false,
                '$': false,
                soundManager: false,
                File: false,
                SparkMD5: false,
                qq: false
            }
        },
        less: {},
        recess: {
            strictPropertyOrder: false,
            noOverqualifying: false,
            noUniversalSelectors: false
        },
        uglify: {
            mangle: false
        }
    },

    /**
     * This is a collection of file patterns that refer to our app code (the
     * stuff in `src/`). These file paths are used in the configuration of
     * build tasks. `js` is all project javascript, less tests. `ctpl` contains
     * our reusable components' (`src/common`) template HTML files, while
     * `atpl` contains the same, but for our app's code. `html` is just our
     * main HTML file, `less` is our main stylesheet, and `unit` contains our
     * app's unit tests.
     */
    appFiles: {
        js: [ 'src/**/*.js', '!src/**/*.spec.js', '!src/assets/**/*.js' ],
        jsunit: [ join(buildDir, '/js/**/*.js'), '!'+join(buildDir, '/js/vendor/**/*.js'), 'src/**/*.spec.js' ],

        tpl: [ 'src/app/**/*.tpl.html', 'src/common/**/*.tpl.html' ],

        html: join('src', indexFile),
        less: 'src/less/main.less',
        assets: join('src', assetsDir, '**/*.*')
    },

    /**
     * Similar to above, except this is the pattern of files to watch
     * for live build and reloading.
     */
    watchFiles: {
        js: [ 'src/**/*.js', '!src/**/*.spec.js', '!src/assets/**/*.js' ],
        //jsunit: [ 'src/**/*.spec.js' ], // watch is handled by the karma plugin!

        tpl: [ 'src/app/**/*.tpl.html', 'src/common/**/*.tpl.html' ],

        html: [ join(buildDir, '**/*'), '!'+join(buildDir,indexFile), join('src',indexFile) ],
        less: [ 'src/**/*.less' ],
        assets: join('src',assetsDir,'**/*.*')
    },

    /**
     * This is a collection of files used during testing only.
     */
    testFiles: {
        config: 'karma.conf.js',
        js: [
            'vendor/angular-mocks/angular-mocks.js'
        ]
    },

    /**
     * This is the same as `app_files`, except it contains patterns that
     * reference vendor code (`vendor/`) that we need to place into the build
     * process somewhere. While the `app_files` property ensures all
     * standardized files are collected for compilation, it is the user's job
     * to ensure non-standardized (i.e. vendor-related) files are handled
     * appropriately in `vendorFiles.js`.
     *
     * The `vendorFiles.js` property holds files to be automatically
     * concatenated and minified with our project source files.
     *
     * The `vendorFiles.assets` property holds any assets to be copied along
     * with our app's assets. This structure is flattened, so it is not
     * recommended that you use wildcards.
     */
    vendorFiles: {
        js: [
            'vendor/jquery/dist/jquery.js',
            'vendor/jquery-ui/ui/jquery-ui.js',
            'vendor/lodash/dist/lodash.js',
            'vendor/angular/angular.js',
            'vendor/angular-sanitize/angular-sanitize.js',
            'vendor/angular-cookies/angular-cookies.js',
            'vendor/angular-bootstrap/ui-bootstrap.js',
            'vendor/angular-bootstrap/ui-bootstrap-tpls.js',
            'vendor/angular-ui-router/release/angular-ui-router.js',
            'vendor/angular-ui-utils/modules/route/route.js',
            'vendor/fineuploader-s3/custom.fineuploader.js',
            'vendor/bootstrap/dist/js/bootstrap.js',
            'vendor/bootbox/bootbox.js',
            'vendor/moment/min/moment.min.js',
            'vendor-custom/ui-sortable/sortable.js'
        ],
        css: [
            'vendor/jquery-ui/themes/base/images/**',
            'vendor/jquery-ui/themes/base/jquery-ui.css',
            'vendor/jquery-ui/themes/base/jquery.ui.theme.css',
            'vendor/fineuploader-s3/custom.fineuploader.css',
            'vendor/fineuploader-s3/*.gif',
            'vendor/fineuploader-s3/placeholders/**'
        ],
        assets: [
            'vendor/bootstrap/dist/fonts/**'
        ]
    }
};
<commit_msg>Broke out vendor files into their own file<commit_after>/**
 * This file/module contains all configuration for the build process.
 */

var join = require('path').join,
    bowerrc = JSON.parse(require('fs').readFileSync('./.bowerrc', {encoding: 'utf8'})),
    bower = require(bowerrc.json.replace(/^\.?\/?/, './')),
    pkg = require('./package.json'),

    /**
     * The `buildDir` folder is where our projects are compiled during
     * development and the `compileDir` folder is where our app resides once it's
     * completely built.
     */
    buildDir = 'build',
    compileDir = 'compile',
    vendorDir = bowerrc.directory,
    templatesDir = 'templates',
    indexFile = 'index.html',
    jsDir = 'js',
    cssDir = 'css',
    assetsDir = 'assets';

module.exports = {
    buildDir: buildDir,
    compileDir: compileDir,

    // Relative paths to core files and folders for input and output
    indexFile: indexFile,
    jsDir: jsDir,
    cssDir: cssDir,
    assetsDir: assetsDir,
    vendorDir: vendorDir,
    templatesDir: templatesDir,

    // allows settings reuse from package.json and bower.json
    bower: bower,
    pkg: pkg,

    /**
     * Settings for the server task
     * When run, this task will start a connect server on
     * your build directory, great for livereload
     */
    server: {
        port: 8081, // 0 = random port
        host: null, // null/falsy means listen to all, but will auto open localhost

        // Enable disable default auto open
        // false: run with --open to open
        // true: run with --no-open to not open, recommended if port is 0
        openByDefault: false,

        // set to false to prevent request logging
        // set to any non-`true` value to configure the logger
        log: false,

        // Live Reload server port
        lrPort: 35729
    },

    taskOptions: {
        csso: false, // set to true to prevent structural modifications
        jshint: {
            eqeqeq: true,
            camelcase: true,
            freeze: true,
            immed: true,
            latedef: true,
            newcap: true,
            undef: true,
            unused: 'vars',
            //strict: true,
            browser: true,
            globals: {
                angular: false,
                console: false,
                bootbox: false,
                '_': false,
                RESTQuery: false,
                '$': false,
                soundManager: false,
                File: false,
                SparkMD5: false,
                qq: false
            }
        },
        less: {},
        recess: {
            strictPropertyOrder: false,
            noOverqualifying: false,
            noUniversalSelectors: false
        },
        uglify: {
            mangle: false
        }
    },

    /**
     * This is a collection of file patterns that refer to our app code (the
     * stuff in `src/`). These file paths are used in the configuration of
     * build tasks. `js` is all project javascript, less tests. `ctpl` contains
     * our reusable components' (`src/common`) template HTML files, while
     * `atpl` contains the same, but for our app's code. `html` is just our
     * main HTML file, `less` is our main stylesheet, and `unit` contains our
     * app's unit tests.
     */
    appFiles: {
        js: [ 'src/**/*.js', '!src/**/*.spec.js', '!src/assets/**/*.js' ],
        jsunit: [ join(buildDir, '/js/**/*.js'), '!'+join(buildDir, '/js/vendor/**/*.js'), 'src/**/*.spec.js' ],

        tpl: [ 'src/app/**/*.tpl.html', 'src/common/**/*.tpl.html' ],

        html: join('src', indexFile),
        less: 'src/less/main.less',
        assets: join('src', assetsDir, '**/*.*')
    },

    /**
     * Similar to above, except this is the pattern of files to watch
     * for live build and reloading.
     */
    watchFiles: {
        js: [ 'src/**/*.js', '!src/**/*.spec.js', '!src/assets/**/*.js' ],
        //jsunit: [ 'src/**/*.spec.js' ], // watch is handled by the karma plugin!

        tpl: [ 'src/app/**/*.tpl.html', 'src/common/**/*.tpl.html' ],

        html: [ join(buildDir, '**/*'), '!'+join(buildDir,indexFile), join('src',indexFile) ],
        less: [ 'src/**/*.less' ],
        assets: join('src',assetsDir,'**/*.*')
    },

    /**
     * This is a collection of files used during testing only.
     */
    testFiles: {
        config: 'karma.conf.js',
        js: [
            'vendor/angular-mocks/angular-mocks.js'
        ]
    },

    vendorFiles: require('./vendorFiles.config.js')
};
<|endoftext|>


<commit_before>'use strict';

var React   = require('react');
var Button  = require('react-native-button');
var Modal   = require('react-native-modalbox');
var Slider  = require('react-native-slider');
var window  = require('Dimensions').get('window');

var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ScrollView
} = require('react-native');

var styles = StyleSheet.create({

  wrapper: {
    paddingTop: 50,
    flex: 1
  },

  modal: {
    justifyContent: 'center',
    alignItems: 'center'
  },

  modal2: {
    height: 230,
    backgroundColor: "#3B5998"
  },

  modal3: {
    height: 300,
    width: 300
  },

  modal4: {
    height: 300
  },

  btn: {
    margin: 10,
    backgroundColor: "#3B5998",
    color: "white",
    padding: 10
  },

  btnModal: {
    position: "absolute",
    top: 0,
    right: 0,
    width: 50,
    height: 50,
    backgroundColor: "transparent"
  },

  text: {
    color: "black",
    fontSize: 22
  }

});

var Example = React.createClass({

  getInitialState: function() {
    return {
      isOpen: false,
      isDisabled: false,
      swipeToClose: true,
      sliderValue: 0.3
    };
  },

  openModal1: function(id) {
    this.refs.modal1.open();
  },

  openModal2: function(id) {
    this.refs.modal2.open();
  },

  openModal3: function(id) {
    this.refs.modal3.open();
  },

  openModal4: function(id) {
    this.refs.modal4.open();
  },

  openModal5: function(id) {
    this.setState({isOpen: true});
  },

  closeModal5: function(id) {
    this.setState({isOpen: false});
  },

  openModal6: function(id) {
    this.refs.modal6.open();
  },

  openModal6: function(id) {
    this.refs.modal6.open();
  },

  toggleDisable: function() {
    this.setState({isDisabled: !this.state.isDisabled});
  },

  toggleSwipeToClose: function() {
    this.setState({swipeToClose: !this.state.swipeToClose});
  },

  onClose: function() {
    console.log('Modal just closed');
  },

  onOpen: function() {
    console.log('Modal just openned');
  },

  onClosingState: function(state) {
    console.log('the open/close of the swipeToClose just changed');
  },

  renderList() {
    var list = [];

    for (var i=0;i<50;i++) {
      list.push(<Text style={styles.text} key={i}>Elem {i}</Text>);
    }

    return list;
  },

  render: function() {

    var BContent = <Button onPress={this.closeModal5} style={[styles.btn, styles.btnModal]}>X</Button>;

    return (
      <View style={styles.wrapper}>
        <Button onPress={this.openModal1} style={styles.btn}>Basic modal</Button>
        <Button onPress={this.openModal2} style={styles.btn}>Position top</Button>
        <Button onPress={this.openModal3} style={styles.btn}>Position centered + backdrop + disable</Button>
        <Button onPress={this.openModal4} style={styles.btn}>Position bottom + backdrop + slider</Button>
        <Button onPress={this.openModal5} style={styles.btn}>Backdrop + backdropContent</Button>
        <Button onPress={this.openModal6} style={styles.btn}>Position bottom + ScrollView</Button>

        <Modal style={[styles.modal, styles.modal1]} ref={"modal1"} swipeToClose={this.state.swipeToClose} onClosed={this.onClose} onOpened={this.onOpen} onClosingState={this.onClosingState}>
          <Text style={styles.text}>Basic modal</Text>
          <Button onPress={this.toggleSwipeToClose} style={styles.btn}>Disable swipeToClose({this.state.swipeToClose ? "true" : "false"})</Button>
        </Modal>

        <Modal style={[styles.modal, styles.modal2]} backdrop={false}  position={"top"} ref={"modal2"}>
          <Text style={[styles.text, {color: "white"}]}>Modal on top</Text>
        </Modal>

        <Modal style={[styles.modal, styles.modal3]} position={"center"} ref={"modal3"} isDisabled={this.state.isDisabled}>
          <Text style={styles.text}>Modal centered</Text>
          <Button onPress={this.toggleDisable} style={styles.btn}>Disable ({this.state.isDisabled ? "true" : "false"})</Button>
        </Modal>

        <Modal style={[styles.modal, styles.modal4]} position={"bottom"} ref={"modal4"}>
          <Text style={styles.text}>Modal on bottom with backdrop</Text>
          <Slider style={{width: 200}} value={this.state.sliderValue} onValueChange={(value) => this.setState({sliderValue: value})} />
        </Modal>

        <Modal isOpen={this.state.isOpen} onClosed={this.closeModal5} style={[styles.modal, styles.modal4]} position={"center"} backdropContent={BContent}>
          <Text style={styles.text}>Modal with backdrop content</Text>
        </Modal>

        <Modal style={[styles.modal, styles.modal4]} position={"bottom"} ref={"modal6"} swipeArea={20}>
          <ScrollView>
            <View style={{width: window.width, paddingLeft: 10}}>
              {this.renderList()}
            </View>
          </ScrollView>
        </Modal>
      </View>
    );
  }
});

AppRegistry.registerComponent('Example', () => Example);
<commit_msg>duplicated code removed<commit_after>'use strict';

var React   = require('react');
var Button  = require('react-native-button');
var Modal   = require('react-native-modalbox');
var Slider  = require('react-native-slider');
var window  = require('Dimensions').get('window');

var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  ScrollView
} = require('react-native');

var styles = StyleSheet.create({

  wrapper: {
    paddingTop: 50,
    flex: 1
  },

  modal: {
    justifyContent: 'center',
    alignItems: 'center'
  },

  modal2: {
    height: 230,
    backgroundColor: "#3B5998"
  },

  modal3: {
    height: 300,
    width: 300
  },

  modal4: {
    height: 300
  },

  btn: {
    margin: 10,
    backgroundColor: "#3B5998",
    color: "white",
    padding: 10
  },

  btnModal: {
    position: "absolute",
    top: 0,
    right: 0,
    width: 50,
    height: 50,
    backgroundColor: "transparent"
  },

  text: {
    color: "black",
    fontSize: 22
  }

});

var Example = React.createClass({

  getInitialState: function() {
    return {
      isOpen: false,
      isDisabled: false,
      swipeToClose: true,
      sliderValue: 0.3
    };
  },

  openModal1: function(id) {
    this.refs.modal1.open();
  },

  openModal2: function(id) {
    this.refs.modal2.open();
  },

  openModal3: function(id) {
    this.refs.modal3.open();
  },

  openModal4: function(id) {
    this.refs.modal4.open();
  },

  openModal5: function(id) {
    this.setState({isOpen: true});
  },

  closeModal5: function(id) {
    this.setState({isOpen: false});
  },

  openModal6: function(id) {
    this.refs.modal6.open();
  },

  toggleDisable: function() {
    this.setState({isDisabled: !this.state.isDisabled});
  },

  toggleSwipeToClose: function() {
    this.setState({swipeToClose: !this.state.swipeToClose});
  },

  onClose: function() {
    console.log('Modal just closed');
  },

  onOpen: function() {
    console.log('Modal just openned');
  },

  onClosingState: function(state) {
    console.log('the open/close of the swipeToClose just changed');
  },

  renderList() {
    var list = [];

    for (var i=0;i<50;i++) {
      list.push(<Text style={styles.text} key={i}>Elem {i}</Text>);
    }

    return list;
  },

  render: function() {

    var BContent = <Button onPress={this.closeModal5} style={[styles.btn, styles.btnModal]}>X</Button>;

    return (
      <View style={styles.wrapper}>
        <Button onPress={this.openModal1} style={styles.btn}>Basic modal</Button>
        <Button onPress={this.openModal2} style={styles.btn}>Position top</Button>
        <Button onPress={this.openModal3} style={styles.btn}>Position centered + backdrop + disable</Button>
        <Button onPress={this.openModal4} style={styles.btn}>Position bottom + backdrop + slider</Button>
        <Button onPress={this.openModal5} style={styles.btn}>Backdrop + backdropContent</Button>
        <Button onPress={this.openModal6} style={styles.btn}>Position bottom + ScrollView</Button>

        <Modal style={[styles.modal, styles.modal1]} ref={"modal1"} swipeToClose={this.state.swipeToClose} onClosed={this.onClose} onOpened={this.onOpen} onClosingState={this.onClosingState}>
          <Text style={styles.text}>Basic modal</Text>
          <Button onPress={this.toggleSwipeToClose} style={styles.btn}>Disable swipeToClose({this.state.swipeToClose ? "true" : "false"})</Button>
        </Modal>

        <Modal style={[styles.modal, styles.modal2]} backdrop={false}  position={"top"} ref={"modal2"}>
          <Text style={[styles.text, {color: "white"}]}>Modal on top</Text>
        </Modal>

        <Modal style={[styles.modal, styles.modal3]} position={"center"} ref={"modal3"} isDisabled={this.state.isDisabled}>
          <Text style={styles.text}>Modal centered</Text>
          <Button onPress={this.toggleDisable} style={styles.btn}>Disable ({this.state.isDisabled ? "true" : "false"})</Button>
        </Modal>

        <Modal style={[styles.modal, styles.modal4]} position={"bottom"} ref={"modal4"}>
          <Text style={styles.text}>Modal on bottom with backdrop</Text>
          <Slider style={{width: 200}} value={this.state.sliderValue} onValueChange={(value) => this.setState({sliderValue: value})} />
        </Modal>

        <Modal isOpen={this.state.isOpen} onClosed={this.closeModal5} style={[styles.modal, styles.modal4]} position={"center"} backdropContent={BContent}>
          <Text style={styles.text}>Modal with backdrop content</Text>
        </Modal>

        <Modal style={[styles.modal, styles.modal4]} position={"bottom"} ref={"modal6"} swipeArea={20}>
          <ScrollView>
            <View style={{width: window.width, paddingLeft: 10}}>
              {this.renderList()}
            </View>
          </ScrollView>
        </Modal>
      </View>
    );
  }
});

AppRegistry.registerComponent('Example', () => Example);
<|endoftext|>


<commit_before>/**
 * FastPriorityQueue.js : a fast heap-based priority queue  in JavaScript.
 * (c) the authors
 * Licensed under the Apache License, Version 2.0.
 *
 * Speed-optimized heap-based priority queue for modern browsers and JavaScript engines.
 *
 * Usage :
         Installation (in shell, if you use node):
         $ npm install fastpriorityqueue

         Running test program (in JavaScript):

         // var FastPriorityQueue = require("fastpriorityqueue");// in node
         var x = new FastPriorityQueue();
         x.add(1);
         x.add(0);
         x.add(5);
         x.add(4);
         x.add(3);
         x.peek(); // should return 0, leaves x unchanged
         x.size; // should return 5, leaves x unchanged
         while(!x.isEmpty()) {
           console.log(x.poll());
         } // will print 0 1 3 4 5
         x.trim(); // (optional) optimizes memory usage
 */
'use strict';

var defaultcomparator = function(a, b) {
  return a < b;
};

// the provided comparator function should take a, b and return *true* when a < b
function FastPriorityQueue(comparator) {
  if (!(this instanceof FastPriorityQueue)) return new FastPriorityQueue(comparator);
  this.array = [];
  this.size = 0;
  this.compare = comparator || defaultcomparator;
}

// copy the priority queue into another, and return it. Queue items are shallow-copied.
// Runs in `O(n)` time.
FastPriorityQueue.prototype.clone = function() {
  var fpq = new FastPriorityQueue(this.compare);
  fpq.size = this.size;
  fpq.array = this.array.slice(0, this.size);
  return fpq;
};

// Add an element into the queue
// runs in O(log n) time
FastPriorityQueue.prototype.add = function(myval) {
  var i = this.size;
  this.array[this.size] = myval;
  this.size += 1;
  var p;
  var ap;
  while (i > 0) {
    p = (i - 1) >> 1;
    ap = this.array[p];
    if (!this.compare(myval, ap)) {
      break;
    }
    this.array[i] = ap;
    i = p;
  }
  this.array[i] = myval;
};

// replace the content of the heap by provided array and "heapify it"
FastPriorityQueue.prototype.heapify = function(arr) {
  this.array = arr;
  this.size = arr.length;
  var i;
  for (i = this.size >> 1; i >= 0; i--) {
    this._percolateDown(i);
  }
};

// for internal use
FastPriorityQueue.prototype._percolateUp = function(i, force) {
  var myval = this.array[i];
  var p;
  var ap;
  while (i > 0) {
    p = (i - 1) >> 1;
    ap = this.array[p];
    // force will skip the compare
    if (!force && !this.compare(myval, ap)) {
      break;
    }
    this.array[i] = ap;
    i = p;
  }
  this.array[i] = myval;
};

// for internal use
FastPriorityQueue.prototype._percolateDown = function(i) {
  var size = this.size;
  var hsize = this.size >>> 1;
  var ai = this.array[i];
  var l;
  var r;
  var bestc;
  while (i < hsize) {
    l = (i << 1) + 1;
    r = l + 1;
    bestc = this.array[l];
    if (r < size) {
      if (this.compare(this.array[r], bestc)) {
        l = r;
        bestc = this.array[r];
      }
    }
    if (!this.compare(bestc, ai)) {
      break;
    }
    this.array[i] = bestc;
    i = l;
  }
  this.array[i] = ai;
};

// internal
// _removeAt(index) will remove the item at the given index from the queue,
// retaining balance. returns the removed item, or undefined if nothing is removed.
FastPriorityQueue.prototype._removeAt = function(index) {
  if (index > this.size - 1 || index < 0) return undefined;

  // impl1:
  //this.array.splice(index, 1);
  //this.heapify(this.array);
  // impl2:
  this._percolateUp(index, true);
  return this.poll();
};

// remove(myval) will remove an item matching the provided value from the
// queue, checked for equality by using the queue's comparator.
// return true if removed, false otherwise.
FastPriorityQueue.prototype.remove = function(myval) {
  for (var i = 0; i < this.size; i++) {
    if (!this.compare(this.array[i], myval) && !this.compare(myval, this.array[i])) {
      // items match, comparator returns false both ways, remove item
      this._removeAt(i);
      return true;
    }
  }
  return false;
};

// internal
// removes and returns items for which the callback returns true.
FastPriorityQueue.prototype._batchRemove = function(callback, limit) {
  // initialize return array with max size of the limit or current queue size
  var retArr = new Array(limit ? limit : this.size);
  var count = 0;

  if (typeof callback === 'function' && this.size) {
    var i = 0;
    while (i < this.size && count < retArr.length) {
      if (callback(this.array[i])) {
        retArr[count] = this._removeAt(i);
        count++;
        // move up a level in the heap if we remove an item
        i = i >> 1;
      } else {
        i++;
      }
    }
  }
  retArr.length = count;
  return retArr;
}

// removeOne(callback) will execute the callback function for each item of the queue
// and will remove the first item for which the callback will return true.
// return the removed item, or undefined if nothing is removed.
FastPriorityQueue.prototype.removeOne = function(callback) {
  var arr = this._batchRemove(callback, 1);
  return arr.length > 0 ? arr[0] : undefined;
};

// remove(callback[, limit]) will execute the callback function for each item of
// the queue and will remove each item for which the callback returns true, up to
// a max limit of removed items if specified or no limit if unspecified.
// return an array containing the removed items.
FastPriorityQueue.prototype.removeMany = function(callback, limit) {
  return this._batchRemove(callback, limit);
};

// Look at the top of the queue (one of the smallest elements) without removing it
// executes in constant time
//
// Calling peek on an empty priority queue returns
// the "undefined" value.
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/undefined
//
FastPriorityQueue.prototype.peek = function() {
  if (this.size == 0) return undefined;
  return this.array[0];
};

// remove the element on top of the heap (one of the smallest elements)
// runs in logarithmic time
//
// If the priority queue is empty, the function returns the
// "undefined" value.
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/undefined
//
// For long-running and large priority queues, or priority queues
// storing large objects, you may  want to call the trim function
// at strategic times to recover allocated memory.
FastPriorityQueue.prototype.poll = function() {
  if (this.size == 0) return undefined;
  var ans = this.array[0];
  if (this.size > 1) {
    this.array[0] = this.array[--this.size];
    this._percolateDown(0);
  } else {
    this.size -= 1;
  }
  return ans;
};

// This function adds the provided value to the heap, while removing
// and returning one of the smallest elements (like poll). The size of the queue
// thus remains unchanged.
FastPriorityQueue.prototype.replaceTop = function(myval) {
  if (this.size == 0) return undefined;
  var ans = this.array[0];
  this.array[0] = myval;
  this._percolateDown(0);
  return ans;
};

// recover unused memory (for long-running priority queues)
FastPriorityQueue.prototype.trim = function() {
  this.array = this.array.slice(0, this.size);
};

// Check whether the heap is empty
FastPriorityQueue.prototype.isEmpty = function() {
  return this.size === 0;
};

// iterate over the items in order, pass a callback that receives (item, index) as args.
// TODO once we transpile, uncomment
// if (Symbol && Symbol.iterator) {
//   FastPriorityQueue.prototype[Symbol.iterator] = function*() {
//     if (this.isEmpty()) return;
//     var fpq = this.clone();
//     while (!fpq.isEmpty()) {
//       yield fpq.poll();
//     }
//   };
// }
FastPriorityQueue.prototype.forEach = function(callback) {
  if (this.isEmpty() || typeof callback != 'function') return;
  var i = 0;
  var fpq = this.clone();
  while (!fpq.isEmpty()) {
    callback(fpq.poll(), i++);
  }
};

// return the k 'smallest' elements of the queue as an array,
// runs in O(k log k) time, the elements are not removed
// from the priority queue.
FastPriorityQueue.prototype.kSmallest = function(k) {
  if (this.size == 0) return [];
  k = Math.min(this.size, k);
  var fpq = new FastPriorityQueue(this.compare);
  const newSize = Math.min((k > 0 ? Math.pow(2, k - 1) : 0) + 1, this.size);
  fpq.size = newSize;
  fpq.array = this.array.slice(0, newSize);

  var smallest = new Array(k);
  for (var i = 0; i < k; i++) {
    smallest[i] = fpq.poll();
  }
  return smallest;
}

module.exports = FastPriorityQueue;
<commit_msg>The callback should be a pure function.<commit_after>/**
 * FastPriorityQueue.js : a fast heap-based priority queue  in JavaScript.
 * (c) the authors
 * Licensed under the Apache License, Version 2.0.
 *
 * Speed-optimized heap-based priority queue for modern browsers and JavaScript engines.
 *
 * Usage :
         Installation (in shell, if you use node):
         $ npm install fastpriorityqueue

         Running test program (in JavaScript):

         // var FastPriorityQueue = require("fastpriorityqueue");// in node
         var x = new FastPriorityQueue();
         x.add(1);
         x.add(0);
         x.add(5);
         x.add(4);
         x.add(3);
         x.peek(); // should return 0, leaves x unchanged
         x.size; // should return 5, leaves x unchanged
         while(!x.isEmpty()) {
           console.log(x.poll());
         } // will print 0 1 3 4 5
         x.trim(); // (optional) optimizes memory usage
 */
'use strict';

var defaultcomparator = function(a, b) {
  return a < b;
};

// the provided comparator function should take a, b and return *true* when a < b
function FastPriorityQueue(comparator) {
  if (!(this instanceof FastPriorityQueue)) return new FastPriorityQueue(comparator);
  this.array = [];
  this.size = 0;
  this.compare = comparator || defaultcomparator;
}

// copy the priority queue into another, and return it. Queue items are shallow-copied.
// Runs in `O(n)` time.
FastPriorityQueue.prototype.clone = function() {
  var fpq = new FastPriorityQueue(this.compare);
  fpq.size = this.size;
  fpq.array = this.array.slice(0, this.size);
  return fpq;
};

// Add an element into the queue
// runs in O(log n) time
FastPriorityQueue.prototype.add = function(myval) {
  var i = this.size;
  this.array[this.size] = myval;
  this.size += 1;
  var p;
  var ap;
  while (i > 0) {
    p = (i - 1) >> 1;
    ap = this.array[p];
    if (!this.compare(myval, ap)) {
      break;
    }
    this.array[i] = ap;
    i = p;
  }
  this.array[i] = myval;
};

// replace the content of the heap by provided array and "heapify it"
FastPriorityQueue.prototype.heapify = function(arr) {
  this.array = arr;
  this.size = arr.length;
  var i;
  for (i = this.size >> 1; i >= 0; i--) {
    this._percolateDown(i);
  }
};

// for internal use
FastPriorityQueue.prototype._percolateUp = function(i, force) {
  var myval = this.array[i];
  var p;
  var ap;
  while (i > 0) {
    p = (i - 1) >> 1;
    ap = this.array[p];
    // force will skip the compare
    if (!force && !this.compare(myval, ap)) {
      break;
    }
    this.array[i] = ap;
    i = p;
  }
  this.array[i] = myval;
};

// for internal use
FastPriorityQueue.prototype._percolateDown = function(i) {
  var size = this.size;
  var hsize = this.size >>> 1;
  var ai = this.array[i];
  var l;
  var r;
  var bestc;
  while (i < hsize) {
    l = (i << 1) + 1;
    r = l + 1;
    bestc = this.array[l];
    if (r < size) {
      if (this.compare(this.array[r], bestc)) {
        l = r;
        bestc = this.array[r];
      }
    }
    if (!this.compare(bestc, ai)) {
      break;
    }
    this.array[i] = bestc;
    i = l;
  }
  this.array[i] = ai;
};

// internal
// _removeAt(index) will remove the item at the given index from the queue,
// retaining balance. returns the removed item, or undefined if nothing is removed.
FastPriorityQueue.prototype._removeAt = function(index) {
  if (index > this.size - 1 || index < 0) return undefined;

  // impl1:
  //this.array.splice(index, 1);
  //this.heapify(this.array);
  // impl2:
  this._percolateUp(index, true);
  return this.poll();
};

// remove(myval) will remove an item matching the provided value from the
// queue, checked for equality by using the queue's comparator.
// return true if removed, false otherwise.
FastPriorityQueue.prototype.remove = function(myval) {
  for (var i = 0; i < this.size; i++) {
    if (!this.compare(this.array[i], myval) && !this.compare(myval, this.array[i])) {
      // items match, comparator returns false both ways, remove item
      this._removeAt(i);
      return true;
    }
  }
  return false;
};

// internal
// removes and returns items for which the callback returns true.
FastPriorityQueue.prototype._batchRemove = function(callback, limit) {
  // initialize return array with max size of the limit or current queue size
  var retArr = new Array(limit ? limit : this.size);
  var count = 0;

  if (typeof callback === 'function' && this.size) {
    var i = 0;
    while (i < this.size && count < retArr.length) {
      if (callback(this.array[i])) {
        retArr[count] = this._removeAt(i);
        count++;
        // move up a level in the heap if we remove an item
        i = i >> 1;
      } else {
        i++;
      }
    }
  }
  retArr.length = count;
  return retArr;
}

// removeOne(callback) will execute the callback function for each item of the queue
// and will remove the first item for which the callback will return true.
// return the removed item, or undefined if nothing is removed.
FastPriorityQueue.prototype.removeOne = function(callback) {
  var arr = this._batchRemove(callback, 1);
  return arr.length > 0 ? arr[0] : undefined;
};

// remove(callback[, limit]) will execute the callback function for each item of
// the queue and will remove each item for which the callback returns true, up to
// a max limit of removed items if specified or no limit if unspecified.
// return an array containing the removed items.
// The callback function should be a pure function.
FastPriorityQueue.prototype.removeMany = function(callback, limit) {
  return this._batchRemove(callback, limit);
};

// Look at the top of the queue (one of the smallest elements) without removing it
// executes in constant time
//
// Calling peek on an empty priority queue returns
// the "undefined" value.
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/undefined
//
FastPriorityQueue.prototype.peek = function() {
  if (this.size == 0) return undefined;
  return this.array[0];
};

// remove the element on top of the heap (one of the smallest elements)
// runs in logarithmic time
//
// If the priority queue is empty, the function returns the
// "undefined" value.
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/undefined
//
// For long-running and large priority queues, or priority queues
// storing large objects, you may  want to call the trim function
// at strategic times to recover allocated memory.
FastPriorityQueue.prototype.poll = function() {
  if (this.size == 0) return undefined;
  var ans = this.array[0];
  if (this.size > 1) {
    this.array[0] = this.array[--this.size];
    this._percolateDown(0);
  } else {
    this.size -= 1;
  }
  return ans;
};

// This function adds the provided value to the heap, while removing
// and returning one of the smallest elements (like poll). The size of the queue
// thus remains unchanged.
FastPriorityQueue.prototype.replaceTop = function(myval) {
  if (this.size == 0) return undefined;
  var ans = this.array[0];
  this.array[0] = myval;
  this._percolateDown(0);
  return ans;
};

// recover unused memory (for long-running priority queues)
FastPriorityQueue.prototype.trim = function() {
  this.array = this.array.slice(0, this.size);
};

// Check whether the heap is empty
FastPriorityQueue.prototype.isEmpty = function() {
  return this.size === 0;
};

// iterate over the items in order, pass a callback that receives (item, index) as args.
// TODO once we transpile, uncomment
// if (Symbol && Symbol.iterator) {
//   FastPriorityQueue.prototype[Symbol.iterator] = function*() {
//     if (this.isEmpty()) return;
//     var fpq = this.clone();
//     while (!fpq.isEmpty()) {
//       yield fpq.poll();
//     }
//   };
// }
FastPriorityQueue.prototype.forEach = function(callback) {
  if (this.isEmpty() || typeof callback != 'function') return;
  var i = 0;
  var fpq = this.clone();
  while (!fpq.isEmpty()) {
    callback(fpq.poll(), i++);
  }
};

// return the k 'smallest' elements of the queue as an array,
// runs in O(k log k) time, the elements are not removed
// from the priority queue.
FastPriorityQueue.prototype.kSmallest = function(k) {
  if (this.size == 0) return [];
  k = Math.min(this.size, k);
  var fpq = new FastPriorityQueue(this.compare);
  const newSize = Math.min((k > 0 ? Math.pow(2, k - 1) : 0) + 1, this.size);
  fpq.size = newSize;
  fpq.array = this.array.slice(0, newSize);

  var smallest = new Array(k);
  for (var i = 0; i < k; i++) {
    smallest[i] = fpq.poll();
  }
  return smallest;
}

module.exports = FastPriorityQueue;
<|endoftext|>


<commit_before>const globalVarsObjs = require('../Objects/GlobalVarsObjects.js');

var cmdYoutube = globalVarsObjs.commandVarObject.cmdYoutube;
var youtubeObjs = globalVarsObjs.otherObject.youtubeObjs;

// Youtube Responses
// Youtube Keywords/Phrases
var youtubeKeywordsPhrases = function(client) {
    client.on('message', message => {
        if(message.content.toLowerCase() === cmdYoutube + 'boneless pizza') {
            message.channel.send(youtubeObjs.bonelesspizza.url);
        }
    });
}

// Objects
var youtubeKeywordsPhrasesObject = {
    youtubeKeywordsPhrases: youtubeKeywordsPhrases
}

var exportobject = {
    youtubeKeywordsPhrasesObject: youtubeKeywordsPhrasesObject
}
module.exports = exportobject;<commit_msg>Changes - Fixed missing string.<commit_after>const globalVarsObjs = require('../Objects/GlobalVarsObjects.js');

var cmdYoutube = globalVarsObjs.commandVarObject.cmdYoutube;
var youtubeObjs = globalVarsObjs.otherObject.youtubeObjs;

// Youtube Responses
// Youtube Keywords/Phrases
var youtubeKeywordsPhrases = function(client) {
    client.on('message', message => {
        if(message.content.toLowerCase() === cmdYoutube + ' ' + 'boneless pizza') {
            message.channel.send(youtubeObjs.bonelesspizza.url);
        }
    });
}

// Objects
var youtubeKeywordsPhrasesObject = {
    youtubeKeywordsPhrases: youtubeKeywordsPhrases
}

var exportobject = {
    youtubeKeywordsPhrasesObject: youtubeKeywordsPhrasesObject
}
module.exports = exportobject;<|endoftext|>


<commit_before>/*global exports */

(function () {
    "use strict";

    var popularNamesPerState = function(req, res) {
        var body = JSON.stringify([
            {name: 'Smith', geo: {lat: -37.716, lon: 144.891}},
            {name: 'Jones', geo: {lat: -41.218, lon: 1446.188}},
            {name: 'Nyuan', geo: {lat: -25.173, lon: 144.891}},
            {name: 'Potter', geo: {lat: -33.390, lon: 149.547}},
            {name: 'Brown', geo: {lat: -28.101, lon: 115.192}}
        ]);
        res.setHeader('Content-Type', 'application/json');
        res.setHeader('Content-Length', body.length);
        res.end(body);
    };

    exports.list = function(req, res) {
        popularNamesPerState(req, res);
    };
})();

<commit_msg>Add all of the states<commit_after>/*global exports */

(function () {
    "use strict";

    var popularNamesPerState = function(req, res) {
        var body = JSON.stringify([
            {name: 'Smith', geo: {lat: -36.64, lon: 144.11}},
            {name: 'Smith', geo: {lat: -31.0, lon: 146.4}},
            {name: 'Smith', geo: {lat: -24.9, lon: 145.0}},
            {name: 'Smith', geo: {lat: -14.5, lon: 131.7}},
            {name: 'Smith', geo: {lat: -27.9, lon: 134.3}},
            {name: 'Smith', geo: {lat: -42.39, lon: 146.73}},
            {name: 'Smith', geo: {lat: -28.1, lon: 119.3}}
        ]);
        res.setHeader('Content-Type', 'application/json');
        res.setHeader('Content-Length', body.length);
        res.end(body);
    };

    exports.list = function(req, res) {
        popularNamesPerState(req, res);
    };
})();

<|endoftext|>