<commit_before>var SYSTEM = require("system");
var FILE = require("file");
var OS = require("os");
var UTIL = require("util");

function ensurePackageUpToDate(packageName, requiredVersion, options)
{
    options = options || {};

    var packageInfo = require("packages").catalog[packageName];
    if (!packageInfo)
    {
        if (options.optional)
            return;

        print("You are missing package \"" + packageName + "\", version " + requiredVersion + " or later. Please install using \"tusk install "+packageName+"\" and re-run jake");
        OS.exit(1);
    }

    var version = packageInfo.version;
    if (typeof version === "string")
        version = version.split(".");

    if (typeof requiredVersion === "string")
        requiredVersion = requiredVersion.split(".");

    if (version && UTIL.compare(version, requiredVersion) !== -1)
        return;

    print("Your copy of " + packageName + " is out of date (" + (version||["0"]).join(".") + " installed, " + requiredVersion.join(".") + " required).");

    if (!options.noupdate)
    {
        print("Update? yes or no:");
        if (!SYSTEM.env["CAPP_AUTO_UPGRADE"] && system.stdin.readLine() !== "yes\n")
        {
            print("Jake aborted.");
            OS.exit(1);
        }
        OS.system(["tusk", "install", "--force", packageName]);
    }

    if (options.message)
    {
        print(options.message)
        OS.exit(1);
    }
}

// UPDATE THESE TO PICK UP CORRESPONDING CHANGES IN DEPENDENCIES
ensurePackageUpToDate("jake",           "0.1.4");
ensurePackageUpToDate("browserjs",      "0.1.1");
ensurePackageUpToDate("shrinksafe",     "0.2");
ensurePackageUpToDate("narwhal",        "0.2.2", {
    noupdate : true,
    message : "Update Narwhal to 0.2.1 by running bootstrap.sh, or pulling the latest from git (see: http://github.com/280north/narwhal)."
});
ensurePackageUpToDate("narwhal-jsc",    "0.1.1", {
    optional : true,
    message : "Rebuild narwhal-jsc by changing to the narwhal-jsc package directory and running \"make webkit\"."
});

var JAKE = require("jake");

// Set up development environment variables.

// record the initial SYSTEM.env so we know which need to be serialized later
var envInitial = Object.freeze(UTIL.copy(SYSTEM.env));

SYSTEM.env["BUILD_PATH"] = FILE.absolute(
    SYSTEM.env["BUILD_PATH"] ||
    SYSTEM.env["CAPP_BUILD"] || // Global Cappuccino build directory.
    SYSTEM.env["STEAM_BUILD"] || // Maintain backwards compatibility with steam.
    FILE.join(FILE.dirname(module.path), "Build") // Just build here.
);

if (!SYSTEM.env["CAPP_BUILD"] && SYSTEM.env["STEAM_BUILD"])
    system.stderr.print("STEAM_BUILD environment variable is deprecated; Please use CAPP_BUILD instead.");

if (!SYSTEM.env["CONFIG"])
    SYSTEM.env["CONFIG"] = "Release";

global.ENV  = SYSTEM.env;
global.ARGV = SYSTEM.args
global.FILE = FILE;
global.OS   = OS;

global.task = JAKE.task;
global.directory = JAKE.directory;
global.file = JAKE.file;
global.filedir = JAKE.filedir;
global.FileList = JAKE.FileList;

global.CLEAN = require("jake/clean").CLEAN;
global.CLOBBER = require("jake/clean").CLOBBER;

global.$CONFIGURATION                   = SYSTEM.env['CONFIG'];
global.$BUILD_DIR                       = SYSTEM.env['BUILD_PATH'];
global.$BUILD_CONFIGURATION_DIR         = FILE.join($BUILD_DIR, $CONFIGURATION);

global.$BUILD_CJS_OBJECTIVE_J           = FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "objective-j");

global.$BUILD_CJS_CAPPUCCINO            = FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "cappuccino");
global.$BUILD_CJS_CAPPUCCINO_BIN        = FILE.join($BUILD_CJS_CAPPUCCINO, "bin");
global.$BUILD_CJS_CAPPUCCINO_LIB        = FILE.join($BUILD_CJS_CAPPUCCINO, "lib");
global.$BUILD_CJS_CAPPUCCINO_FRAMEWORKS = FILE.join($BUILD_CJS_CAPPUCCINO, "Frameworks");

global.$HOME_DIR        = FILE.absolute(FILE.dirname(module.path));
global.$LICENSE_FILE    = FILE.absolute(FILE.join(FILE.dirname(module.path), 'LICENSE'));

global.FIXME_fileDependency = function(destinationPath, sourcePath)
{
    file(destinationPath, [sourcePath], function(){
        FILE.touch(destinationPath);
    });
};

// logic to determine which packages should be loaded but are not.
// used in serializedENV()
function additionalPackages()
{
    var builtObjectiveJPackage = FILE.path($BUILD_CONFIGURATION_DIR).join("CommonJS", "objective-j", "");
    var builtCappuccinoPackage = FILE.path($BUILD_CONFIGURATION_DIR).join("CommonJS", "cappuccino", "");

    var packages = [];

    // load built objective-j if exists, otherwise unbuilt
    if (builtObjectiveJPackage.join("package.json").exists()) {
        if (!packageInCatalog(builtObjectiveJPackage))
            packages.push(builtObjectiveJPackage);
    }

    // load built cappuccino if it exists
    if (builtCappuccinoPackage.join("package.json").exists()) {
        if (!packageInCatalog(builtCappuccinoPackage))
            packages.push(builtCappuccinoPackage);
    }

    return packages;
}

// checks to see if a path is in the package catalog
function packageInCatalog(path)
{
    var catalog = require("packages").catalog;
    for (var name in catalog)
        if (String(catalog[name].directory) === String(path))
            return true;
    return false;
}

serializedENV = function()
{
    var envNew = {};

    // add changed keys to the new ENV
    Object.keys(SYSTEM.env).forEach(function(key) {
        if (SYSTEM.env[key] !== envInitial[key])
            envNew[key] = SYSTEM.env[key];
    });

    // pseudo-HACK: add NARWHALOPT with packages we should ensure are loaded
    var packages = additionalPackages();
    if (packages.length) {
        envNew["NARWHALOPT"] = packages.map(function(p) { return "-p " + p; }).join(" ");
        envNew["PATH"] = packages.map(function(p) { return FILE.join(p, "bin"); }).concat(SYSTEM.env["PATH"]).join(":");
    }

    return Object.keys(envNew).map(function(key) {
        return key + "=" + OS.enquote(envNew[key]);
    }).join(" ");
}

function reforkWithPackages()
{
    if (additionalPackages().length > 0) {
        var cmd = serializedENV() + " " + system.args.map(OS.enquote).join(" ");
        //print("REFORKING: " + cmd);
        OS.exit(OS.system(cmd));
    }
}

reforkWithPackages();

function handleSetupEnvironmentError(e) {
    if (String(e).indexOf("require error")==-1) {
        print("setupEnvironment warning: " + e);
        //throw e;
    }
}

function setupEnvironment()
{
    try {
        require("objective-j").OBJJ_INCLUDE_PATHS.push(FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "cappuccino", "Frameworks"));
    } catch (e) {
        handleSetupEnvironmentError(e);
    }
}

setupEnvironment();

global.rm_rf = function(/*String*/ aFilename)
{
    try { FILE.rmtree(aFilename); }
    catch (anException) { }
}

global.cp_r = function(/*String*/ from, /*String*/ to)
{
    if (FILE.exists(to))
        rm_rf(to);

    if (FILE.isDirectory(from))
        FILE.copyTree(from, to);
    else{try{
        FILE.copy(from, to);}catch(e) { print(e + FILE.exists(from) + " " + FILE.exists(FILE.dirname(to))); }}
}

global.cp = function(/*String*/ from, /*String*/ to)
{
    FILE.copy(from, to);
//    FILE.chmod(to, FILE.mod(from));
}

global.mv = function(/*String*/ from, /*String*/ to)
{
    FILE.move(from, to);
}

global.subjake = function(/*Array<String>*/ directories, /*String*/ aTaskName)
{
    if (!Array.isArray(directories))
        directories = [directories];

    directories.forEach(function(/*String*/ aDirectory)
    {
        if (FILE.isDirectory(aDirectory) && FILE.isFile(FILE.join(aDirectory, "Jakefile")))
        {
            var cmd = "cd " + OS.enquote(aDirectory) + " && " + serializedENV() + " " + OS.enquote(SYSTEM.args[0]) + " " + OS.enquote(aTaskName);
            var returnCode = OS.system(cmd);
            if (returnCode)
                OS.exit(returnCode);
        }
        else
            print("warning: subjake missing: " + aDirectory + " (this is not necessarily an error, " + aDirectory + " may be optional)");
    });
}

global.executableExists = function(/*String*/ aFileName)
{
    return SYSTEM.env["PATH"].split(':').some(function(/*String*/ aPath)
    {
        return FILE.exists(FILE.join(aPath, aFileName));
    });
}

$OBJJ_TEMPLATE_EXECUTABLE = FILE.join($HOME_DIR, "Objective-J", "CommonJS", "objj-executable");

global.make_objj_executable = function(aPath)
{
    cp($OBJJ_TEMPLATE_EXECUTABLE, aPath);
    FILE.chmod(aPath, 0755);
}

global.symlink_executable = function(source)
{
    relative = FILE.relative($ENVIRONMENT_NARWHAL_BIN_DIR, source);
    destination = FILE.join($ENVIRONMENT_NARWHAL_BIN_DIR, FILE.basename(source));
    FILE.symlink(relative, destination);
}

global.subtasks = function(subprojects, taskNames)
{
    taskNames.forEach(function(aTaskName)
    {
        var subtaskName = aTaskName + "_subprojects";

        task (aTaskName, [subtaskName]);

        task (subtaskName, function()
        {
            subjake(subprojects, aTaskName);
        });
    });
}

function spawnJake(/*String*/ aTaskName)
{
    if (OS.system(serializedENV() + " " + SYSTEM.args[0] + " " + aTaskName))
        OS.exit(1);//rake abort if ($? != 0)
}

// built in tasks

task ("build");
task ("default", "build");

task ("release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("build");
});

task ("debug", function()
{
    SYSTEM.env["CONFIG"] = "Debug";
    spawnJake("build");
});

task ("all", ["debug", "release"]);

task ("clean-debug", function()
{
    SYSTEM.env['CONFIG'] = 'Debug'
    spawnJake("clean");
});

task ("cleandebug", ["clean-debug"]);

task ("clean-release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("clean");
});

task ("cleanrelease", ["clean-release"]);

task ("clean-all", ["clean-debug", "clean-release"]);
task ("cleanall", ["clean-all"]);

task ("clobber-debug", function()
{
    SYSTEM.env["CONFIG"] = "Debug";
    spawnJake("clobber");
});

task ("clobberdebug", ["clobber-debug"]);

task ("clobber-release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("clobber");
});

task ("clobberrelease", ['clobber-release']);

task ("clobber-all", ["clobber-debug", "clobber-release"]);
task ("clobberall", ["clobber-all"]);
<commit_msg>Enquote NARWHALOPT package paths to fix building in directories with spaces.<commit_after>var SYSTEM = require("system");
var FILE = require("file");
var OS = require("os");
var UTIL = require("util");

function ensurePackageUpToDate(packageName, requiredVersion, options)
{
    options = options || {};

    var packageInfo = require("packages").catalog[packageName];
    if (!packageInfo)
    {
        if (options.optional)
            return;

        print("You are missing package \"" + packageName + "\", version " + requiredVersion + " or later. Please install using \"tusk install "+packageName+"\" and re-run jake");
        OS.exit(1);
    }

    var version = packageInfo.version;
    if (typeof version === "string")
        version = version.split(".");

    if (typeof requiredVersion === "string")
        requiredVersion = requiredVersion.split(".");

    if (version && UTIL.compare(version, requiredVersion) !== -1)
        return;

    print("Your copy of " + packageName + " is out of date (" + (version||["0"]).join(".") + " installed, " + requiredVersion.join(".") + " required).");

    if (!options.noupdate)
    {
        print("Update? yes or no:");
        if (!SYSTEM.env["CAPP_AUTO_UPGRADE"] && system.stdin.readLine() !== "yes\n")
        {
            print("Jake aborted.");
            OS.exit(1);
        }
        OS.system(["tusk", "install", "--force", packageName]);
    }

    if (options.message)
    {
        print(options.message)
        OS.exit(1);
    }
}

// UPDATE THESE TO PICK UP CORRESPONDING CHANGES IN DEPENDENCIES
ensurePackageUpToDate("jake",           "0.1.5");
ensurePackageUpToDate("browserjs",      "0.1.1");
ensurePackageUpToDate("shrinksafe",     "0.2");
ensurePackageUpToDate("narwhal",        "0.2.2", {
    noupdate : true,
    message : "Update Narwhal to 0.2.1 by running bootstrap.sh, or pulling the latest from git (see: http://github.com/280north/narwhal)."
});
ensurePackageUpToDate("narwhal-jsc",    "0.1.1", {
    optional : true,
    message : "Rebuild narwhal-jsc by changing to the narwhal-jsc package directory and running \"make webkit\"."
});

var JAKE = require("jake");

// Set up development environment variables.

// record the initial SYSTEM.env so we know which need to be serialized later
var envInitial = Object.freeze(UTIL.copy(SYSTEM.env));

SYSTEM.env["BUILD_PATH"] = FILE.absolute(
    SYSTEM.env["BUILD_PATH"] ||
    SYSTEM.env["CAPP_BUILD"] || // Global Cappuccino build directory.
    SYSTEM.env["STEAM_BUILD"] || // Maintain backwards compatibility with steam.
    FILE.join(FILE.dirname(module.path), "Build") // Just build here.
);

if (!SYSTEM.env["CAPP_BUILD"] && SYSTEM.env["STEAM_BUILD"])
    system.stderr.print("STEAM_BUILD environment variable is deprecated; Please use CAPP_BUILD instead.");

if (!SYSTEM.env["CONFIG"])
    SYSTEM.env["CONFIG"] = "Release";

global.ENV  = SYSTEM.env;
global.ARGV = SYSTEM.args
global.FILE = FILE;
global.OS   = OS;

global.task = JAKE.task;
global.directory = JAKE.directory;
global.file = JAKE.file;
global.filedir = JAKE.filedir;
global.FileList = JAKE.FileList;

global.CLEAN = require("jake/clean").CLEAN;
global.CLOBBER = require("jake/clean").CLOBBER;

global.$CONFIGURATION                   = SYSTEM.env['CONFIG'];
global.$BUILD_DIR                       = SYSTEM.env['BUILD_PATH'];
global.$BUILD_CONFIGURATION_DIR         = FILE.join($BUILD_DIR, $CONFIGURATION);

global.$BUILD_CJS_OBJECTIVE_J           = FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "objective-j");

global.$BUILD_CJS_CAPPUCCINO            = FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "cappuccino");
global.$BUILD_CJS_CAPPUCCINO_BIN        = FILE.join($BUILD_CJS_CAPPUCCINO, "bin");
global.$BUILD_CJS_CAPPUCCINO_LIB        = FILE.join($BUILD_CJS_CAPPUCCINO, "lib");
global.$BUILD_CJS_CAPPUCCINO_FRAMEWORKS = FILE.join($BUILD_CJS_CAPPUCCINO, "Frameworks");

global.$HOME_DIR        = FILE.absolute(FILE.dirname(module.path));
global.$LICENSE_FILE    = FILE.absolute(FILE.join(FILE.dirname(module.path), 'LICENSE'));

global.FIXME_fileDependency = function(destinationPath, sourcePath)
{
    file(destinationPath, [sourcePath], function(){
        FILE.touch(destinationPath);
    });
};

// logic to determine which packages should be loaded but are not.
// used in serializedENV()
function additionalPackages()
{
    var builtObjectiveJPackage = FILE.path($BUILD_CONFIGURATION_DIR).join("CommonJS", "objective-j", "");
    var builtCappuccinoPackage = FILE.path($BUILD_CONFIGURATION_DIR).join("CommonJS", "cappuccino", "");

    var packages = [];

    // load built objective-j if exists, otherwise unbuilt
    if (builtObjectiveJPackage.join("package.json").exists()) {
        if (!packageInCatalog(builtObjectiveJPackage))
            packages.push(builtObjectiveJPackage);
    }

    // load built cappuccino if it exists
    if (builtCappuccinoPackage.join("package.json").exists()) {
        if (!packageInCatalog(builtCappuccinoPackage))
            packages.push(builtCappuccinoPackage);
    }

    return packages;
}

// checks to see if a path is in the package catalog
function packageInCatalog(path)
{
    var catalog = require("packages").catalog;
    for (var name in catalog)
        if (String(catalog[name].directory) === String(path))
            return true;
    return false;
}

serializedENV = function()
{
    var envNew = {};

    // add changed keys to the new ENV
    Object.keys(SYSTEM.env).forEach(function(key) {
        if (SYSTEM.env[key] !== envInitial[key])
            envNew[key] = SYSTEM.env[key];
    });

    // pseudo-HACK: add NARWHALOPT with packages we should ensure are loaded
    var packages = additionalPackages();
    if (packages.length) {
        envNew["NARWHALOPT"] = packages.map(function(p) { return "-p " + OS.enquote(p); }).join(" ");
        envNew["PATH"] = packages.map(function(p) { return FILE.join(p, "bin"); }).concat(SYSTEM.env["PATH"]).join(":");
    }

    return Object.keys(envNew).map(function(key) {
        return key + "=" + OS.enquote(envNew[key]);
    }).join(" ");
}

function reforkWithPackages()
{
    if (additionalPackages().length > 0) {
        var cmd = serializedENV() + " " + system.args.map(OS.enquote).join(" ");
        //print("REFORKING: " + cmd);
        OS.exit(OS.system(cmd));
    }
}

reforkWithPackages();

function handleSetupEnvironmentError(e) {
    if (String(e).indexOf("require error")==-1) {
        print("setupEnvironment warning: " + e);
        //throw e;
    }
}

function setupEnvironment()
{
    try {
        require("objective-j").OBJJ_INCLUDE_PATHS.push(FILE.join($BUILD_CONFIGURATION_DIR, "CommonJS", "cappuccino", "Frameworks"));
    } catch (e) {
        handleSetupEnvironmentError(e);
    }
}

setupEnvironment();

global.rm_rf = function(/*String*/ aFilename)
{
    try { FILE.rmtree(aFilename); }
    catch (anException) { }
}

global.cp_r = function(/*String*/ from, /*String*/ to)
{
    if (FILE.exists(to))
        rm_rf(to);

    if (FILE.isDirectory(from))
        FILE.copyTree(from, to);
    else{try{
        FILE.copy(from, to);}catch(e) { print(e + FILE.exists(from) + " " + FILE.exists(FILE.dirname(to))); }}
}

global.cp = function(/*String*/ from, /*String*/ to)
{
    FILE.copy(from, to);
//    FILE.chmod(to, FILE.mod(from));
}

global.mv = function(/*String*/ from, /*String*/ to)
{
    FILE.move(from, to);
}

global.subjake = function(/*Array<String>*/ directories, /*String*/ aTaskName)
{
    if (!Array.isArray(directories))
        directories = [directories];

    directories.forEach(function(/*String*/ aDirectory)
    {
        if (FILE.isDirectory(aDirectory) && FILE.isFile(FILE.join(aDirectory, "Jakefile")))
        {
            var cmd = "cd " + OS.enquote(aDirectory) + " && " + serializedENV() + " " + OS.enquote(SYSTEM.args[0]) + " " + OS.enquote(aTaskName);
            var returnCode = OS.system(cmd);
            if (returnCode)
                OS.exit(returnCode);
        }
        else
            print("warning: subjake missing: " + aDirectory + " (this is not necessarily an error, " + aDirectory + " may be optional)");
    });
}

global.executableExists = function(/*String*/ aFileName)
{
    return SYSTEM.env["PATH"].split(':').some(function(/*String*/ aPath)
    {
        return FILE.exists(FILE.join(aPath, aFileName));
    });
}

$OBJJ_TEMPLATE_EXECUTABLE = FILE.join($HOME_DIR, "Objective-J", "CommonJS", "objj-executable");

global.make_objj_executable = function(aPath)
{
    cp($OBJJ_TEMPLATE_EXECUTABLE, aPath);
    FILE.chmod(aPath, 0755);
}

global.symlink_executable = function(source)
{
    relative = FILE.relative($ENVIRONMENT_NARWHAL_BIN_DIR, source);
    destination = FILE.join($ENVIRONMENT_NARWHAL_BIN_DIR, FILE.basename(source));
    FILE.symlink(relative, destination);
}

global.subtasks = function(subprojects, taskNames)
{
    taskNames.forEach(function(aTaskName)
    {
        var subtaskName = aTaskName + "_subprojects";

        task (aTaskName, [subtaskName]);

        task (subtaskName, function()
        {
            subjake(subprojects, aTaskName);
        });
    });
}

function spawnJake(/*String*/ aTaskName)
{
    if (OS.system(serializedENV() + " " + SYSTEM.args[0] + " " + aTaskName))
        OS.exit(1);//rake abort if ($? != 0)
}

// built in tasks

task ("build");
task ("default", "build");

task ("release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("build");
});

task ("debug", function()
{
    SYSTEM.env["CONFIG"] = "Debug";
    spawnJake("build");
});

task ("all", ["debug", "release"]);

task ("clean-debug", function()
{
    SYSTEM.env['CONFIG'] = 'Debug'
    spawnJake("clean");
});

task ("cleandebug", ["clean-debug"]);

task ("clean-release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("clean");
});

task ("cleanrelease", ["clean-release"]);

task ("clean-all", ["clean-debug", "clean-release"]);
task ("cleanall", ["clean-all"]);

task ("clobber-debug", function()
{
    SYSTEM.env["CONFIG"] = "Debug";
    spawnJake("clobber");
});

task ("clobberdebug", ["clobber-debug"]);

task ("clobber-release", function()
{
    SYSTEM.env["CONFIG"] = "Release";
    spawnJake("clobber");
});

task ("clobberrelease", ['clobber-release']);

task ("clobber-all", ["clobber-debug", "clobber-release"]);
task ("clobberall", ["clobber-all"]);
<|endoftext|>


<commit_before>import easeInOutQuad from './easing'

const jumper = () => {
  // globals
  let start         // where scroll starts (px)
  let stop          // where scroll stops (px)

  let offset        // adjustment from the stop position (px)
  let easing        // easing function

  let duration      // scroll duration
  let distance      // distance of scroll (px)

  let timeStart     // time scroll started
  let timeElapsed   // time scrolling thus far

  let next          // next scroll position (px)

  let callback      // fire when done scrolling

  function loop(timeCurrent) {
    if(!timeStart) {
      timeStart = timeCurrent
    }

    // determine time spent scrolling so far
    timeElapsed = timeCurrent - timeStart

    // calculate next scroll position
    next = easing(timeElapsed, start, distance, duration)

    // scroll to it
    window.scrollTo(0, next)

    // continue looping or end
    timeElapsed < duration
      ? requestAnimationFrame(loop)
      : end()
  }

  function end() {
    // account for rounding inaccuracies
    window.scrollTo(0, start + distance)

    // if it exists, fire the callback
    if(typeof callback === 'function') {
      callback()
    }

    // reset for next jump
    timeStart = undefined
  }

  function jump(target, options = {}) {
    // cache starting position
    start = window.scrollY || window.pageYOffset

    // resolve duration, the only required option
    // if its not a number, assume its a function
    duration = typeof options.duration === 'number'
      ? options.duration
      : options.duration(distance)

    // resolve offset
    offset = options.offset || 0

    // resolve callback
    callback = options.callback

    // resolve easing
    easing = options.easing || easeInOutQuad

    // resolve target
    switch(typeof target) {
      // scroll from current position
      case 'number':
        stop = start + target
      break

      // scroll to element (node)
      case 'object':
        stop = target.getBoundingClientRect().top
      break

      // scroll to element (selector)
      case 'string':
        stop = document.querySelector(target).getBoundingClientRect().top
      break
    }

    // resolve distance
    distance = stop - start

    // start the loop
    requestAnimationFrame(loop)
  }

  return jump
}

// export singleton

const singleton = jumper()

export default singleton
<commit_msg>improve commenting<commit_after>import easeInOutQuad from './easing'

const jumper = () => {
  // globals
  let start         // where scroll starts (px)
  let stop          // where scroll stops (px)

  let offset        // adjustment from the stop position (px)
  let easing        // easing function

  let duration      // scroll duration
  let distance      // distance of scroll (px)

  let timeStart     // time scroll started
  let timeElapsed   // time scrolling thus far

  let next          // next scroll position (px)

  let callback      // fire when done scrolling

  function loop(timeCurrent) {
    // store time started scrolling when starting
    if(!timeStart) {
      timeStart = timeCurrent
    }

    // determine time spent scrolling so far
    timeElapsed = timeCurrent - timeStart

    // calculate next scroll position
    next = easing(timeElapsed, start, distance, duration)

    // scroll to it
    window.scrollTo(0, next)

    // continue looping or end
    timeElapsed < duration
      ? requestAnimationFrame(loop)
      : end()
  }

  function end() {
    // account for rounding inaccuracies
    window.scrollTo(0, start + distance)

    // if it exists, fire the callback
    if(typeof callback === 'function') {
      callback()
    }

    // reset for next jump
    timeStart = undefined
  }

  function jump(target, options = {}) {
    // cache starting position
    start = window.scrollY || window.pageYOffset

    // resolve duration, the only required option
    // if its not a number, assume its a function
    duration = typeof options.duration === 'number'
      ? options.duration
      : options.duration(distance)

    // resolve offset
    offset = options.offset || 0

    // resolve callback
    callback = options.callback

    // resolve easing
    easing = options.easing || easeInOutQuad

    // resolve target
    switch(typeof target) {
      // scroll from current position
      case 'number':
        stop = start + target
      break

      // scroll to element (node)
      case 'object':
        stop = target.getBoundingClientRect().top
      break

      // scroll to element (selector)
      case 'string':
        stop = document.querySelector(target).getBoundingClientRect().top
      break
    }

    // resolve distance
    distance = stop - start

    // start the loop
    requestAnimationFrame(loop)
  }

  return jump
}

// export singleton

const singleton = jumper()

export default singleton
<|endoftext|>


<commit_before>var cookieParser    = require('cookie-parser');
var cookieSession   = require('cookie-session');
var _               = require('lodash');
var Promise         = require('promise');
var debug           = require('debug')("auth:persona");
var assert          = require('assert');
var moment          = require('moment');
var marked          = require('marked');
var passport        = require('passport');
var PassportPersona = require('passport-persona');
var express         = require('express')
var bodyParser      = require('body-parser');
var querystring     = require('querystring');
var taskcluster = require('taskcluster-client');
var url         = require('url');

/** Index page (the only page we have) */
var renderIndex = function(authFailed, req, res) {
  // Load client so we can sign
  var Client = req.app.globals.Client;
  Client.load(req.app.globals.clientIdForTempCreds).then(function(client) {
    return taskcluster.createTemporaryCredentials({
      start:        new Date(),
      expiry:       new Date(new Date().getTime() + 31 * 24 * 60 * 60 * 1000),
      scopes:       client.scopes,
      credentials:  {
        clientId:     client.clientId,
        accessToken:  client.accessToken
      }
    });
  }, function(err) {
    debug("Error loading client: %s, as JSON: %j", err, err, err.stack);
    return {
      clientId:     '',
      accessToken:  '',
      certificate:  'Internal server error'
    };
  }).then(function(credentials) {
    if (typeof(credentials.certificate) !== 'string') {
      credentials.certificate = JSON.stringify(credentials.certificate);
    }

    // Add temporary credentials to target URL
    var target = undefined;
    if (req.query.target) {
      target = url.parse(req.query.target);
      delete target.search;
      if (!target.query) {
        target.query = {};
      }
      target.query.clientId     = credentials.clientId;
      target.query.accessToken  = credentials.accessToken;
      target.query.certificate  = credentials.certificate;
    }

    // Render login page
    res.render('login', {
      query:        req.query,
      target:       url.format(target),
      credentials:  credentials,
      querystring:  querystring.stringify(req.query),
      authFailed:   authFailed
    });
  });
};

/** Setup the application for hosting the index page */
var setup = function(app, options) {
  assert(options.cookieSecret,    "cookieSecret is required");
  assert(options.viewFolder,      "viewFolder is required");
  assert(options.assetFolder,     "assetFolder is required");

  app.set('views', options.viewFolder);
  app.set('view engine', 'jade');
  app.locals.moment = moment;
  app.locals.marked = marked;

  app.use(bodyParser.urlencoded({extended: false}));
  app.use(cookieParser(options.cookieSecret));
  app.use(cookieSession({secret: options.cookieSecret}));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(function(req, res, next) {
    // Expose user to all templates, if logged in
    res.locals.user = req.user;
    next();
  });
  app.use('/assets', express.static(options.assetFolder));

  // Warn if no secret was used in production
  if ('production' == app.get('env')) {
    var secret = options.cookieSecret;
    if (secret == "Warn, if no secret is used on production") {
      console.log("Warning: Customized cookie secret should be used in " +
                  "production");
    }
  }

  // Passport configuration
  passport.use(new PassportPersona.Strategy({
      audience:   options.publicUrl
    }, function(email, done) {
    debug("Signed in with:" + email);
    if (/@mozilla\.com$/.test(email)) {
      done(null, {email: email});
    } else {
      done(null, null);
    }
  }));

  // Serialize user to signed cookie
  passport.serializeUser(function(user, done) {
    done(null, user.email);
  });

  // Deserialize user from signed cookie
  passport.deserializeUser(function(email, done) {
    done(null, {email: email});
  });

  // Facilitate persona login
  app.post('/', function(req, res, next) {
    passport.authenticate('persona', function(err, user, info) {
      if (user) {
        // Make sure we preserve the querystring
        req.logIn(user, function() {
          res.redirect('/?' + querystring.stringify(req.query));
        });
      } else {
        renderIndex(true, req, res);
      }
    })(req, res, next);
  });

  // Provide end-point to log out the user
  app.get('/logout', function(req, res){
    req.logout();
    // Make sure we preserve the querystring
    res.redirect('/?' + querystring.stringify(req.query));
  });

  // render index page
  app.get('/', function(req, res) {
    renderIndex(false, req, res);
  });
};

// Export setup
exports.setup = setup;<commit_msg>Granting access for @qanalydocs.com email addresses<commit_after>var cookieParser    = require('cookie-parser');
var cookieSession   = require('cookie-session');
var _               = require('lodash');
var Promise         = require('promise');
var debug           = require('debug')("auth:persona");
var assert          = require('assert');
var moment          = require('moment');
var marked          = require('marked');
var passport        = require('passport');
var PassportPersona = require('passport-persona');
var express         = require('express')
var bodyParser      = require('body-parser');
var querystring     = require('querystring');
var taskcluster = require('taskcluster-client');
var url         = require('url');

/** Index page (the only page we have) */
var renderIndex = function(authFailed, req, res) {
  // Load client so we can sign
  var Client = req.app.globals.Client;
  Client.load(req.app.globals.clientIdForTempCreds).then(function(client) {
    return taskcluster.createTemporaryCredentials({
      start:        new Date(),
      expiry:       new Date(new Date().getTime() + 31 * 24 * 60 * 60 * 1000),
      scopes:       client.scopes,
      credentials:  {
        clientId:     client.clientId,
        accessToken:  client.accessToken
      }
    });
  }, function(err) {
    debug("Error loading client: %s, as JSON: %j", err, err, err.stack);
    return {
      clientId:     '',
      accessToken:  '',
      certificate:  'Internal server error'
    };
  }).then(function(credentials) {
    if (typeof(credentials.certificate) !== 'string') {
      credentials.certificate = JSON.stringify(credentials.certificate);
    }

    // Add temporary credentials to target URL
    var target = undefined;
    if (req.query.target) {
      target = url.parse(req.query.target);
      delete target.search;
      if (!target.query) {
        target.query = {};
      }
      target.query.clientId     = credentials.clientId;
      target.query.accessToken  = credentials.accessToken;
      target.query.certificate  = credentials.certificate;
    }

    // Render login page
    res.render('login', {
      query:        req.query,
      target:       url.format(target),
      credentials:  credentials,
      querystring:  querystring.stringify(req.query),
      authFailed:   authFailed
    });
  });
};

/** Setup the application for hosting the index page */
var setup = function(app, options) {
  assert(options.cookieSecret,    "cookieSecret is required");
  assert(options.viewFolder,      "viewFolder is required");
  assert(options.assetFolder,     "assetFolder is required");

  app.set('views', options.viewFolder);
  app.set('view engine', 'jade');
  app.locals.moment = moment;
  app.locals.marked = marked;

  app.use(bodyParser.urlencoded({extended: false}));
  app.use(cookieParser(options.cookieSecret));
  app.use(cookieSession({secret: options.cookieSecret}));
  app.use(passport.initialize());
  app.use(passport.session());
  app.use(function(req, res, next) {
    // Expose user to all templates, if logged in
    res.locals.user = req.user;
    next();
  });
  app.use('/assets', express.static(options.assetFolder));

  // Warn if no secret was used in production
  if ('production' == app.get('env')) {
    var secret = options.cookieSecret;
    if (secret == "Warn, if no secret is used on production") {
      console.log("Warning: Customized cookie secret should be used in " +
                  "production");
    }
  }

  // Passport configuration
  passport.use(new PassportPersona.Strategy({
      audience:   options.publicUrl
    }, function(email, done) {
    debug("Signed in with:" + email);
    if (/@(mozilla|qanalydocs)\.com$/.test(email)) {
      done(null, {email: email});
    } else {
      done(null, null);
    }
  }));

  // Serialize user to signed cookie
  passport.serializeUser(function(user, done) {
    done(null, user.email);
  });

  // Deserialize user from signed cookie
  passport.deserializeUser(function(email, done) {
    done(null, {email: email});
  });

  // Facilitate persona login
  app.post('/', function(req, res, next) {
    passport.authenticate('persona', function(err, user, info) {
      if (user) {
        // Make sure we preserve the querystring
        req.logIn(user, function() {
          res.redirect('/?' + querystring.stringify(req.query));
        });
      } else {
        renderIndex(true, req, res);
      }
    })(req, res, next);
  });

  // Provide end-point to log out the user
  app.get('/logout', function(req, res){
    req.logout();
    // Make sure we preserve the querystring
    res.redirect('/?' + querystring.stringify(req.query));
  });

  // render index page
  app.get('/', function(req, res) {
    renderIndex(false, req, res);
  });
};

// Export setup
exports.setup = setup;<|endoftext|>


<commit_before>module.exports = {
  'BACKSPACE':8,
  'TAB':9,
  'ENTER':13,
  'PAUSE':19,
  'CAPS':20,
  'ESC':27,
  'SPACE':32,
  'PAGE_UP':33,
  'PAGE_DOWN':34,
  'END':35,
  'HOME':36,
  'LEFT':37,
  'UP':38,
  'RIGHT':39,
  'DOWN':40,
  'INSERT':45,
  'DELETE':46,
  '_0':48,
  '_1':49,
  '_2':50,
  '_3':51,
  '_4':52,
  '_5':53,
  '_6':54,
  '_7':55,
  '_8':56,
  '_9':57,
  'A':65,
  'B':66,
  'C':67,
  'D':68,
  'E':69,
  'F':70,
  'G':71,
  'H':72,
  'I':73,
  'J':74,
  'K':75,
  'L':76,
  'M':77,
  'N':78,
  'O':79,
  'P':80,
  'Q':81,
  'R':82,
  'S':83,
  'T':84,
  'U':85,
  'V':86,
  'W':87,
  'X':88,
  'Y':89,
  'Z':90,
  'NUMPAD_0':96,
  'NUMPAD_1':97,
  'NUMPAD_2':98,
  'NUMPAD_3':99,
  'NUMPAD_4':100,
  'NUMPAD_5':101,
  'NUMPAD_6':102,
  'NUMPAD_7':103,
  'NUMPAD_8':104,
  'NUMPAD_9':105,
  'MULTIPLY':106,
  'ADD':107,
  'SUBSTRACT':109,
  'DECIMAL':110,
  'DIVIDE':111,
  'F1':112,
  'F2':113,
  'F3':114,
  'F4':115,
  'F5':116,
  'F6':117,
  'F7':118,
  'F8':119,
  'F9':120,
  'F10':121,
  'F11':122,
  'F12':123,
  'SHIFT':16,
  'CTRL':17,
  'ALT':18,
  'PLUS':187,
  'COMMA':188,
  'MINUS':189,
  'PERIOD':190
};
<commit_msg>reformat keys file<commit_after>module.exports = {
  'BACKSPACE': 8,
  'TAB': 9,
  'ENTER': 13,
  'PAUSE': 19,
  'CAPS': 20,
  'ESC': 27,
  'SPACE': 32,
  'PAGE_UP': 33,
  'PAGE_DOWN': 34,
  'END': 35,
  'HOME': 36,
  'LEFT': 37,
  'UP': 38,
  'RIGHT': 39,
  'DOWN': 40,
  'INSERT': 45,
  'DELETE': 46,
  '_0': 48,
  '_1': 49,
  '_2': 50,
  '_3': 51,
  '_4': 52,
  '_5': 53,
  '_6': 54,
  '_7': 55,
  '_8': 56,
  '_9': 57,
  'A': 65,
  'B': 66,
  'C': 67,
  'D': 68,
  'E': 69,
  'F': 70,
  'G': 71,
  'H': 72,
  'I': 73,
  'J': 74,
  'K': 75,
  'L': 76,
  'M': 77,
  'N': 78,
  'O': 79,
  'P': 80,
  'Q': 81,
  'R': 82,
  'S': 83,
  'T': 84,
  'U': 85,
  'V': 86,
  'W': 87,
  'X': 88,
  'Y': 89,
  'Z': 90,
  'NUMPAD_0': 96,
  'NUMPAD_1': 97,
  'NUMPAD_2': 98,
  'NUMPAD_3': 99,
  'NUMPAD_4': 100,
  'NUMPAD_5': 101,
  'NUMPAD_6': 102,
  'NUMPAD_7': 103,
  'NUMPAD_8': 104,
  'NUMPAD_9': 105,
  'MULTIPLY': 106,
  'ADD': 107,
  'SUBSTRACT': 109,
  'DECIMAL': 110,
  'DIVIDE': 111,
  'F1': 112,
  'F2': 113,
  'F3': 114,
  'F4': 115,
  'F5': 116,
  'F6': 117,
  'F7': 118,
  'F8': 119,
  'F9': 120,
  'F10': 121,
  'F11': 122,
  'F12': 123,
  'SHIFT': 16,
  'CTRL': 17,
  'ALT': 18,
  'PLUS': 187,
  'COMMA': 188,
  'MINUS': 189,
  'PERIOD': 190
};
<|endoftext|>


<commit_before>
/*

  Compile.js

*/

var Bundler     = require("./bundler"),
    express     = require("express"),
    Metadata    = require("./metadata"),
    Motors      = global.engines,
    Promise     = require("bluebird"),
    Utils       = require("./utils");
    makeQuery   = Promise.promisify(global.db.queries);

function createDataQuery(queries) {
  return function(context) {
    return makeQuery(queries, context).then(function(data) {
      return Promise.resolve(Object.assign({}, global.vars, context, data));
    });
  }
}

function sequence(tasks, initial) {
  return Promise.reduce(tasks || [], function(val, task) {
    return task(val);
  }, initial);
}

/**

  @returns <String> Directory to ignore (if exists)

**/

function addFile(router, route, file, type, basePath) {

    var tasks = [],
        metadata = {};

    // Add to list of extensions if not present
    if (!Motors.hasEngine(file.ext)) Motors.addEngine(file.ext);

    // Extract metadata
    if (/^html?$/.test(type)) {
      metadata = Metadata.extract(Utils.readFileHead(file.path, 500));
      tasks.push(createDataQuery(metadata.data));
    }

    // File compilation function
    if (file.bundle)
      tasks.push(Bundler.fromFile(file, type).get);
    else
      tasks.push(Promise.promisify(Motors.compileFile.bind(Motors, file.path)));

    // Route handling function
    function handler(req, res) {

      // Set cookies
      for (var key in metadata.cookies || {})
        res.cookie(key, metadata.cookies[key]);

      // Set session
      for (var key in metadata.session || {})
        req.session[key] = metadata.session[key];

      sequence(tasks, req.params)
      .then(res.type(type).send.bind(res))
      .catch(function(err) { console.log(err); res.sendStatus(500); });

    }

    // Add routes to router
    Utils.makeRoutes(route, file, { type : type, query : metadata.query }).forEach(function(r) {
      router.get(r, handler);
    });

    // If we have a bundle, return the path (we won't "watch" as this happens
    // already in Bundler.
    if (file.ignored) return file.ignored;

}

module.exports = function(options) {

  var router  = express(),
      ignore,
      ignored = [],
      files   = Utils.mapFiles(options.path, options),
      exts    = {};

  files.forEach(function(file) {

    ignore = addFile(router, options.url, file, options.ext);
    if (ignore) ignored = ignored.concat(ignore);

    exts[file.ext] = 1;

  });

  for (var key in exts)
    Utils.watch(options.path, key, options.ext, { ignoreInitial : true, ignored : ignored });

  return router;

};
<commit_msg>Compiler: switches to Utils#sequene<commit_after>
/*

  Compile.js

*/

var Bundler     = require("./bundler"),
    express     = require("express"),
    Metadata    = require("./metadata"),
    Motors      = global.engines,
    Promise     = require("bluebird"),
    Utils       = require("./utils");
    makeQuery   = Promise.promisify(global.db.queries);

function createDataQuery(queries) {
  return function(context) {
    return makeQuery(queries, context).then(function(data) {
      return Promise.resolve(Object.assign({}, global.vars, context, data));
    });
  }
}

/**

  @returns <String> Directory to ignore (if exists)

**/

function addFile(router, route, file, type, basePath) {

    var tasks = [],
        metadata = {};

    // Add to list of extensions if not present
    if (!Motors.hasEngine(file.ext)) Motors.addEngine(file.ext);

    // Extract metadata
    if (/^html?$/.test(type)) {
      metadata = Metadata.extract(Utils.readFileHead(file.path, 500));
      tasks.push(createDataQuery(metadata.data));
    }

    // File compilation function
    if (file.bundle)
      tasks.push(Bundler.fromFile(file, type).get);
    else
      tasks.push(Promise.promisify(Motors.compileFile.bind(Motors, file.path)));

    // Route handling function
    function handler(req, res) {

      // Set cookies
      for (var key in metadata.cookies || {})
        res.cookie(key, metadata.cookies[key]);

      // Set session
      for (var key in metadata.session || {})
        req.session[key] = metadata.session[key];

      Utils.sequence(tasks, req.params)
      .then(res.type(type).send.bind(res))
      .catch(function(err) { console.log(err); res.sendStatus(500); });

    }

    // Add routes to router
    Utils.makeRoutes(route, file, { type : type, query : metadata.query }).forEach(function(r) {
      router.get(r, handler);
    });

    // If we have a bundle, return the path (we won't "watch" as this happens
    // already in Bundler.
    if (file.ignored) return file.ignored;

}

module.exports = function(options) {

  var router  = express(),
      ignore,
      ignored = [],
      files   = Utils.mapFiles(options.path, options),
      exts    = {};

  files.forEach(function(file) {

    ignore = addFile(router, options.url, file, options.ext);
    if (ignore) ignored = ignored.concat(ignore);

    exts[file.ext] = 1;

  });

  for (var key in exts)
    Utils.watch(options.path, key, options.ext, { ignoreInitial : true, ignored : ignored });

  return router;

};
<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('IssueTracker', [
  'ngRoute',
  'IssueTracker.welcome',
  'IssueTracker.version',
  'IssueTracker.addIssue',
  'IssueTracker.addProject',
  'IssueTracker.issuePage',
  'IssueTracker.dashboard',
  'IssueTracker.users',
  'IssueTracker.users.authentication',
  'IssueTracker.projects',
  'IssueTracker.issues'

]).
  config(['$routeProvider', function($routeProvider, $http) {
    $routeProvider.otherwise({redirectTo: '/dashboard'});
    debugger;
  }])
    .constant('BASE_URL', 'http://softuni-issue-tracker.azurewebsites.net');<commit_msg>Changed redirection to /welcome.<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('IssueTracker', [
  'ngRoute',
  'IssueTracker.welcome',
  'IssueTracker.version',
  'IssueTracker.addIssue',
  'IssueTracker.addProject',
  'IssueTracker.issuePage',
  'IssueTracker.dashboard',
  'IssueTracker.users',
  'IssueTracker.users.authentication',
  'IssueTracker.projects',
  'IssueTracker.issues'

]).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.otherwise({redirectTo: '/welcome'});
  }])
    .constant('BASE_URL', 'http://softuni-issue-tracker.azurewebsites.net');<|endoftext|>


<commit_before>export default {
  LEFT: 37,
  UP: 38,
  RIGHT: 39,
  DOWN: 40,
  ENTER: 13,
  SPACE: 32,
};
<commit_msg>Add ESC key<commit_after>export default {
  LEFT: 37,
  UP: 38,
  RIGHT: 39,
  DOWN: 40,
  ENTER: 13,
  SPACE: 32,
  ESC: 27,
};
<|endoftext|>


<commit_before>"use strict";
/**
 * JBB - Javascript Binary Bundles - Binary Compiler
 * Copyright (C) 2015 Ioannis Charalampidis <ioannis.charalampidis@cern.ch>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Ioannis Charalampidis / https://github.com/wavesoft
 */

var BinaryEncoder = require("./encoder");
var BinaryDecoder = require("./decoder");
var path = require('path');

/**
 * Compile the specifie bundle data to the specified bundle file.
 * Additional information, such as profile or other compile-time parameters
 * can be specified through the config object.
 */
function compile( bundleData, bundleFile, config, callback ) {
	var baseDir = config['path'] || path.dirname(bundleFile);
	var importDB = {}, exportDB = {};
	var encoder, profileTable, profileCompiler;

	// Identify some important information
	var profile = config['profile'] || bundleData['profile'];
	if (!profile) {
		callback( "No jbb profile was specified!");
		return;
	}

	// Compile stages
	var openBundle = function( cb ) {
		return function() {

			// Create encoder
			encoder = new BinaryEncoder(
					bundleFile,
					{
						'name' 			: bundleData['name'],
						'base_dir' 		: baseDir,
						'object_table' 	: profileTable,
						'log'			: config['log'] || 0x2000,
					}
				);

			// We are ready
			cb();
		}
	}

	var loadImports = function( cb ) {
		return function() {
			var imports = bundleData['imports'];
			if (!imports) { cb(); return; };

			// TODO: Import imports

			// Update encoder db
			encoder.setDatabase(importDB);
			cb();
		}
	}

	var compileExports = function( cb ) {
		return function() {
			var exports = bundleData['exports'];
			if (!exports) { cb(); return; };

			// Serialize items/loaders
			var loaders = Object.keys(exports),
				items = [];
			for (var i=0; i<loaders.length; i++) {
				var keys = Object.keys(exports[loaders[i]]);
				for (var j=0; j<keys.length; j++) {
					items.push([ loaders[i], keys[j], exports[loaders[i]][keys[j]] ]);
				}
			}

			// Process items
			var getNext = function() {
				if (items.length == 0) { cb(); return; }
				var item = items.shift(),
					loader = item[0], key = item[1], loaderConfig = item[2];

				// Convert relative path to full-path
				if (typeof(loaderConfig) == "string") {
					if (loaderConfig.substr(0,1) != "/") {
						loaderConfig = path.join(baseDir, loaderConfig);
					}
				}

				// If this is a binary blob, don't go through the profile compiler
				if (loader.toLowerCase() == "blob") {

					// Check if we have mime details
					var file = null, mime = null;
					if (typeof(loaderConfig) == "string") {
						file = loaderConfig;
					} else {
						file = loaderConfig[0];
						mime = loaderConfig[1];
					}

					// Encode blob
					encoder.embed( file, mime );

				} else {

					// Use profile loader to load this
					profileCompiler.load( loaderConfig, key,
						function(err, objects) {

							// Encode objects
							for (var k in objects) {
								encoder.encode( objects[k], k );
							}

							// Schedule next item
							setTimeout(getNext, 1);
						}
					);

				}
			}

			// Start loading exports
			getNext();

		}
	}

	var closeBundle = function( cb ) {
		return function() {
			// Close & Complete
			encoder.close();
			cb();
		}
	}

	// Load profile table and compiler helper
	profileTable = require('jbb-profile-'+profile);
	profileCompiler = require('jbb-profile-'+profile+"/compiler");

	// Initialize profile compiler
	profileCompiler.initialize(
		openBundle(
			loadImports(
				compileExports(
					closeBundle( callback )
					)
				)
			)
	);

}

/**
 * Export the 'compile' function
 */
module.exports = {
	'compile': compile
};
<commit_msg>Bugfixes<commit_after>"use strict";
/**
 * JBB - Javascript Binary Bundles - Binary Compiler
 * Copyright (C) 2015 Ioannis Charalampidis <ioannis.charalampidis@cern.ch>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Ioannis Charalampidis / https://github.com/wavesoft
 */

var BinaryEncoder = require("./encoder");
var BinaryDecoder = require("./decoder");
var path = require('path');

/**
 * Compile the specifie bundle data to the specified bundle file.
 * Additional information, such as profile or other compile-time parameters
 * can be specified through the config object.
 */
function compile( bundleData, bundleFile, config, callback ) {
	var baseDir = config['path'] || path.dirname(bundleFile);
	var importDB = {}, exportDB = {};
	var encoder, profileTable, profileCompiler;

	// Identify some important information
	var profile = config['profile'] || bundleData['profile'];
	if (!profile) {
		callback( "No jbb profile was specified!");
		return;
	}

	// Compile stages
	var openBundle = function( cb ) {
		return function() {

			// Create encoder
			encoder = new BinaryEncoder(
					bundleFile,
					{
						'name' 			: bundleData['name'],
						'base_dir' 		: baseDir,
						'object_table' 	: profileTable,
						'log'			: config['log'] || 0x2000,
					}
				);

			// We are ready
			cb();
		}
	}

	var loadImports = function( cb ) {
		return function() {
			var imports = bundleData['imports'];
			if (!imports) { cb(); return; };

			// TODO: Import imports

			// Update encoder db
			encoder.setDatabase(importDB);
			cb();
		}
	}

	var compileExports = function( cb ) {
		return function() {
			var exports = bundleData['exports'];
			if (!exports) { cb(); return; };

			// Serialize items/loaders
			var loaders = Object.keys(exports),
				items = [];
			for (var i=0; i<loaders.length; i++) {
				var keys = Object.keys(exports[loaders[i]]);
				for (var j=0; j<keys.length; j++) {
					items.push([ loaders[i], keys[j], exports[loaders[i]][keys[j]] ]);
				}
			}

			// Process items
			var getNext = function() {
				if (items.length == 0) { cb(); return; }
				var item = items.shift(),
					loader = item[0], key = item[1], loaderConfig = item[2];

				// Convert relative path to full-path
				if (typeof(loaderConfig) == "string") {
					if (loaderConfig.substr(0,1) != "/") {
						loaderConfig = path.join(baseDir, loaderConfig);
					}
				}

				// If this is a binary blob, don't go through the profile compiler
				if (loader.toLowerCase() == "blob") {

					// Check if we have mime details
					var file = null, mime = null;
					if (typeof(loaderConfig) == "string") {
						file = loaderConfig;
					} else {
						file = loaderConfig[0];
						mime = loaderConfig[1];
					}

					// Encode blob
					encoder.embed( file, mime );

				} else {

					// Use profile loader to load this
					profileCompiler.load( loader, loaderConfig, key,
						function(err, objects) {

							// Encode objects
							for (var k in objects) {
								encoder.encode( objects[k], k );
							}

							// Schedule next item
							setTimeout(getNext, 1);
						}
					);

				}
			}

			// Start loading exports
			getNext();

		}
	}

	var closeBundle = function( cb ) {
		return function() {
			// Close & Complete
			encoder.close();
			cb();
		}
	}

	// Load profile table and compiler helper
	profileTable = require('jbb-profile-'+profile);
	profileCompiler = require('jbb-profile-'+profile+"/compiler");

	// Initialize profile compiler
	profileCompiler.initialize(
		openBundle(
			loadImports(
				compileExports(
					closeBundle( callback )
					)
				)
			)
	);

}

/**
 * Export the 'compile' function
 */
module.exports = {
	'compile': compile
};
<|endoftext|>


<commit_before>// for debug only
var __kb;
var __scope;

/**
 * The main app
 */
var App = angular.module('Vocab', [
  'ngAudio',
  'lumx'
]);

App.config(function($locationProvider) {
  $locationProvider
    .html5Mode({ enabled: true, requireBase: false });
});

App.controller('Main', function($scope, $http, $location, $timeout, ngAudio, LxNotificationService, LxProgressService, LxDialogService) {
  // Namespaces
  var CHAT  = $rdf.Namespace("https://ns.rww.io/chat#");
  var CURR  = $rdf.Namespace("https://w3id.org/cc#");
  var DCT   = $rdf.Namespace("http://purl.org/dc/terms/");
  var FACE  = $rdf.Namespace("https://graph.facebook.com/schema/~/");
  var FOAF  = $rdf.Namespace("http://xmlns.com/foaf/0.1/");
  var LIKE  = $rdf.Namespace("http://ontologi.es/like#");
  var LDP   = $rdf.Namespace("http://www.w3.org/ns/ldp#");
  var MBLOG = $rdf.Namespace("http://www.w3.org/ns/mblog#");
  var OWL   = $rdf.Namespace("http://www.w3.org/2002/07/owl#");
  var PIM   = $rdf.Namespace("http://www.w3.org/ns/pim/space#");
  var RDF   = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
  var RDFS  = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#");
  var SIOC  = $rdf.Namespace("http://rdfs.org/sioc/ns#");
  var SOLID = $rdf.Namespace("http://www.w3.org/ns/solid/app#");
  var TMP   = $rdf.Namespace("urn:tmp:");

  var f,g;

  // INIT
  /**
   * Init app
   */
  $scope.initApp = function() {
    $scope.init();
  };

  /**
   * Set Initial variables
   */
  $scope.init = function() {

    $scope.firstLang = 'cs';
    $scope.secondLang = 'en';
    $scope.initialized = true;
    $scope.loggedIn = false;
    $scope.loginTLSButtonText = "Login";
    $scope.points = 0;
    $scope.current = 0;
    $scope.percent = 0;
    $scope.max = 2000;

    $scope.initRDF();
    $scope.initQueryString();
    $scope.initLocalStorage();

    __kb = g;
    __scope = $scope;
  };

  /**
   * Get values from localStorage
   */
  $scope.initLocalStorage = function() {
    if (localStorage.getItem('again')) {
      $scope.again = JSON.parse(localStorage.getItem('again'));
    } else {
      $scope.again = [];
    }
    if (localStorage.getItem('good')) {
      $scope.good = JSON.parse(localStorage.getItem('good'));
    } else {
      $scope.good = [];
    }
    if (localStorage.getItem('easy')) {
      $scope.easy = JSON.parse(localStorage.getItem('easy'));
    } else {
      $scope.easy = [];
    }
    if (localStorage.getItem('user')) {
      var user = JSON.parse(localStorage.getItem('user'));
      $scope.loginSuccess(user);
    }
  };

  /**
   * init RDF knowledge base
   */
  $scope.initRDF = function() {
    var PROXY = "https://rww.io/proxy.php?uri={uri}";
    var AUTH_PROXY = "https://rww.io/auth-proxy?uri=";
    var TIMEOUT = 90000;
    $rdf.Fetcher.crossSiteProxyTemplate=PROXY;

    g = $rdf.graph();
    f = $rdf.fetcher(g, TIMEOUT);
  };

  /**
   * init from query string
   */
  $scope.initQueryString = function() {
    if ($location.search().max) {
      $scope.max = $location.search().max;
    }
    $scope.setMax($scope.max);

    $scope.storageURI = 'https://melvincarvalho.github.io/data/vocab/czech.ttl';
    if ($location.search().storageURI) {
      $scope.storageURI = $location.search().storageURI;
    }
    $scope.setStorageURI($scope.storageURI);

  };

  /**
   * setMax set maximum number of words
   * @param  {Number} max number or words
   */
  $scope.setMax = function(max) {
    $scope.max = max;
    $location.search('max', $scope.max);
  };

  /**
   * setStorageURI set the storage URI for words
   * @param  {String} the storage URI for words
   */
  $scope.setStorageURI = function(storageURI) {
    $scope.storageURI = storageURI;
    $location.search('storageURI', $scope.storageURI);
  };

  // AUTH
  /**
  * TLS Login with WebID
  */
  $scope.TLSlogin = function() {
    var AUTHENDPOINT = "https://databox.me/";
    $scope.loginTLSButtonText = 'Logging in...';
    $http({
      method: 'HEAD',
      url: AUTHENDPOINT,
      withCredentials: true
    }).success(function(data, status, headers) {
      var header = 'User';
      var scheme = 'http';
      var user = headers(header);
      if (user && user.length > 0 && user.slice(0,scheme.length) === scheme) {
        $scope.loginSuccess(user);
      } else {
        $scope.notify('WebID-TLS authentication failed.', 'error');
      }
      $scope.loginTLSButtonText = 'Login';
    }).error(function(data, status, headers) {
      $scope.notify('Could not connect to auth server: HTTP '+status);
      $scope.loginTLSButtonText = 'Login';
    });
  };

  /**
  * loginSuccess called after successful login
  * @param  {String} user the logged in user
  */
  $scope.loginSuccess = function(user) {
    $scope.notify('Login Successful!');
    $scope.loggedIn = true;
    $scope.user = user;
    $scope.fetchAll();
    $('#second').hide('tc-black');
    localStorage.setItem('user', JSON.stringify(user));
  };

  /**
  * Logout
  */
  $scope.logout = function() {
    $scope.init();
    $scope.notify('Logout Successful!');
    localStorage.removeItem('user');
  };

  // FETCH
  /**
  * fecthAll fetches everything
  */
  $scope.fetchAll = function() {
    $scope.fetchStorageURI();
    $scope.fetchSeeAlso();
  };

  /**
   * fetchSeeAlso fetches the see also
   */
  $scope.fetchSeeAlso = function() {
    var seeAlso = 'https://melvincarvalho.github.io/vocab/data/seeAlso.ttl';
    if ($location.search().seeAlso) {
      seeAlso = $location.search().seeAlso;
    }
    f.nowOrWhenFetched(seeAlso, undefined, function(ok, body) {
      console.log('seeAlso fetched from : ' + seeAlso);
    });

  };

  /**
   * fetches the word list from the storageURI
   */
  $scope.fetchStorageURI = function() {
    var dict = $scope.firstLang + '-' + $scope.secondLang;
    if (localStorage.getItem(dict)) {
      $scope.uncacheDictionary();
      return;
    }
    f.nowOrWhenFetched($scope.storageURI, undefined, function(ok, body) {
      console.log('vocab list fetched from : ' + $scope.storageURI);
      $scope.notify('words loaded');
      $scope.next();
      if (!localStorage.getItem(dict)) {
        $scope.cacheDictionary();
      }
    });

  };

  /**
   * Save clip
   */
  $scope.save = function() {
    var clipboard = $scope.clipboard;
    if (!clipboard) {
      $scope.notify('clipboard is empty', 'error');
      return;
    }
    console.log(clipboard);

    $http({
        method: 'PUT',
        url: $scope.storageURI,
        withCredentials: true,
        headers: {
            "Content-Type": "text/turtle"
        },
        data: '<#this> <urn:tmp:clipboard> """' + clipboard + '""" .',
    }).
    success(function(data, status, headers) {
      $scope.notify('clipboard saved');
      $location.search('storageURI', $scope.storageURI);
    }).
    error(function(data, status, headers) {
      $scope.notify('could not save clipboard', 'error');
    });

  };

  /**
   * cache the dictionary
   */
  $scope.cacheDictionary = function() {
    var dict = $scope.firstLang + '-' + $scope.secondLang;
    var words = [];
    for (var i=1; i<=10000; i++) {
      words.push($scope.getPair(i));
    }
    localStorage.setItem(dict, JSON.stringify(words));
    console.log('dict ' + dict + ' saved');
  };

  /**
   * uncache the dictionary
   */
  $scope.uncacheDictionary = function() {
    var lit;
    var dict = $scope.firstLang + '-' + $scope.secondLang;
    var words = JSON.parse(localStorage.getItem(dict));
    var statement;
    for (var i=0; i<words.length; i++) {
      //console.log(words[i]);

      lit = $rdf.lit(words[i][$scope.firstLang]);
      lit.lang = $scope.firstLang;
      g.add(
        $rdf.sym($scope.storageURI + '#' + (i + 1)),
        RDFS('label'),
        $rdf.lit(words[i][$scope.firstLang]),
        $rdf.sym($scope.storageURI)
      );

      lit = $rdf.lit(words[i][$scope.secondLang]);
      lit.lang = $scope.secondLang;
      g.add(
        $rdf.sym($scope.storageURI + '#' + (i + 1)),
        RDFS('label'),
        $rdf.lit(lit),
        $rdf.sym($scope.storageURI)
      );

    }
    console.log('vocab list fetched from : ' + $scope.storageURI);
  };

  // HELPER
  /**
  * Notify
  * @param  {String} message the message to display
  * @param  {String} type the type of notification, error or success
  */
  $scope.notify = function(message, type) {
    console.log(message);
    if (type === 'error') {
      LxNotificationService.error(message);
    } else {
      LxNotificationService.success(message);
    }
  };

  /**
   * incagain increment again
   */
  $scope.incagain = function() {
    if ($scope.again.indexOf($scope.num) === -1) {
      $scope.again.push($scope.num);
      localStorage.setItem('again', JSON.stringify($scope.again));
    }
    $scope.points += 1;
    $scope.percent = Math.round((100* $scope.current) / $scope.points);
    $scope.next();
    $scope.render();
  };

  $scope.incgood = function() {
    if ($scope.good.indexOf($scope.num) === -1) {
      $scope.good.push($scope.num);
      localStorage.setItem('good', JSON.stringify($scope.good));
    }
    $scope.points += 1;
    $scope.percent = Math.round((100* $scope.current) / $scope.points);
    $scope.next();
    $scope.render();
  };

  $scope.inceasy = function() {
    if ($scope.easy.indexOf($scope.num) === -1) {
      $scope.easy.push($scope.num);
      localStorage.setItem('easy', JSON.stringify($scope.easy));
      navigator.vibrate(500);
    }
    $scope.points += 1;
    $scope.current += 1;
    $scope.percent = Math.round((100* $scope.current) / $scope.points);
    $scope.next();
    $scope.render();
  };

  $scope.reset = function() {
    var points = $scope.points;
    $scope.current = 0;
    $scope.points = 0;
    $scope.percent = 0;

    // TODO people specific hooks, generalize
    var inbox = g.any($rdf.sym($scope.user), SOLID('inbox'));
    if (inbox) {
      console.log('writing to : ' + inbox);
      $http({
        method: 'PUT',
        url: inbox.value + 'points.ttl',
        withCredentials: true,
        headers: {
          "Content-Type": "text/turtle"
        },
        data: '<> <> ' + (Math.round(points / 5)*5) + ' .',
      }).
      success(function(data, status, headers) {
        $scope.notify('Points saved');
        $location.search('storageURI', $scope.storageURI);
        $scope.render();
      }).
      error(function(data, status, headers) {
        $scope.notify('could not save points', 'error');
      });
    }
  };

  /**
   * Next value in vocab
   */
  $scope.next = function() {
    $scope.num = Math.round( $scope.max * Math.random() );
    var pair = $scope.getPair($scope.num);
    $scope.first = pair[$scope.firstLang];
    $scope.second = pair[$scope.secondLang];
    $scope.translate = "https://translate.google.com/#cs/en/" + encodeURI($scope.first);
  };

  /**
   * gets a pair of words
   * @param  {Number} num the number of the word
   * @return {Object} object with firstLang word, secondLang word
   */
  $scope.getPair = function(num) {
    var ret = {};
    var words = g.statementsMatching($rdf.sym($scope.storageURI + '#' + num), RDFS('label'));
    for (var i=0; i<words.length; i++) {
      if (words[i].object.lang===$scope.firstLang) {
        ret[$scope.firstLang] = words[i].object.value;
      }
      if (words[i].object.lang===$scope.secondLang) {
        ret[$scope.secondLang] = words[i].object.value;
      }
    }
    return ret;

  };

  /**
   * cycle through word lists
   */
  $scope.cycleMax = function() {
    navigator.vibrate(500);
    var cycle = [2000, 3000, 5000, 10000, 1000];
    var ind = cycle.indexOf($scope.max);
    var next = (ind+1)%(cycle.length);
    $scope.setMax(cycle[next]);
    $scope.notify('Using ' + cycle[next] + ' words');
  };

  /**
  * toggle toggles second field
  */
  $scope.toggle = function() {
    $('#second').show('tc-black');
    setTimeout(function() { $('#second').hide('tc-black'); }, 600);
  };

  // RENDER
  /**
   * render screen
   */
  $scope.render = function() {
    var col = Math.round(($scope.percent*200)/100);
    $('.percent').css('color', 'rgb(0,'+col+',0)');
  };

  /**
  * openDialog opens a dialog box
  * @param  {String} elem  The element to display
  */
  $scope.openDialog = function(elem) {
    LxDialogService.open(elem);
    $(document).keyup(function(e) {
      if (e.keyCode===27) {
        LxDialogService.close(elem);
      }
    });
  };

  $scope.initApp();

});
<commit_msg>Bugfix<commit_after>// for debug only
var __kb;
var __scope;

/**
 * The main app
 */
var App = angular.module('Vocab', [
  'ngAudio',
  'lumx'
]);

App.config(function($locationProvider) {
  $locationProvider
    .html5Mode({ enabled: true, requireBase: false });
});

App.controller('Main', function($scope, $http, $location, $timeout, ngAudio, LxNotificationService, LxProgressService, LxDialogService) {
  // Namespaces
  var CHAT  = $rdf.Namespace("https://ns.rww.io/chat#");
  var CURR  = $rdf.Namespace("https://w3id.org/cc#");
  var DCT   = $rdf.Namespace("http://purl.org/dc/terms/");
  var FACE  = $rdf.Namespace("https://graph.facebook.com/schema/~/");
  var FOAF  = $rdf.Namespace("http://xmlns.com/foaf/0.1/");
  var LIKE  = $rdf.Namespace("http://ontologi.es/like#");
  var LDP   = $rdf.Namespace("http://www.w3.org/ns/ldp#");
  var MBLOG = $rdf.Namespace("http://www.w3.org/ns/mblog#");
  var OWL   = $rdf.Namespace("http://www.w3.org/2002/07/owl#");
  var PIM   = $rdf.Namespace("http://www.w3.org/ns/pim/space#");
  var RDF   = $rdf.Namespace("http://www.w3.org/1999/02/22-rdf-syntax-ns#");
  var RDFS  = $rdf.Namespace("http://www.w3.org/2000/01/rdf-schema#");
  var SIOC  = $rdf.Namespace("http://rdfs.org/sioc/ns#");
  var SOLID = $rdf.Namespace("http://www.w3.org/ns/solid/app#");
  var TMP   = $rdf.Namespace("urn:tmp:");

  var f,g;

  // INIT
  /**
   * Init app
   */
  $scope.initApp = function() {
    $scope.init();
  };

  /**
   * Set Initial variables
   */
  $scope.init = function() {

    $scope.firstLang = 'cs';
    $scope.secondLang = 'en';
    $scope.initialized = true;
    $scope.loggedIn = false;
    $scope.loginTLSButtonText = "Login";
    $scope.points = 0;
    $scope.current = 0;
    $scope.percent = 0;
    $scope.max = 2000;

    $scope.initRDF();
    $scope.initQueryString();
    $scope.initLocalStorage();

    __kb = g;
    __scope = $scope;
  };

  /**
   * Get values from localStorage
   */
  $scope.initLocalStorage = function() {
    if (localStorage.getItem('again')) {
      $scope.again = JSON.parse(localStorage.getItem('again'));
    } else {
      $scope.again = [];
    }
    if (localStorage.getItem('good')) {
      $scope.good = JSON.parse(localStorage.getItem('good'));
    } else {
      $scope.good = [];
    }
    if (localStorage.getItem('easy')) {
      $scope.easy = JSON.parse(localStorage.getItem('easy'));
    } else {
      $scope.easy = [];
    }
    if (localStorage.getItem('user')) {
      var user = JSON.parse(localStorage.getItem('user'));
      $scope.loginSuccess(user);
    }
  };

  /**
   * init RDF knowledge base
   */
  $scope.initRDF = function() {
    var PROXY = "https://rww.io/proxy.php?uri={uri}";
    var AUTH_PROXY = "https://rww.io/auth-proxy?uri=";
    var TIMEOUT = 90000;
    $rdf.Fetcher.crossSiteProxyTemplate=PROXY;

    g = $rdf.graph();
    f = $rdf.fetcher(g, TIMEOUT);
  };

  /**
   * init from query string
   */
  $scope.initQueryString = function() {
    if ($location.search().max) {
      $scope.max = $location.search().max;
    }
    $scope.setMax($scope.max);

    $scope.storageURI = 'https://melvincarvalho.github.io/data/vocab/czech.ttl';
    if ($location.search().storageURI) {
      $scope.storageURI = $location.search().storageURI;
    }
    $scope.setStorageURI($scope.storageURI);

  };

  /**
   * setMax set maximum number of words
   * @param  {Number} max number or words
   */
  $scope.setMax = function(max) {
    $scope.max = max;
    $location.search('max', $scope.max);
  };

  /**
   * setStorageURI set the storage URI for words
   * @param  {String} the storage URI for words
   */
  $scope.setStorageURI = function(storageURI) {
    $scope.storageURI = storageURI;
    $location.search('storageURI', $scope.storageURI);
  };

  // AUTH
  /**
  * TLS Login with WebID
  */
  $scope.TLSlogin = function() {
    var AUTHENDPOINT = "https://databox.me/";
    $scope.loginTLSButtonText = 'Logging in...';
    $http({
      method: 'HEAD',
      url: AUTHENDPOINT,
      withCredentials: true
    }).success(function(data, status, headers) {
      var header = 'User';
      var scheme = 'http';
      var user = headers(header);
      if (user && user.length > 0 && user.slice(0,scheme.length) === scheme) {
        $scope.loginSuccess(user);
      } else {
        $scope.notify('WebID-TLS authentication failed.', 'error');
      }
      $scope.loginTLSButtonText = 'Login';
    }).error(function(data, status, headers) {
      $scope.notify('Could not connect to auth server: HTTP '+status);
      $scope.loginTLSButtonText = 'Login';
    });
  };

  /**
  * loginSuccess called after successful login
  * @param  {String} user the logged in user
  */
  $scope.loginSuccess = function(user) {
    $scope.notify('Login Successful!');
    $scope.loggedIn = true;
    $scope.user = user;
    $scope.fetchAll();
    $('#second').hide('tc-black');
    localStorage.setItem('user', JSON.stringify(user));
  };

  /**
  * Logout
  */
  $scope.logout = function() {
    $scope.init();
    $scope.notify('Logout Successful!');
    localStorage.removeItem('user');
  };

  // FETCH
  /**
  * fecthAll fetches everything
  */
  $scope.fetchAll = function() {
    $scope.fetchStorageURI();
    $scope.fetchSeeAlso();
  };

  /**
   * fetchSeeAlso fetches the see also
   */
  $scope.fetchSeeAlso = function() {
    var seeAlso = 'https://melvincarvalho.github.io/vocab/data/seeAlso.ttl';
    if ($location.search().seeAlso) {
      seeAlso = $location.search().seeAlso;
    }
    f.nowOrWhenFetched(seeAlso, undefined, function(ok, body) {
      console.log('seeAlso fetched from : ' + seeAlso);
    });

  };

  /**
   * fetches the word list from the storageURI
   */
  $scope.fetchStorageURI = function() {
    var dict = $scope.firstLang + '-' + $scope.secondLang;
    if (localStorage.getItem(dict)) {
      $scope.uncacheDictionary();
      return;
    }
    f.nowOrWhenFetched($scope.storageURI, undefined, function(ok, body) {
      console.log('vocab list fetched from : ' + $scope.storageURI);
      $scope.notify('words loaded');
      $scope.next();
      if (!localStorage.getItem(dict)) {
        $scope.cacheDictionary();
      }
    });

  };

  /**
   * Save clip
   */
  $scope.save = function() {
    var clipboard = $scope.clipboard;
    if (!clipboard) {
      $scope.notify('clipboard is empty', 'error');
      return;
    }
    console.log(clipboard);

    $http({
        method: 'PUT',
        url: $scope.storageURI,
        withCredentials: true,
        headers: {
            "Content-Type": "text/turtle"
        },
        data: '<#this> <urn:tmp:clipboard> """' + clipboard + '""" .',
    }).
    success(function(data, status, headers) {
      $scope.notify('clipboard saved');
      $location.search('storageURI', $scope.storageURI);
    }).
    error(function(data, status, headers) {
      $scope.notify('could not save clipboard', 'error');
    });

  };

  /**
   * cache the dictionary
   */
  $scope.cacheDictionary = function() {
    var dict = $scope.firstLang + '-' + $scope.secondLang;
    var words = [];
    for (var i=1; i<=10000; i++) {
      words.push($scope.getPair(i));
    }
    localStorage.setItem(dict, JSON.stringify(words));
    console.log('dict ' + dict + ' saved');
  };

  /**
   * uncache the dictionary
   */
  $scope.uncacheDictionary = function() {
    var lit;
    var dict = $scope.firstLang + '-' + $scope.secondLang;
    var words = JSON.parse(localStorage.getItem(dict));
    var statement;
    for (var i=0; i<words.length; i++) {
      //console.log(words[i]);

      lit = $rdf.lit(words[i][$scope.firstLang]);
      lit.lang = $scope.firstLang;
      g.add(
        $rdf.sym($scope.storageURI + '#' + (i + 1)),
        RDFS('label'),
        lit,
        $rdf.sym($scope.storageURI)
      );

      lit = $rdf.lit(words[i][$scope.secondLang]);
      lit.lang = $scope.secondLang;
      g.add(
        $rdf.sym($scope.storageURI + '#' + (i + 1)),
        RDFS('label'),
        lit,
        $rdf.sym($scope.storageURI)
      );

    }
    console.log('vocab list fetched from : ' + $scope.storageURI);
  };

  // HELPER
  /**
  * Notify
  * @param  {String} message the message to display
  * @param  {String} type the type of notification, error or success
  */
  $scope.notify = function(message, type) {
    console.log(message);
    if (type === 'error') {
      LxNotificationService.error(message);
    } else {
      LxNotificationService.success(message);
    }
  };

  /**
   * incagain increment again
   */
  $scope.incagain = function() {
    if ($scope.again.indexOf($scope.num) === -1) {
      $scope.again.push($scope.num);
      localStorage.setItem('again', JSON.stringify($scope.again));
    }
    $scope.points += 1;
    $scope.percent = Math.round((100* $scope.current) / $scope.points);
    $scope.next();
    $scope.render();
  };

  $scope.incgood = function() {
    if ($scope.good.indexOf($scope.num) === -1) {
      $scope.good.push($scope.num);
      localStorage.setItem('good', JSON.stringify($scope.good));
    }
    $scope.points += 1;
    $scope.percent = Math.round((100* $scope.current) / $scope.points);
    $scope.next();
    $scope.render();
  };

  $scope.inceasy = function() {
    if ($scope.easy.indexOf($scope.num) === -1) {
      $scope.easy.push($scope.num);
      localStorage.setItem('easy', JSON.stringify($scope.easy));
      navigator.vibrate(500);
    }
    $scope.points += 1;
    $scope.current += 1;
    $scope.percent = Math.round((100* $scope.current) / $scope.points);
    $scope.next();
    $scope.render();
  };

  $scope.reset = function() {
    var points = $scope.points;
    $scope.current = 0;
    $scope.points = 0;
    $scope.percent = 0;

    // TODO people specific hooks, generalize
    var inbox = g.any($rdf.sym($scope.user), SOLID('inbox'));
    if (inbox) {
      console.log('writing to : ' + inbox);
      $http({
        method: 'PUT',
        url: inbox.value + 'points.ttl',
        withCredentials: true,
        headers: {
          "Content-Type": "text/turtle"
        },
        data: '<> <> ' + (Math.round(points / 5)*5) + ' .',
      }).
      success(function(data, status, headers) {
        $scope.notify('Points saved');
        $location.search('storageURI', $scope.storageURI);
        $scope.render();
      }).
      error(function(data, status, headers) {
        $scope.notify('could not save points', 'error');
      });
    }
  };

  /**
   * Next value in vocab
   */
  $scope.next = function() {
    $scope.num = Math.round( $scope.max * Math.random() );
    var pair = $scope.getPair($scope.num);
    $scope.first = pair[$scope.firstLang];
    $scope.second = pair[$scope.secondLang];
    $scope.translate = "https://translate.google.com/#cs/en/" + encodeURI($scope.first);
  };

  /**
   * gets a pair of words
   * @param  {Number} num the number of the word
   * @return {Object} object with firstLang word, secondLang word
   */
  $scope.getPair = function(num) {
    var ret = {};
    var words = g.statementsMatching($rdf.sym($scope.storageURI + '#' + num), RDFS('label'));
    for (var i=0; i<words.length; i++) {
      if (words[i].object.lang===$scope.firstLang) {
        ret[$scope.firstLang] = words[i].object.value;
      }
      if (words[i].object.lang===$scope.secondLang) {
        ret[$scope.secondLang] = words[i].object.value;
      }
    }
    return ret;

  };

  /**
   * cycle through word lists
   */
  $scope.cycleMax = function() {
    navigator.vibrate(500);
    var cycle = [2000, 3000, 5000, 10000, 1000];
    var ind = cycle.indexOf($scope.max);
    var next = (ind+1)%(cycle.length);
    $scope.setMax(cycle[next]);
    $scope.notify('Using ' + cycle[next] + ' words');
  };

  /**
  * toggle toggles second field
  */
  $scope.toggle = function() {
    $('#second').show('tc-black');
    setTimeout(function() { $('#second').hide('tc-black'); }, 600);
  };

  // RENDER
  /**
   * render screen
   */
  $scope.render = function() {
    var col = Math.round(($scope.percent*200)/100);
    $('.percent').css('color', 'rgb(0,'+col+',0)');
  };

  /**
  * openDialog opens a dialog box
  * @param  {String} elem  The element to display
  */
  $scope.openDialog = function(elem) {
    LxDialogService.open(elem);
    $(document).keyup(function(e) {
      if (e.keyCode===27) {
        LxDialogService.close(elem);
      }
    });
  };

  $scope.initApp();

});
<|endoftext|>


<commit_before>var goog = require('closure').Closure({CLOSURE_BASE_PATH: 'ext\\closure-library\\closure\\goog\\'});
require('./ext/closure-library/closure/goog/bootstrap/nodejs')
goog.require('goog.Uri');

goog.provide('gee');
goog.provide('gee.initialize');

initialize = function(onsuccess) {
  var google = require('googleapis');
  var OAuth2 = google.auth.OAuth2;
  var fs = require('fs')

  var AUTH_FILE = 'config/authinfo.json';

  var home = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
  var REFRESH_TOKEN_FILE = home + '/.config/earthengine/credentials';
  //var REFRESH_TOKEN_FILE = 'config/refresh_token.json';

  var o = JSON.parse(fs.readFileSync(AUTH_FILE, 'utf8'));
  var client = new OAuth2(o.client_id, o.client_secret, o.redirect_uri);

  // generate refresh token
  if (!fs.existsSync(REFRESH_TOKEN_FILE)) {
    var toQueryData = function(params) {
      var queryData = new goog.Uri.QueryData();
      for (var item in params) {
        queryData.set(item, params[item]);
      }
      return queryData;
    }

    var params = {
      'scope': 'https://www.googleapis.com/auth/earthengine.readonly',
      'redirect_uri': o.redirect_uri,
      'response_type': 'code',
      'client_id': o.client_id
    };

    var uri = 'https://accounts.google.com/o/oauth2/auth?' + toQueryData(params).toString()

    //goog.Uri.create('https', null, 'accounts.google.com', null, '/o/oauth2/auth', toQueryData(params));

    // open browser to get authorization code
    var opener = require('opener')
    opener(uri)

    // ask user to enter authorization code
    var readline = require('readline-sync');
    var auth_code = readline.question('Please enter authorization code: ');

    console.log('Entered code: ' + auth_code);

    // request refresh token
    params = {
      'code': auth_code,
      'client_id': o.client_id,
      'client_secret': o.client_secret,
      'redirect_uri': o.redirect_uri,
      'grant_type': 'authorization_code'
    }
    console.log('https://accounts.google.com/o/oauth2/token?' + toQueryData(params).toString())

    var refresh_token = null;
    var request = require('request');
    request.post('https://accounts.google.com/o/oauth2/token', {form: params}, function optionalCallback(err, httpResponse, body) {
      if (err) {
        return console.error('upload failed:', err);
      }
      refresh_token = JSON.parse(body).refresh_token;
    });

    // wait for results
    while(refresh_token == null) {
       require('deasync').sleep(100);
    }

    // write refresh_token to config file
    fs.writeFileSync(REFRESH_TOKEN_FILE, JSON.stringify({ refresh_token: refresh_token }), 'utf8');
  }

  var o2 = JSON.parse(fs.readFileSync(REFRESH_TOKEN_FILE, 'utf8'));
  client.setCredentials({refresh_token: o2.refresh_token});

  client.refreshAccessToken(function(err, tokens) {
    ee.data.authToken_ = 'Bearer ' + tokens['access_token'];
    ee.data.authClientId_ = o.cliet_id
    ee.data.authScopes_ = [ee.data.AUTH_SCOPE_]
    ee.data.DEFAULT_API_BASE_URL_ = "https://earthengine.googleapis.com/api"
    ee.initialize(ee.data.DEFAULT_API_BASE_URL_);

    onsuccess();
  });
}

module.exports.initialize = initialize

// initialize()<commit_msg>fixed path problems<commit_after>var goog = require('closure').Closure({CLOSURE_BASE_PATH: 'ext\\closure-library\\closure\\goog' + require('path').sep});
require('./ext/closure-library/closure/goog/bootstrap/nodejs')
goog.require('goog.Uri');

goog.provide('gee');
goog.provide('gee.initialize');

initialize = function(onsuccess) {
  var google = require('googleapis');
  var OAuth2 = google.auth.OAuth2;
  var fs = require('fs')

  var AUTH_FILE = 'config/authinfo.json';

  var home = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
  var REFRESH_TOKEN_FILE = home + '/.config/earthengine/credentials';
  //var REFRESH_TOKEN_FILE = 'config/refresh_token.json';

  var o = JSON.parse(fs.readFileSync(AUTH_FILE, 'utf8'));
  var client = new OAuth2(o.client_id, o.client_secret, o.redirect_uri);

  // generate refresh token
  if (!fs.existsSync(REFRESH_TOKEN_FILE)) {
    var toQueryData = function(params) {
      var queryData = new goog.Uri.QueryData();
      for (var item in params) {
        queryData.set(item, params[item]);
      }
      return queryData;
    }

    var params = {
      'scope': 'https://www.googleapis.com/auth/earthengine.readonly',
      'redirect_uri': o.redirect_uri,
      'response_type': 'code',
      'client_id': o.client_id
    };

    var uri = 'https://accounts.google.com/o/oauth2/auth?' + toQueryData(params).toString()

    //goog.Uri.create('https', null, 'accounts.google.com', null, '/o/oauth2/auth', toQueryData(params));

    // open browser to get authorization code
    var opener = require('opener')
    opener(uri)

    // ask user to enter authorization code
    var readline = require('readline-sync');
    var auth_code = readline.question('Please enter authorization code: ');

    console.log('Entered code: ' + auth_code);

    // request refresh token
    params = {
      'code': auth_code,
      'client_id': o.client_id,
      'client_secret': o.client_secret,
      'redirect_uri': o.redirect_uri,
      'grant_type': 'authorization_code'
    }
    console.log('https://accounts.google.com/o/oauth2/token?' + toQueryData(params).toString())

    var refresh_token = null;
    var request = require('request');
    request.post('https://accounts.google.com/o/oauth2/token', {form: params}, function optionalCallback(err, httpResponse, body) {
      if (err) {
        return console.error('upload failed:', err);
      }
      refresh_token = JSON.parse(body).refresh_token;
    });

    // wait for results
    while(refresh_token == null) {
       require('deasync').sleep(100);
    }

    // write refresh_token to config file
    fs.writeFileSync(REFRESH_TOKEN_FILE, JSON.stringify({ refresh_token: refresh_token }), 'utf8');
  }

  var o2 = JSON.parse(fs.readFileSync(REFRESH_TOKEN_FILE, 'utf8'));
  client.setCredentials({refresh_token: o2.refresh_token});

  client.refreshAccessToken(function(err, tokens) {
    ee.data.authToken_ = 'Bearer ' + tokens['access_token'];
    ee.data.authClientId_ = o.cliet_id
    ee.data.authScopes_ = [ee.data.AUTH_SCOPE_]
    ee.data.DEFAULT_API_BASE_URL_ = "https://earthengine.googleapis.com/api"
    ee.initialize(ee.data.DEFAULT_API_BASE_URL_);

    onsuccess();
  });
}

module.exports.initialize = initialize

// initialize()<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on views, and components
angular.module('collaborate', [
  'ui.router',
  'ngAnimate',
  'ui.bootstrap',
  'home',
  'login',
  'services',
  'directives'
]).
config(['$urlRouterProvider','$httpProvider', function($urlRouterProvider, $httpProvider) {
  $httpProvider.interceptors.push('requestInterceptor');
  $urlRouterProvider.otherwise('/login');
  io.connect(window.__config.socketEndPoint);
}]);<commit_msg>Remove socket connection on app load for security<commit_after>'use strict';

// Declare app level module which depends on views, and components
angular.module('collaborate', [
  'ui.router',
  'ngAnimate',
  'ui.bootstrap',
  'home',
  'login',
  'services',
  'directives'
]).
config(['$urlRouterProvider','$httpProvider', function($urlRouterProvider, $httpProvider) {
  $httpProvider.interceptors.push('requestInterceptor');
  $urlRouterProvider.otherwise('/login');
}]);<|endoftext|>