<commit_before>// Node modules

var https = require('https'),
  url = require('url');
  fs = require('fs');
// EdgeGrid Auth Module
var auth = require('./auth.js');

var _client_token = null,
  _client_secret = null,
  _access_token = null,
  _base_uri = null,
  _request = null;

function parseEdgerc(path, conf) {
  var edgerc = fs.readFileSync(path).toString().split("\n");
  var confData = [];
  for(var i=0;i<edgerc.length;i++) {
    var matchConf = edgerc[i].match(/\[(.*)\]/);
    // if we found our matching config, push the next 4 lines into a temp array
    if (matchConf && matchConf[1] === conf) {
      confData.push(edgerc[i+1]);
      confData.push(edgerc[i+2]);
      confData.push(edgerc[i+3]);
      confData.push(edgerc[i+4]);
      // convert the array to a descriptive object
      confData = confData.map(function(el) {
        var ret = {}
        var key = el.split(' = ')[0].trim();
        var val = el.split(' = ')[1].trim();
        if (key === 'host') {
          val = 'https://' + val;
        }
        ret[key] = val;
        return ret;
      });
      // turn the array of objects into a single object
      var result = {};
      for (var i = 0, length = confData.length; i < length; i++) {
        result[Object.keys(confData[i])[0]] = confData[i][Object.keys(confData[i])[0]];
      }
      return result;
    }
  }
  // if we escaped the parse loop without returning, something is wrong
  throw('An error occurred parsing the .edgerc file. You probably specified an invalid group name.');
}

var EdgeGrid = function(client_token, client_secret, access_token, base_uri) {
  // accepting an object containing a path to .edgerc and a config group
  if (typeof arguments[0] === 'object') {
    var path = arguments[0].path;
    var group = arguments[0].group;
    if (path === undefined) {
      console.log("No .edgerc path");
      return false;
    }
    if (group === undefined) {
      console.log("No .edgerc group provided, using 'default'");
      group = 'default';
    }
    var config = parseEdgerc(path, group);
    _client_token = config.client_token;
    _client_secret = config.client_secret;
    _access_token = config.access_token;
    _base_uri = config.host;
  }
  else {
    if (client_token === undefined || client_token === null) {
      console.log("No client token");
      return false;
    } else if (client_secret === undefined || client_secret === null) {
      console.log("No client secret");
      return false;
    } else if (access_token === undefined || access_token === null) {
      console.log("No access token");
      return false;
    } else if (base_uri === undefined || base_uri === null) {
      console.log("No base uri");
      return false;
    }

    _client_token = client_token;
    _client_secret = client_secret;
    _access_token = access_token;
    _base_uri = base_uri;
  }

  return this;

};

EdgeGrid.prototype.auth = function(request, callback) {
  _request = auth.generate_auth(request, _client_token, _client_secret, _access_token, _base_uri);

  if (callback && typeof callback == "function") {
    callback(this);
  }

  return this;
};

EdgeGrid.prototype.send = function(callback) {

  var request = _request,
    data = "";

  var parts = url.parse(request.url);
  request.hostname = parts.hostname;
  request.port = parts.port;
  request.path = parts.path;

  if (request.method == "POST" || request.method == "PUT") {
    request.headers["content-type"] = 'application/x-www-form-urlencoded';
    request.headers['content-length'] = request.body.length;
  }

  var req = https.request(request, function(res) {
    res.on('data', function(d) {
      data += d;
    });

    res.on('end', function() {
      if (callback && typeof callback == "function") {
        callback(data, res);
      }

    });
  });

  if (request.method == "POST" || request.method == "PUT") {
    req.write(request.body);
  }

  req.end();
};

module.exports = EdgeGrid;
<commit_msg>Adding support for user-defined content-type header since some APIs need 'application/xml' and may in fact use other content types in the future<commit_after>// Node modules

var https = require('https'),
  url = require('url');
  fs = require('fs');
// EdgeGrid Auth Module
var auth = require('./auth.js');

var _client_token = null,
  _client_secret = null,
  _access_token = null,
  _base_uri = null,
  _request = null;

function parseEdgerc(path, conf) {
  var edgerc = fs.readFileSync(path).toString().split("\n");
  var confData = [];
  for(var i=0;i<edgerc.length;i++) {
    var matchConf = edgerc[i].match(/\[(.*)\]/);
    // if we found our matching config, push the next 4 lines into a temp array
    if (matchConf && matchConf[1] === conf) {
      confData.push(edgerc[i+1]);
      confData.push(edgerc[i+2]);
      confData.push(edgerc[i+3]);
      confData.push(edgerc[i+4]);
      // convert the array to a descriptive object
      confData = confData.map(function(el) {
        var ret = {}
        var key = el.split(' = ')[0].trim();
        var val = el.split(' = ')[1].trim();
        if (key === 'host') {
          val = 'https://' + val;
        }
        ret[key] = val;
        return ret;
      });
      // turn the array of objects into a single object
      var result = {};
      for (var i = 0, length = confData.length; i < length; i++) {
        result[Object.keys(confData[i])[0]] = confData[i][Object.keys(confData[i])[0]];
      }
      return result;
    }
  }
  // if we escaped the parse loop without returning, something is wrong
  throw('An error occurred parsing the .edgerc file. You probably specified an invalid group name.');
}

var EdgeGrid = function(client_token, client_secret, access_token, base_uri) {
  // accepting an object containing a path to .edgerc and a config group
  if (typeof arguments[0] === 'object') {
    var path = arguments[0].path;
    var group = arguments[0].group;
    if (path === undefined) {
      console.log("No .edgerc path");
      return false;
    }
    if (group === undefined) {
      console.log("No .edgerc group provided, using 'default'");
      group = 'default';
    }
    var config = parseEdgerc(path, group);
    _client_token = config.client_token;
    _client_secret = config.client_secret;
    _access_token = config.access_token;
    _base_uri = config.host;
  }
  else {
    if (client_token === undefined || client_token === null) {
      console.log("No client token");
      return false;
    } else if (client_secret === undefined || client_secret === null) {
      console.log("No client secret");
      return false;
    } else if (access_token === undefined || access_token === null) {
      console.log("No access token");
      return false;
    } else if (base_uri === undefined || base_uri === null) {
      console.log("No base uri");
      return false;
    }

    _client_token = client_token;
    _client_secret = client_secret;
    _access_token = access_token;
    _base_uri = base_uri;
  }

  return this;

};

EdgeGrid.prototype.auth = function(request, callback) {
  _request = auth.generate_auth(request, _client_token, _client_secret, _access_token, _base_uri);

  if (callback && typeof callback == "function") {
    callback(this);
  }

  return this;
};

EdgeGrid.prototype.send = function(callback) {

  var request = _request,
    data = "";

  var parts = url.parse(request.url);
  request.hostname = parts.hostname;
  request.port = parts.port;
  request.path = parts.path;

  // headers are case-insensitive so this function returns the value of a header
  // no matter what its case is. Returns undefined if there's no header defined.
  request.getHeader = function(header) {
    var result = undefined;
    for (k in this.headers) {
      if (k.toLowerCase() === header) {
        result = this.headers[k];
        break;
      }
    }
    return result;
  }

  if (request.method == "POST" || request.method == "PUT") {
    // Accept user-defined, case-insensitive content-type header -- or use default type
    request.headers['content-type'] = request.getHeader('content-type') || 'application/x-www-form-urlencoded';
    request.headers['content-length'] = request.body.length;
  }

  var req = https.request(request, function(res) {
    res.on('data', function(d) {
      data += d;
    });

    res.on('end', function() {
      if (callback && typeof callback == "function") {
        callback(data, res);
      }

    });
  });

  if (request.method == "POST" || request.method == "PUT") {
    req.write(request.body);
  }

  req.end();
};

module.exports = EdgeGrid;
<|endoftext|>


<commit_before>document.getElementById("id_logic_level_version").innerHTML = "Logic level version: 2017.10.25.2";
window.addEventListener('deviceorientation', ondeviceorientation);
window.addEventListener('devicemotion', ondevicemotion);

function ondeviceorientation(event) {

    document.getElementById("id_alpha").innerHTML = Math.round(event.alpha * 100) / 100;
    document.getElementById("id_beta").innerHTML = Math.round(event.beta * 100) / 100;
    document.getElementById("id_gamma").innerHTML = Math.round(event.gamma * 100) / 100;

}

function ondevicemotion(event) {

    document.getElementById("id_acc").innerHTML = "Acc = " + Math.round(event.acceleration.x * 10) / 10+ "  " +Math.round(event.acceleration.y * 10) / 10+ " " +Math.round(event.acceleration.z * 10) / 10;

    var ag = event.accelerationIncludingGravity;
    var x_incl = Math.atan(ag.x / ag.z);
    var y_incl = Math.atan(ag.y / ag.z);
    document.getElementById("id_acc_g").innerHTML = "AccG = " + Math.round(ag.x * 10) / 10+ "  " +Math.round(ag.y * 10) / 10+ " " +Math.round(ag.z * 10) / 10 + "incl_x = " + x.incl + "incl_y = " + y.incl;
    <commit_msg>Adaugare acolada<commit_after>document.getElementById("id_logic_level_version").innerHTML = "Logic level version: 2017.10.25.2";
window.addEventListener('deviceorientation', ondeviceorientation);
window.addEventListener('devicemotion', ondevicemotion);

function ondeviceorientation(event) {

    document.getElementById("id_alpha").innerHTML = Math.round(event.alpha * 100) / 100;
    document.getElementById("id_beta").innerHTML = Math.round(event.beta * 100) / 100;
    document.getElementById("id_gamma").innerHTML = Math.round(event.gamma * 100) / 100;

}

function ondevicemotion(event) {

    document.getElementById("id_acc").innerHTML = "Acc = " + Math.round(event.acceleration.x * 10) / 10+ "  " +Math.round(event.acceleration.y * 10) / 10+ " " +Math.round(event.acceleration.z * 10) / 10;

    var ag = event.accelerationIncludingGravity;
    var x_incl = Math.atan(ag.x / ag.z);
    var y_incl = Math.atan(ag.y / ag.z);
    document.getElementById("id_acc_g").innerHTML = "AccG = " + Math.round(ag.x * 10) / 10+ "  " +Math.round(ag.y * 10) / 10+ " " +Math.round(ag.z * 10) / 10 + "incl_x = " + x.incl + "incl_y = " + y.incl;

}<|endoftext|>


<commit_before>var express = require('express'),
    app = express();

exports.server = function (dirPath, option, callback) {

    app.configure(function () {
        app.use(express.logger());
        app.use(express.compress());
        app.use(app.router);
        app.use(express.static(dirPath));
    });

    app.get('/', function (req, res) {
        res.sendfile(option.homepage+".html", {root:dirPath});
    });

    var server = app.listen(option.port, callback);

    return server;
};
<commit_msg>commits : parse html dom with cheerio, inject svh.js script to client, using SSE.<commit_after>var express = require('express'),
    app = express(),
    fs = require('fs'),
    join = require('path').join,
    cheerio = require('cheerio'),
    concat = require('concat-stream'),
    count = 0;

exports.server = function (dirPath, option, callback) {

    app.configure(function () {
        app.use(express.logger());
        app.use(express.compress());
        app.use(app.router);
        app.use(express.static(__dirname+'/client'));
        app.use(express.static(dirPath));
    });

    app.get('/', function (req, res) {
        var filename = option.homepage + ".html",
            path = join(dirPath, filename),
            stream = fs.createReadStream(path, {encoding: 'utf-8'});

        stream.pipe(concat(function (data) {
            var $ = cheerio.load(data),

            // hack for a good fuck!
            injectan = "<script src='svh.js'></script>"
            $('body').append(injectan);

            res.write($.html());
            res.end();
        }))

        //res.sendfile(filename, {root:dirPath});
    });

    app.get('/reload', function(req, res){

        var event = "reload";
        client = {
            "reload" : option.reload,
            "count": count
        };

        res.writeHead(200, {
            "Content-Type":"text/event-stream",
            "Cache-Control":"no-cache",
            "Connection":"keep-alive"
        });

        var id = (new Date()).toLocaleTimeString();

        res.write("id: " + id + '\n');
        res.write("event: " + event + "\n");
        res.write("data: "+JSON.stringify(client)+"\n\n");
        res.write('retry: 10000\n');

        // Reset
        count = 0;

        res.end();
    });

    var server = app.listen(option.port, callback);
    return server;
};

exports.setReload = function(data){
    count = data;
}
<|endoftext|>


<commit_before>import commander from 'commander'
import {
  resolvePlugins,
  resolvePackages,
  resolveExtends,
  filterDefaultPlugins,
  forEach,
  chdir
} from './util'

export { getConfig } from './util'

import { plugin as exec } from './plugin/exec'
import { plugin as link } from './plugin/link'
import { plugin as init } from './plugin/init'
import { plugin as commit } from './plugin/commit'
import { plugin as release } from './plugin/release'

export const defaultPlugins = [ init, commit, release, exec, link ]

const clone = (...obj) => Object.assign({}, ...obj)

/**
 * Utility function to create a basic plugin
 */
export function basicPlugin (command, description, action, only = false) {
  return function plugin (program, config, directory) {
    if (only) {
      program.command(command)
      .option('-o, --only <packageName>', 'Run a command in a single package')
      .description(description)
      .action((...args) => action(config, directory, ...args))
    } else {
      program.command(command)
      .description(description)
      .action((...args) => action(config, directory, ...args))
    }
  }
}

/**
 * Programmatically run the application
 */
export function setup ({ config, directory, defaultPlugins = [] }) {
  const version = require('../package.json').version

  if (directory) { chdir(directory) }

  const packages = resolvePackages(config, directory)
  if (config && config.packages) {
    config.packages = packages
  }

  const configExtends = resolveExtends(config, directory)

  const defaults = filterDefaultPlugins(config, defaultPlugins)
  const userPlugins = resolvePlugins(config, directory)

  const plugins = defaults.concat(userPlugins)

  const program = commander.version(version)

  forEach(plugins, plugin => plugin(program, clone(configExtends, config), directory))

  return {
    plugins,
    packages,
    version,
    start (args) {
      program.parse(args)
    }
  }
}
<commit_msg>feat(northbrook): add run to default plugins<commit_after>import commander from 'commander'
import {
  resolvePlugins,
  resolvePackages,
  resolveExtends,
  filterDefaultPlugins,
  forEach,
  chdir
} from './util'

export { getConfig } from './util'

import { plugin as exec } from './plugin/exec'
import { plugin as link } from './plugin/link'
import { plugin as init } from './plugin/init'
import { plugin as commit } from './plugin/commit'
import { plugin as release } from './plugin/release'
import { plugin as scripts } from './plugin/run'

export const defaultPlugins = [ init, commit, release, exec, link, scripts ]

const clone = (...obj) => Object.assign({}, ...obj)

/**
 * Utility function to create a basic plugin
 */
export function basicPlugin (command, description, action, only = false) {
  return function plugin (program, config, directory) {
    if (only) {
      program.command(command)
      .option('-o, --only <packageName>', 'Run a command in a single package')
      .description(description)
      .action((...args) => action(config, directory, ...args))
    } else {
      program.command(command)
      .description(description)
      .action((...args) => action(config, directory, ...args))
    }
  }
}

/**
 * Programmatically run the application
 */
export function setup ({ config, directory, defaultPlugins = [] }) {
  const version = require('../package.json').version

  if (directory) { chdir(directory) }

  const packages = resolvePackages(config, directory)
  if (config && config.packages) {
    config.packages = packages
  }

  const configExtends = resolveExtends(config, directory)

  const defaults = filterDefaultPlugins(config, defaultPlugins)
  const userPlugins = resolvePlugins(config, directory)

  const plugins = defaults.concat(userPlugins)

  const program = commander.version(version)

  forEach(plugins, plugin => plugin(program, clone(configExtends, config), directory))

  return {
    plugins,
    packages,
    version,
    start (args) {
      program.parse(args)
    }
  }
}
<|endoftext|>


<commit_before>/**
 * Welcome to Pebble.js!
 *
 * This is where you write your app.
 */
var Accel = require('ui/accel');
var UI = require('ui');
var Vector2 = require('vector2');
var steps = 0;
var runners = [
    {
      title:"Zombie",
      subtitle:'slow and easy',
      icon: 'images/photo.png'
    },
    {
      title:"Werewolf",
      subtitle:'nice and steady',
      icon: 'images/photo.png'
    },
    {
     title:"Vampire",
      subtitle:'fast and hard',
      icon: 'images/photo.png'
    }
  ];

var main = new UI.Card({
  title: 'Monster Track',
  icon: 'images/photo.png',
  subtitle: 'Press Up to Run!',
  body:  'Team Dont Byte Me'
});

main.show();

main.on('click', 'up', function(e) {
 var runMenu = new UI.Menu({
    sections:[{
      title: 'Pick Your Run',
      items: runners
   }]
   });

runMenu.on('select', function(event){
    Accel.init();
    var runWind = new UI.Window();
    var topRect = new UI.Rect({
      position: new Vector2(10,5),
      size: new Vector2(124,30),
      backgroundColor:'black'
      });
    var bgRect = new UI.Rect({
      position: new Vector2(0,0),
      size: new Vector2(144,168),
      backgroundColor:'white'
      });

    runWind.add(bgRect);
    runWind.add(topRect);
     Accel.on('tap', function(e) { //step measuring thing
    console.log('tapevent on axis:', + e.axis + ' and direction: ' + e.direction);
      steps =+ 1;
      var stepsDisplay = new UI.Text({
      position: new Vector2(10,5),
      size: new Vector2(124,20),
      text: steps,
      color: 'white',
      textAlign: 'center'
    });
    console.log('this is steps:' + steps);
       runWind.add(stepsDisplay);
  });

    runWind.show();
    });

  runMenu.show();
});

main.on('click', 'select', function(e) {
  var wind = new UI.Window();
  var textfield = new UI.Text({
    position: new Vector2(0, 50),
    size: new Vector2(144, 30),
    font: 'gothic-24-bold',
    text: 'Text Anywhere!',
    textAlign: 'center'
  });
  wind.add(textfield);
  wind.show();
});

main.on('click', 'down', function(e) {
  var card = new UI.Card();
  card.title('A Card');
  card.subtitle('Is a Window');
  card.body('The simplest window type in Pebble.js.');
  card.show();
});
<commit_msg>Steps update<commit_after>/**
 * Welcome to Pebble.js!
 *
 * This is where you write your app.
 */
var Accel = require('ui/accel');
var UI = require('ui');
var Vector2 = require('vector2');
var steps = 0;
var runners = [
    {
      title:"Zombie",
      subtitle:'slow and easy',
      icon: 'images/photo.png'
    },
    {
      title:"Werewolf",
      subtitle:'nice and steady',
      icon: 'images/photo.png'
    },
    {
     title:"Vampire",
      subtitle:'fast and hard',
      icon: 'images/photo.png'
    }
  ];

var main = new UI.Card({
  title: 'Monster Track',
  icon: 'images/photo.png',
  subtitle: 'Press Up to Run!',
  body:  'Team Dont Byte Me'
});

main.show();

main.on('click', 'up', function(e) {
 var runMenu = new UI.Menu({
    sections:[{
      title: 'Pick Your Run',
      items: runners
   }]
   });

runMenu.on('select', function(event){
    Accel.init();
    //var death = false;
    var didStep = false;
    var runWind = new UI.Window();
    var topRect = new UI.Rect({
      position: new Vector2(10,5),
      size: new Vector2(124,30),
      backgroundColor:'black'
      });
    var bgRect = new UI.Rect({
      position: new Vector2(0,0),
      size: new Vector2(144,168),
      backgroundColor:'white'
      });
    runWind.add(bgRect);
    runWind.add(topRect);

     Accel.on('tap', function(e) { //step measuring thing
    console.log('tapevent on axis:', + e.axis + ' and direction: ' + e.direction);

       var stepsDisplay = new UI.Text({
      position: new Vector2(10,5),
      size: new Vector2(124,20),
      text: steps,
      color: 'white',
      textAlign: 'center'
      });
       runWind.add(stepsDisplay);

       //Step counter display
       if (e.direction > 0){
        didStep = true;
      }else{
        didStep = true;
      }
      if (didStep === true){
        steps += 1;
        didStep = false;
      }

       console.log('steps: '+steps);

    });
    runWind.show();

    });

  runMenu.show();
});

main.on('click', 'select', function(e) {
  var wind = new UI.Window();
  var textfield = new UI.Text({
    position: new Vector2(0, 50),
    size: new Vector2(144, 30),
    font: 'gothic-24-bold',
    text: 'Text Anywhere!',
    textAlign: 'center'
  });
  wind.add(textfield);
  wind.show();
});

main.on('click', 'down', function(e) {
  var card = new UI.Card();
  card.title('A Card');
  card.subtitle('Is a Window');
  card.body('The simplest window type in Pebble.js.');
  card.show();
});
<|endoftext|>


<commit_before><commit_msg>Update project covjson-reader to 0.3.3<commit_after><|endoftext|>


<commit_before>import {promises as jsonld} from 'jsonld'
import urltemplate from 'url-template'

const PartialCollectionView = 'PartialCollectionView'
const IriTemplate = 'IriTemplate'

const COVAPI_NS = 'http://coverageapi.org/ns#'
const COVAPI_API = COVAPI_NS + 'api'
const CanInclude = COVAPI_NS + 'canInclude'

const COVJSON_NS = 'http://coveragejson.org/def#'
const Domain = COVJSON_NS + 'Domain'
const Range = COVJSON_NS + 'Range'

const OSGEO_NS = 'http://a9.com/-/opensearch/extensions/geo/1.0/'
const OSTIME_NS = 'http://a9.com/-/opensearch/extensions/time/1.0/'

const URL_PROPS = {
    filterBbox: OSGEO_NS + 'box',
    filterTimeStart: OSTIME_NS + 'start',
    filterTimeEnd: OSTIME_NS + 'end',
    filterVerticalStart: COVAPI_NS + 'verticalStart',
    filterVerticalEnd: COVAPI_NS + 'verticalEnd',
    subsetBbox: COVAPI_NS + 'subsetBbox',
    subsetTimeStart: COVAPI_NS + 'subsetTimeStart',
    subsetTimeEnd: COVAPI_NS + 'subsetTimeEnd',
    subsetVerticalStart: COVAPI_NS + 'subsetVerticalStart',
    subsetVerticalEnd: COVAPI_NS + 'subsetVerticalEnd',
    subsetVerticalTarget: COVAPI_NS + 'subsetVerticalTarget',
    subsetIndex: COVAPI_NS + 'subsetIndex'
}

const FRAME_CONTEXT = [
   // partial copy of http://www.hydra-cg.com/spec/latest/core/core.jsonld
   {
     "hydra": "http://www.w3.org/ns/hydra/core#",
     "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
     "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
     "xsd": "http://www.w3.org/2001/XMLSchema#",
     "owl": "http://www.w3.org/2002/07/owl#",
     "vs": "http://www.w3.org/2003/06/sw-vocab-status/ns#",
     "dc": "http://purl.org/dc/terms/",
     "cc": "http://creativecommons.org/ns#",
     "property": { "@id": "hydra:property", "@type": "@vocab" },
     "required": "hydra:required",
     "view": { "@id": "hydra:view", "@type": "@id" },
     "PartialCollectionView": "hydra:PartialCollectionView",
     "totalItems": "hydra:totalItems",
     "first": { "@id": "hydra:first", "@type": "@id" },
     "last": { "@id": "hydra:last", "@type": "@id" },
     "next": { "@id": "hydra:next", "@type": "@id" },
     "previous": { "@id": "hydra:previous", "@type": "@id" },
     "IriTemplate": "hydra:IriTemplate",
     "template": "hydra:template",
     "mapping": "hydra:mapping",
     "IriTemplateMapping": "hydra:IriTemplateMapping",
     "variable": "hydra:variable"
   },
   {
     'id': '@id',
     'type': '@type',
     // Hydra has "@type": "@vocab" which confuses the compaction -> we override it as workaround
     // see https://github.com/json-ld/json-ld.org/issues/400
     // we also want the full object form anyway, which we can force by omitting "@type"
     "property": { "@id": "hydra:property" },
     'api': COVAPI_API
     }
   ]

/**
 * Extracts API information from the given Coverage/CoverageCollection object
 * and returns an API object.
 */
export function discover (cov) {
  // Our main source of API information comes from data within the .ld property.
  // To query that we need the id of the coverage or coveragecollection.
  if (!cov.id) {
    return Promise.resolve(new API())
  }
  return jsonld.frame(cov.ld, {
    '@context': FRAME_CONTEXT,
    id: cov.id
  })
  .then(framed => jsonld.compact(framed, framed['@context']))
  .then(compacted => new API(compacted))
}

export class API {
  /**
   * @param ld A framed and compacted JSON-LD document from which Hydra data can be read.
   */
  constructor (ld) {
    this.supportedUrlProps = new Map()

    if (!ld) return
    console.log(ld)

    if (ld.view && ld.view.type === PartialCollectionView) {
      this.isPaged = true
      this.paging = ld.view
      this.paging.total = ld.totalItems

      console.log(ld.view)
    }

    if (ld.api && ld.api.type === IriTemplate) {
      this.hasUrlTemplate = true
      this.urlTemplate = ld.api
      console.log('URL template: ' + ld.api.template)

      let mappings = ld.api.mapping
      for (let mapping of mappings) {
        let propId = mapping.property.id
        for (let prop in URL_PROPS) {
          if (URL_PROPS[prop] === propId) {
            console.log('property recognized: ' + propId + ' (variable: ' + mapping.variable + ')')
            this.supportedUrlProps.set(propId, mapping.variable)
          }
        }
      }

      console.log(ld.api)
    }

    if (ld[CanInclude]) {
      // server supports optional inclusion via Prefer header
      this.supportsPreferHeaders = true
    }

    this._createCapabilities()
  }

  get supportsBboxFiltering () {
    return this.supportedUrlProps.has(URL_PROPS.filterBbox)
  }

  get supportsBboxSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetBbox)
  }

  get supportsTimeFiltering () {
    return this.supportedUrlProps.has(URL_PROPS.filterTimeStart) &&
           this.supportedUrlProps.has(URL_PROPS.filterTimeEnd)
  }

  get supportsTimeSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetTimeStart) &&
           this.supportedUrlProps.has(URL_PROPS.subsetTimeEnd)
  }

  get supportsVerticalFiltering () {
    return this.supportedUrlProps.has(URL_PROPS.filterVerticalStart) &&
           this.supportedUrlProps.has(URL_PROPS.filterVerticalEnd)
  }

  get supportsVerticalSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetVerticalStart) &&
           this.supportedUrlProps.has(URL_PROPS.subsetVerticalEnd)
  }

  get supportsVerticalTargetSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetVerticalTarget)
  }

  get supportsIndexSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetIndex)
  }

  _createCapabilities () {
    let caps = {
      filter: {},
      subset: {}
    }
    let startstop = () => ({
      start: true,
      stop: true
    })
    if (this.supportsBboxFiltering) {
      // 'x' is not the axis name, it just represents the x-axis in a horizontal CRS
      caps.filter.x = {
        start: true,
        stop: true,
        dependency: ['y']
      }
      caps.filter.y = {
        start: true,
        stop: true,
        dependency: ['x']
      }
    }
    if (this.supportsTimeFiltering) {
      caps.filter.time = startstop()
    }
    if (this.supportsVerticalFiltering) {
      caps.filter.vertical = startstop()
    }
    if (this.supportsBboxSubsetting) {
      caps.subset.x = {
        start: true,
        stop: true,
        dependency: ['y']
      }
      caps.subset.y = {
        start: true,
        stop: true,
        dependency: ['x']
      }
    }
    if (this.supportsTimeSubsetting) {
      caps.subset.time = startstop()
    }
    if (this.supportsVerticalSubsetting) {
      caps.subset.vertical = startstop()
    }
    if (this.supportsVerticalTargetSubsetting) {
      if (!caps.subset.vertical) {
        caps.subset.vertical = {}
      }
      caps.subset.vertical.target = true
    }
    if (this.supportsIndexSubsetting) {
      caps.subset.index = {
        start: true,
        stop: true,
        step: true
      }
    }
    if (this.supportsPreferHeaders) {
      caps.embed = {
        domain: true,
        range: true
      }
    }
    this.capabilities = caps
  }

  /**
   * Option keys: time, x, y, vertical, embed
   *
   * Each value except for 'embed' is one of (check this.capabilities to see which ones are supported!):
   *
   * {start, stop} // intersect match
   *
   * 'embed' is an object {domain: true, range: true} where both members are optional.
   */
  _getFilterTemplateVars (options = {}) {
    let templateVars = {}
    if (options.time) {
      if (!this.supportsTimeFiltering) {
        throw new Error('Time filtering not supported!')
      }
      let isoStart = options.time.start
      let isoEnd = options.time.stop
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterTimeStart)] = isoStart
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterTimeEnd)] = isoEnd
      delete options.time
    }
    if (options.vertical) {
      if (!this.supportsVerticalFiltering) {
        throw new Error('Vertical filtering not supported!')
      }
      let start = getNumberString(options.vertical.start)
      let end = getNumberString(options.vertical.stop)
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterVerticalStart)] = start
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterVerticalEnd)] = end
      delete options.vertical
    }
    if (options.x) {
      if (!this.supportsBboxFiltering) {
        throw new Error('BBOX filtering not supported!')
      }
      let bboxStr = getBboxString([options.x.start, options.y.start, options.x.stop, options.y.stop])
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterBbox)] = bboxStr
      delete options.x
      delete options.y
    }
    checkEmpty(options, 'Unrecognized filter options')

    return templateVars
  }

  /**
   * Option keys: time, x, y, vertical, index
   *
   * Each value is one of (check this.capabilities to see which ones are supported!):
   *
   * For time, x, y, vertical:
   * ISO string // exact match (time)
   * number // exact match (x, y, vertical) <- typically not supported by API
   * {start, stop} // intersect match
   * {target} // nearest neighbor match
   *
   * For index:
   * {<axisName>: integer, ...}
   * {<axisName>: {start,stop[,step]}, ...}
   */
  _getSubsetTemplateVars (options = {}) {
    let templateVars = {}
    if (options.time) {
      if (!this.supportsTimeSubsetting) {
        throw new Error('Time subsetting not supported!')
      }
      let isoStart = options.time.start
      let isoEnd = options.time.stop
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetTimeStart)] = isoStart
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetTimeEnd)] = isoEnd
      delete options.time
    }
    if (options.x) {
      if (!this.supportsBboxSubsetting) {
        throw new Error('BBOX subsetting not supported!')
      }
      let bboxStr = getBboxString([options.x.start, options.y.start, options.x.stop, options.y.stop])
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetBbox)] = bboxStr
      delete options.x
      delete options.y
    }
    if (options.vertical) {
      if (options.vertical.target) {
        if (!this.supportsVerticalTargetSubsetting) {
          throw new Error('vertical target subsetting not supported!')
        }
        let target = getNumberString(options.vertical.target)
        templateVars[this.supportedUrlProps.get(URL_PROPS.subsetVerticalTarget)] = target
      }
      if (options.vertical.start) {
        if (!this.supportsVerticalSubsetting) {
          throw new Error('vertical subsetting not supported!')
        }
        let start = getNumberString(options.vertical.start)
        let end = getNumberString(options.vertical.stop)
        templateVars[this.supportedUrlProps.get(URL_PROPS.subsetVerticalStart)] = start
        templateVars[this.supportedUrlProps.get(URL_PROPS.subsetVerticalEnd)] = end
      }
      delete options.vertical
    }
    if (options.index) {
      if (!this.supportsIndexSubsetting) {
        throw new Error('index subsetting not supported!')
      }
      let strings = []
      for (let axis of Object.keys(options.index)) {
        strings.push(getIndexSubsetString(axis, options.index[axis]))
      }
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetIndex)] = strings
    }
    checkEmpty(options, 'Unrecognized subset options')

    return templateVars
  }

  _getIncludeDomainAndRangeHeaders (options = {}) {
    if (!this.supportsPreferHeaders) {
      return {}
    }
    let uris = []
    if (options.domain) {
      uris.push(Domain)
    }
    if (options.range) {
      uris.push(Range)
    }
    return {
      Prefer: 'return=representation; ' +
              'include="' + uris.join(' ') + '"'
    }
  }

  getUrlAndHeaders (options) {
    let subsetTemplateVars = this._getSubsetTemplateVars(options.subset)
    let filterTemplateVars = this._getFilterTemplateVars(options.filter)

    let templateVars = subsetTemplateVars
    for (let key in filterTemplateVars) {
      templateVars[key] = filterTemplateVars[key]
    }

    let url = urltemplate.parse(this.urlTemplate.template).expand(templateVars)
    let headers = this._getIncludeDomainAndRangeHeaders(options.embed)
    return {url, headers}
  }

}

function checkEmpty (obj, err) {
  if (Object.keys(obj).length > 0) {
    throw new Error(err)
  }
}

function getBboxString (bbox) {
  return bbox.map(getNumberString).join(',')
}

/**
 * Converts a number to a decimal string in non-scientific notation.
 */
function getNumberString (num) {
  // try toString() to avoid trailing zeros from toFixed()
  let str = num.toString()
  // if this resulted in scientific notation, use toFixed() instead
  if (str.indexOf('e') !== -1) {
    str = num.toFixed(20)
  }
  return str
}

function getIndexSubsetString (axis, spec) {
  let slice
  if (typeof spec === 'number') {
    slice = getNumberString(spec)
  } else if (spec.start === spec.stop && (!spec.step || spec.step === 1)) {
    slice = getNumberString(spec.start)
  } else {
    slice = getNumberString(spec.start) + ':' + getNumberString(stop)
    if (spec.step) {
      slice += ':' + getNumberString(spec.step)
    }
  }
  return axis + '[' + slice + ']'
}

<commit_msg>bugfix<commit_after>import {promises as jsonld} from 'jsonld'
import urltemplate from 'url-template'

const PartialCollectionView = 'PartialCollectionView'
const IriTemplate = 'IriTemplate'

const COVAPI_NS = 'http://coverageapi.org/ns#'
const COVAPI_API = COVAPI_NS + 'api'
const CanInclude = COVAPI_NS + 'canInclude'

const COVJSON_NS = 'http://coveragejson.org/def#'
const Domain = COVJSON_NS + 'Domain'
const Range = COVJSON_NS + 'Range'

const OSGEO_NS = 'http://a9.com/-/opensearch/extensions/geo/1.0/'
const OSTIME_NS = 'http://a9.com/-/opensearch/extensions/time/1.0/'

const URL_PROPS = {
    filterBbox: OSGEO_NS + 'box',
    filterTimeStart: OSTIME_NS + 'start',
    filterTimeEnd: OSTIME_NS + 'end',
    filterVerticalStart: COVAPI_NS + 'verticalStart',
    filterVerticalEnd: COVAPI_NS + 'verticalEnd',
    subsetBbox: COVAPI_NS + 'subsetBbox',
    subsetTimeStart: COVAPI_NS + 'subsetTimeStart',
    subsetTimeEnd: COVAPI_NS + 'subsetTimeEnd',
    subsetVerticalStart: COVAPI_NS + 'subsetVerticalStart',
    subsetVerticalEnd: COVAPI_NS + 'subsetVerticalEnd',
    subsetVerticalTarget: COVAPI_NS + 'subsetVerticalTarget',
    subsetIndex: COVAPI_NS + 'subsetIndex'
}

const FRAME_CONTEXT = [
   // partial copy of http://www.hydra-cg.com/spec/latest/core/core.jsonld
   {
     "hydra": "http://www.w3.org/ns/hydra/core#",
     "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
     "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
     "xsd": "http://www.w3.org/2001/XMLSchema#",
     "owl": "http://www.w3.org/2002/07/owl#",
     "vs": "http://www.w3.org/2003/06/sw-vocab-status/ns#",
     "dc": "http://purl.org/dc/terms/",
     "cc": "http://creativecommons.org/ns#",
     "property": { "@id": "hydra:property", "@type": "@vocab" },
     "required": "hydra:required",
     "view": { "@id": "hydra:view", "@type": "@id" },
     "PartialCollectionView": "hydra:PartialCollectionView",
     "totalItems": "hydra:totalItems",
     "first": { "@id": "hydra:first", "@type": "@id" },
     "last": { "@id": "hydra:last", "@type": "@id" },
     "next": { "@id": "hydra:next", "@type": "@id" },
     "previous": { "@id": "hydra:previous", "@type": "@id" },
     "IriTemplate": "hydra:IriTemplate",
     "template": "hydra:template",
     "mapping": "hydra:mapping",
     "IriTemplateMapping": "hydra:IriTemplateMapping",
     "variable": "hydra:variable"
   },
   {
     'id': '@id',
     'type': '@type',
     // Hydra has "@type": "@vocab" which confuses the compaction -> we override it as workaround
     // see https://github.com/json-ld/json-ld.org/issues/400
     // we also want the full object form anyway, which we can force by omitting "@type"
     "property": { "@id": "hydra:property" },
     'api': COVAPI_API
     }
   ]

/**
 * Extracts API information from the given Coverage/CoverageCollection object
 * and returns an API object.
 */
export function discover (cov) {
  // Our main source of API information comes from data within the .ld property.
  // To query that we need the id of the coverage or coveragecollection.
  if (!cov.id) {
    return Promise.resolve(new API())
  }
  return jsonld.frame(cov.ld, {
    '@context': FRAME_CONTEXT,
    id: cov.id
  })
  .then(framed => jsonld.compact(framed, framed['@context']))
  .then(compacted => new API(compacted))
}

export class API {
  /**
   * @param ld A framed and compacted JSON-LD document from which Hydra data can be read.
   */
  constructor (ld) {
    this.supportedUrlProps = new Map()

    if (!ld) return
    console.log(ld)

    if (ld.view && ld.view.type === PartialCollectionView) {
      this.isPaged = true
      this.paging = ld.view
      this.paging.total = ld.totalItems

      console.log(ld.view)
    }

    if (ld.api && ld.api.type === IriTemplate) {
      this.hasUrlTemplate = true
      this.urlTemplate = ld.api
      console.log('URL template: ' + ld.api.template)

      let mappings = ld.api.mapping
      for (let mapping of mappings) {
        let propId = mapping.property.id
        for (let prop in URL_PROPS) {
          if (URL_PROPS[prop] === propId) {
            console.log('property recognized: ' + propId + ' (variable: ' + mapping.variable + ')')
            this.supportedUrlProps.set(propId, mapping.variable)
          }
        }
      }

      console.log(ld.api)
    }

    if (ld[CanInclude]) {
      // server supports optional inclusion via Prefer header
      this.supportsPreferHeaders = true
    }

    this._createCapabilities()
  }

  get supportsBboxFiltering () {
    return this.supportedUrlProps.has(URL_PROPS.filterBbox)
  }

  get supportsBboxSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetBbox)
  }

  get supportsTimeFiltering () {
    return this.supportedUrlProps.has(URL_PROPS.filterTimeStart) &&
           this.supportedUrlProps.has(URL_PROPS.filterTimeEnd)
  }

  get supportsTimeSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetTimeStart) &&
           this.supportedUrlProps.has(URL_PROPS.subsetTimeEnd)
  }

  get supportsVerticalFiltering () {
    return this.supportedUrlProps.has(URL_PROPS.filterVerticalStart) &&
           this.supportedUrlProps.has(URL_PROPS.filterVerticalEnd)
  }

  get supportsVerticalSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetVerticalStart) &&
           this.supportedUrlProps.has(URL_PROPS.subsetVerticalEnd)
  }

  get supportsVerticalTargetSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetVerticalTarget)
  }

  get supportsIndexSubsetting () {
    return this.supportedUrlProps.has(URL_PROPS.subsetIndex)
  }

  _createCapabilities () {
    let caps = {
      filter: {},
      subset: {},
      embed: {}
    }
    let startstop = () => ({
      start: true,
      stop: true
    })
    if (this.supportsBboxFiltering) {
      // 'x' is not the axis name, it just represents the x-axis in a horizontal CRS
      caps.filter.x = {
        start: true,
        stop: true,
        dependency: ['y']
      }
      caps.filter.y = {
        start: true,
        stop: true,
        dependency: ['x']
      }
    }
    if (this.supportsTimeFiltering) {
      caps.filter.time = startstop()
    }
    if (this.supportsVerticalFiltering) {
      caps.filter.vertical = startstop()
    }
    if (this.supportsBboxSubsetting) {
      caps.subset.x = {
        start: true,
        stop: true,
        dependency: ['y']
      }
      caps.subset.y = {
        start: true,
        stop: true,
        dependency: ['x']
      }
    }
    if (this.supportsTimeSubsetting) {
      caps.subset.time = startstop()
    }
    if (this.supportsVerticalSubsetting) {
      caps.subset.vertical = startstop()
    }
    if (this.supportsVerticalTargetSubsetting) {
      if (!caps.subset.vertical) {
        caps.subset.vertical = {}
      }
      caps.subset.vertical.target = true
    }
    if (this.supportsIndexSubsetting) {
      caps.subset.index = {
        start: true,
        stop: true,
        step: true
      }
    }
    if (this.supportsPreferHeaders) {
      caps.embed = {
        domain: true,
        range: true
      }
    }
    this.capabilities = caps
  }

  /**
   * Option keys: time, x, y, vertical, embed
   *
   * Each value except for 'embed' is one of (check this.capabilities to see which ones are supported!):
   *
   * {start, stop} // intersect match
   *
   * 'embed' is an object {domain: true, range: true} where both members are optional.
   */
  _getFilterTemplateVars (options = {}) {
    let templateVars = {}
    if (options.time) {
      if (!this.supportsTimeFiltering) {
        throw new Error('Time filtering not supported!')
      }
      let isoStart = options.time.start
      let isoEnd = options.time.stop
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterTimeStart)] = isoStart
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterTimeEnd)] = isoEnd
      delete options.time
    }
    if (options.vertical) {
      if (!this.supportsVerticalFiltering) {
        throw new Error('Vertical filtering not supported!')
      }
      let start = getNumberString(options.vertical.start)
      let end = getNumberString(options.vertical.stop)
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterVerticalStart)] = start
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterVerticalEnd)] = end
      delete options.vertical
    }
    if (options.x) {
      if (!this.supportsBboxFiltering) {
        throw new Error('BBOX filtering not supported!')
      }
      let bboxStr = getBboxString([options.x.start, options.y.start, options.x.stop, options.y.stop])
      templateVars[this.supportedUrlProps.get(URL_PROPS.filterBbox)] = bboxStr
      delete options.x
      delete options.y
    }
    checkEmpty(options, 'Unrecognized filter options')

    return templateVars
  }

  /**
   * Option keys: time, x, y, vertical, index
   *
   * Each value is one of (check this.capabilities to see which ones are supported!):
   *
   * For time, x, y, vertical:
   * ISO string // exact match (time)
   * number // exact match (x, y, vertical) <- typically not supported by API
   * {start, stop} // intersect match
   * {target} // nearest neighbor match
   *
   * For index:
   * {<axisName>: integer, ...}
   * {<axisName>: {start,stop[,step]}, ...}
   */
  _getSubsetTemplateVars (options = {}) {
    let templateVars = {}
    if (options.time) {
      if (!this.supportsTimeSubsetting) {
        throw new Error('Time subsetting not supported!')
      }
      let isoStart = options.time.start
      let isoEnd = options.time.stop
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetTimeStart)] = isoStart
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetTimeEnd)] = isoEnd
      delete options.time
    }
    if (options.x) {
      if (!this.supportsBboxSubsetting) {
        throw new Error('BBOX subsetting not supported!')
      }
      let bboxStr = getBboxString([options.x.start, options.y.start, options.x.stop, options.y.stop])
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetBbox)] = bboxStr
      delete options.x
      delete options.y
    }
    if (options.vertical) {
      if (options.vertical.target) {
        if (!this.supportsVerticalTargetSubsetting) {
          throw new Error('vertical target subsetting not supported!')
        }
        let target = getNumberString(options.vertical.target)
        templateVars[this.supportedUrlProps.get(URL_PROPS.subsetVerticalTarget)] = target
      }
      if (options.vertical.start) {
        if (!this.supportsVerticalSubsetting) {
          throw new Error('vertical subsetting not supported!')
        }
        let start = getNumberString(options.vertical.start)
        let end = getNumberString(options.vertical.stop)
        templateVars[this.supportedUrlProps.get(URL_PROPS.subsetVerticalStart)] = start
        templateVars[this.supportedUrlProps.get(URL_PROPS.subsetVerticalEnd)] = end
      }
      delete options.vertical
    }
    if (options.index) {
      if (!this.supportsIndexSubsetting) {
        throw new Error('index subsetting not supported!')
      }
      let strings = []
      for (let axis of Object.keys(options.index)) {
        strings.push(getIndexSubsetString(axis, options.index[axis]))
      }
      templateVars[this.supportedUrlProps.get(URL_PROPS.subsetIndex)] = strings
    }
    checkEmpty(options, 'Unrecognized subset options')

    return templateVars
  }

  _getIncludeDomainAndRangeHeaders (options = {}) {
    if (!this.supportsPreferHeaders) {
      return {}
    }
    let uris = []
    if (options.domain) {
      uris.push(Domain)
    }
    if (options.range) {
      uris.push(Range)
    }
    return {
      Prefer: 'return=representation; ' +
              'include="' + uris.join(' ') + '"'
    }
  }

  getUrlAndHeaders (options) {
    let subsetTemplateVars = this._getSubsetTemplateVars(options.subset)
    let filterTemplateVars = this._getFilterTemplateVars(options.filter)

    let templateVars = subsetTemplateVars
    for (let key in filterTemplateVars) {
      templateVars[key] = filterTemplateVars[key]
    }

    let url = urltemplate.parse(this.urlTemplate.template).expand(templateVars)
    let headers = this._getIncludeDomainAndRangeHeaders(options.embed)
    return {url, headers}
  }

}

function checkEmpty (obj, err) {
  if (Object.keys(obj).length > 0) {
    throw new Error(err)
  }
}

function getBboxString (bbox) {
  return bbox.map(getNumberString).join(',')
}

/**
 * Converts a number to a decimal string in non-scientific notation.
 */
function getNumberString (num) {
  // try toString() to avoid trailing zeros from toFixed()
  let str = num.toString()
  // if this resulted in scientific notation, use toFixed() instead
  if (str.indexOf('e') !== -1) {
    str = num.toFixed(20)
  }
  return str
}

function getIndexSubsetString (axis, spec) {
  let slice
  if (typeof spec === 'number') {
    slice = getNumberString(spec)
  } else if (spec.start === spec.stop && (!spec.step || spec.step === 1)) {
    slice = getNumberString(spec.start)
  } else {
    slice = getNumberString(spec.start) + ':' + getNumberString(stop)
    if (spec.step) {
      slice += ':' + getNumberString(spec.step)
    }
  }
  return axis + '[' + slice + ']'
}

<|endoftext|>


<commit_before>import Vue from 'vue';
import VueRouter from 'vue-router';
import VueBreadcrumbs from 'vue-2-breadcrumbs';

Vue.use(VueRouter);
Vue.use(VueBreadcrumbs);

const Feeds = {template: '
<router-view/>
'};
const Feed = {template: '

Feed

'};
const Biz = {template: '

Biz

'};
const Foo = {template: '

Foo

'};
const Bar = {template: '

Bar

'};

const router = new VueRouter({
    routes: [
        {path: '/', redirect: '/feeds'},
        {
            path: '/feeds',
            component: Feeds,
            meta: {
                breadcrumb: 'Feeds'
            },
            children: [
                {
                    path: '',
                    component: Biz
                },
                {
                    path: 'foo',
                    component: Foo,
                    meta: {
                        breadcrumb: () => `foo ${1 + 1}`
                    }
                },
                {
                    path: 'bar',
                    component: Bar,
                    meta: {
                        breadcrumb: 'bar'
                    }
                },
                {
                    path: ':id',
                    component: Feed,
                    meta: {
                        breadcrumb: (routeParams) => `Other Feed ${routeParams.id}`
                    }
                }
            ]
        }
    ]
});

new Vue({
    router,
    template: `

                    <router-link to="/feeds" class="nav-link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Feeds</router-link>

                        <router-link to="/feeds/foo" class="dropdown-item">Foo</router-link>
                        <router-link to="/feeds/bar" class="dropdown-item">Bar</router-link>
                        <router-link to="/feeds/1" class="dropdown-item">Other Feed 1</router-link>
                        <router-link to="/feeds/2" class="dropdown-item">Other Feed 2</router-link>
                        <router-link to="/feeds/3" class="dropdown-item">Other Feed 3</router-link>

            <breadcrumbs/>
            <router-view/>

    `
}).$mount('#app');
<commit_msg>fix: feeds content<commit_after>import Vue from 'vue';
import VueRouter from 'vue-router';
import VueBreadcrumbs from 'vue-2-breadcrumbs';

Vue.use(VueRouter);
Vue.use(VueBreadcrumbs);

const Feeds = {template: '
<router-view/>
'};
const Feed = {template: '

Feed

'};
const Biz = {template: '

Feeds

'};
const Foo = {template: '

Foo

'};
const Bar = {template: '

Bar

'};

const router = new VueRouter({
    routes: [
        {path: '/', redirect: '/feeds'},
        {
            path: '/feeds',
            component: Feeds,
            meta: {
                breadcrumb: 'Feeds'
            },
            children: [
                {
                    path: '',
                    component: Biz
                },
                {
                    path: 'foo',
                    component: Foo,
                    meta: {
                        breadcrumb: () => `foo ${1 + 1}`
                    }
                },
                {
                    path: 'bar',
                    component: Bar,
                    meta: {
                        breadcrumb: 'bar'
                    }
                },
                {
                    path: ':id',
                    component: Feed,
                    meta: {
                        breadcrumb: (routeParams) => `Other Feed ${routeParams.id}`
                    }
                }
            ]
        }
    ]
});

new Vue({
    router,
    template: `

                    <router-link to="/feeds" class="nav-link dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Feeds</router-link>

                        <router-link to="/feeds/foo" class="dropdown-item">Foo</router-link>
                        <router-link to="/feeds/bar" class="dropdown-item">Bar</router-link>
                        <router-link to="/feeds/1" class="dropdown-item">Other Feed 1</router-link>
                        <router-link to="/feeds/2" class="dropdown-item">Other Feed 2</router-link>
                        <router-link to="/feeds/3" class="dropdown-item">Other Feed 3</router-link>

            <breadcrumbs/>
            <router-view/>

    `
}).$mount('#app');
<|endoftext|>


<commit_before>document.getElementById("id_logic_level_version").innerHTML = "Business level version: 2017.11.29.3";
//window.addEventListener('deviceorientation', ondeviceorientation);
window.addEventListener('devicemotion', ondevicemotion);

var gamma =0;
var beta = 0;

setInterval(deseneaza_cerc_canvas, 40);

//----------------------------------------
function deseneaza_cerc_canvas()
{
	var canvas = document.getElementById("id_canvas");
	var context = canvas.getContext("2d");

	var w = canvas.getAttribute("width");
	var h = canvas.getAttribute("height");

	context.clearRect(0, 0, w, h);

	context.rect(0, 0, w, h);
	context.stroke();

	context.beginPath();

	var centru = {x : w / 2, y : h / 2};
	var raza = 10;
	var max_deplasare_x = w / 2 - raza;
	var max_deplasare_y = h / 2 - raza;
 // gamma == 0 -> centru.x
 // gamma == -90 -> 0 + raza
 // gamma == 90 -> w - raza
	context.arc(centru.x + gamma / 90 * max_deplasare_x, centru.y + beta / 90 * max_deplasare_y, raza, 0, 2 * Math.PI);

	context.stroke();
}
//----------------------------------------
function deseneaza_patrat_canvas(alpha, gamma, beta)
{
	var canvas = document.getElementById("id_canvas");
	var context = canvas.getContext("2d");

	context.resetTransform();
	context.clearRect(0, 0, w, h);

	var w = canvas.getAttribute("width");
	var h = canvas.getAttribute("height");

	var centru = {x : w / 2, y : h / 2};
	var latura = 10;
	var max_deplasare_x = w / 2 - latura / 2;
	var max_deplasare_y = h / 2 - latura / 2;

	var centru_patrat = {x: centru.x + gamma / 90 * max_deplasare_x, y : centru.y + beta / 90 * max_deplasare_y};

	context.translate(centru_patrat.x, centru_patrat.y);
	context.rotate(alpha / 180 * Math.PI);
 // gamma == 0 -> centru.x
 // gamma == -90 -> 0 + raza
 // gamma == 90 -> w - raza

	context.beginPath();
	//context.arc(centru.x + gamma / 90 * max_deplasare_x, centru.y + beta / 90 * max_deplasare_y, raza, 0, 2 * Math.PI);
	context.strokeRect(- latura / 2, -latura / 2, latura, latura);
	context.stroke();
}

//----------------------------------------
function deseneaza_cerc_svg(gamma, beta)
{
	var svg = document.getElementById("id_svg");
	var w = svg.getAttribute("width");
	var h = svg.getAttribute("height");

	var cerc = document.getElementById("id_circle");

	var centru = {x : w / 2, y : h / 2};
	var raza = cerc.getAttribute("r");
	var max_deplasare_x = w / 2 - raza;
	var max_deplasare_y = h / 2 - raza;

	cerc.setAttribute("cx", centru.x + gamma / 90 * max_deplasare_x);
	cerc.setAttribute("cy", centru.y + beta / 90 * max_deplasare_y);
}
//----------------------------------------

function ondeviceorientation(event)
{
	var alpha = event.alpha;
	var beta = event.beta;
	var gamma = event.gamma;

	document.getElementById("id_alpha").innerHTML = "alpha = " + Math.round(alpha * 10) / 10;
	document.getElementById("id_beta").innerHTML = "beta = " + Math.round(beta * 10) / 10;
	document.getElementById("id_gamma").innerHTML = "gamma = " + Math.round(gamma * 10) / 10;

	//deseneaza_cerc_canvas(gamma, beta);
	// deseneaza_cerc_svg(gamma, beta);
	//deseneaza_patrat_canvas(alpha, gamma, beta);
}
//----------------------------------------
function ondevicemotion(event)
{
	document.getElementById("id_acc").innerHTML = "Acc = " + Math.round(event.acceleration.x * 10) / 10 + " " + Math.round(event.acceleration.y * 10) / 10 + " " + Math.round(event.acceleration.z * 10) / 10;

	var ag = event.accelerationIncludingGravity;
	 gamma = -Math.atan(ag.x / ag.z) * 180 / Math.PI;
	 beta = Math.atan(ag.y / ag.z) * 180 / Math.PI;

	//document.getElementById("id_acc_g").innerHTML = "AccG = " + Math.round(ag.x * 10) / 10 + " " + Math.round(ag.y * 10) / 10 + " " + Math.round(ag.z * 10) / 10 + " gamma = " + Math.round(gamma * 10) / 10 + " beta = " + Math.round(beta * 10) / 10;
	//deseneaza_cerc_canvas(gamma, beta);
}
//----------------------------------------<commit_msg>Timer1<commit_after>document.getElementById("id_logic_level_version").innerHTML = "Business level version: 2017.11.29.2";
//window.addEventListener('deviceorientation', ondeviceorientation);
window.addEventListener('devicemotion', ondevicemotion);

var gamma = 0;
var beta = 0;

setInterval(deseneaza_cerc_canvas, 40);

//----------------------------------------
function deseneaza_cerc_canvas()
{
	var canvas = document.getElementById("id_canvas");
	var context = canvas.getContext("2d");

	var w = canvas.getAttribute("width");
	var h = canvas.getAttribute("height");

	context.clearRect(0, 0, w, h);

	context.rect(0, 0, w, h);
	context.stroke();

	context.beginPath();

	var centru = {x : w / 2, y : h / 2};
	var raza = 10;
	var max_deplasare_x = w / 2 - raza;
	var max_deplasare_y = h / 2 - raza;
 // gamma == 0 -> centru.x
 // gamma == -90 -> 0 + raza
 // gamma == 90 -> w - raza
	context.arc(centru.x + gamma / 90 * max_deplasare_x, centru.y + beta / 90 * max_deplasare_y, raza, 0, 2 * Math.PI);

	context.stroke();
}
//----------------------------------------
function deseneaza_cerc_svg(gamma, beta)
{
	var svg = document.getElementById("id_svg");
	var w = svg.getAttribute("width");
	var h = svg.getAttribute("height");

	var cerc = document.getElementById("id_circle");

	var centru = {x : w / 2, y : h / 2};
	var raza = cerc.getAttribute("r");
	var max_deplasare_x = w / 2 - raza;
	var max_deplasare_y = h / 2 - raza;

	cerc.setAttribute("cx", centru.x + gamma / 90 * max_deplasare_x);
	cerc.setAttribute("cy", centru.y + beta / 90 * max_deplasare_y);
}
//----------------------------------------
function deseneaza_patrat_canvas(alpha, gamma, beta)
{
	var canvas = document.getElementById("id_canvas");
	var context = canvas.getContext("2d");

	context.resetTransform();
	context.clearRect(0, 0, w, h);

	var w = canvas.getAttribute("width");
	var h = canvas.getAttribute("height");

	var centru = {x : w / 2, y : h / 2};
	var latura = 10;
	var max_deplasare_x = w / 2 - latura / 2;
	var max_deplasare_y = h / 2 - latura / 2;

	var centru_patrat = {x: centru.x + gamma / 90 * max_deplasare_x, y : centru.y + beta / 90 * max_deplasare_y};

	context.translate(centru_patrat.x, centru_patrat.y);
	context.rotate(alpha / 180 * Math.PI);
 // gamma == 0 -> centru.x
 // gamma == -90 -> 0 + raza
 // gamma == 90 -> w - raza

	context.beginPath();
	//context.arc(centru.x + gamma / 90 * max_deplasare_x, centru.y + beta / 90 * max_deplasare_y, raza, 0, 2 * Math.PI);
	context.strokeRect(- latura / 2, -latura / 2, latura, latura);
	context.stroke();
}
//----------------------------------------
function ondeviceorientation(event)
{
	var alpha = event.alpha;
	var beta = event.beta;
	var gamma = event.gamma;

	document.getElementById("id_alpha").innerHTML = "alpha = " + Math.round(alpha * 10) / 10;
	document.getElementById("id_beta").innerHTML = "beta = " + Math.round(beta * 10) / 10;
	document.getElementById("id_gamma").innerHTML = "gamma = " + Math.round(gamma * 10) / 10;

	//deseneaza_cerc_canvas(gamma, beta);
	// deseneaza_cerc_svg(gamma, beta);
	//deseneaza_patrat_canvas(alpha, gamma, beta);
}
//----------------------------------------
function ondevicemotion(event)
{
	document.getElementById("id_acc").innerHTML = "Acc = " + Math.round(event.acceleration.x * 10) / 10 + " " + Math.round(event.acceleration.y * 10) / 10 + " " + Math.round(event.acceleration.z * 10) / 10;

	var ag = event.accelerationIncludingGravity;
	gamma = -Math.atan(ag.x / ag.z) * 180 / Math.PI;
	beta = Math.atan(ag.y / ag.z) * 180 / Math.PI;

	//document.getElementById("id_acc_g").innerHTML = "AccG = " + Math.round(ag.x * 10) / 10 + " " + Math.round(ag.y * 10) / 10 + " " + Math.round(ag.z * 10) / 10 + " gamma = " + Math.round(gamma * 10) / 10 + " beta = " + Math.round(beta * 10) / 10;
	//deseneaza_cerc_canvas(gamma, beta);
}
//----------------------------------------<|endoftext|>


<commit_before>var cull = (function (global) {
    "use strict";

    var _ = global._ || require("underscore");
    var slice = Array.prototype.slice;
    var toString = Object.prototype.toString;

    function _assert(pred, msg) {
        if (!pred) { throw new TypeError(msg); }
    }

    function _refute(pred, msg) {
        _assert(!pred, msg);
    }

    function isSeq(seq) {
        return !!seq &&
            typeof seq === "object" &&
            typeof seq.length === "number" &&
            !seq.tagName;
    }

    function toSeq(value) {
        if (toString.call(value) === "[object Array]") { return value; }
        if (isSeq(value)) { return slice.call(value); }
        if (typeof value === "undefined" || value === null) { return []; }
        return slice.call(arguments);
    }

    function doall(fn, seq) {
        var i, l;
        for (i = 0, l = seq.length; i < l; ++i) {
            fn(seq[i], i, seq);
        }
    }

    function isFunction(fn) {
        return typeof fn === "function";
    }

    function reduce(fn, initial, seq) {
        if (arguments.length === 3) {
            return _.reduce(seq, fn, initial);
        }
        return _.reduce(initial, fn);
    }

    function all(fn, seq) {
        var i, l;
        for (i = 0, l = seq.length; i < l; ++i) {
            if (!fn(seq[i])) { return false; }
        }
        return true;
    }

    function some(fn, seq) {
        var i, l;
        for (i = 0, l = seq.length; i < l; ++i) {
            if (fn(seq[i])) { return true; }
        }
        return false;
    }

    function onlySome(fn, seq) {
        var i, l, t, f;
        for (i = 0, l = seq.length; i < l; ++i) {
            if (fn(seq[i])) {
                t = true;
            } else {
                f = true;
            }
            if (t && f) { return true; }
        }
        return false;
    }

    function trim(string) {
        return (string.trim && string.trim()) ||
            string.replace(/^\s+|\s+$/, "");
    }

    function identity(arg) { return arg; }

    function defined(o) { return typeof o !== "undefined" && o !== null; }

    cull = {
        _assert: _assert,
        _refute: _refute,
        trim: trim,
        doall: doall,
        reduce: reduce,
        all: all,
        some: some,
        onlySome: onlySome,
        isFunction: isFunction,
        isSeq: isSeq,
        toSeq: toSeq,
        identity: identity,
        defined: defined
    };

    function unary(fn) {
        return function (arg) {
            return fn.call(this, arg);
        };
    }

    function prop(name) {
        return function (object) {
            return object[name];
        };
    }

    function func(name, args) {
        return function (object) {
            return object[name].apply(object, toSeq(args));
        };
    }

    function eq(one) {
        return function (other) { return one === other; };
    }

    var composeSignature = "compose takes func|[funcs] " +
            "and optional thisp object";

    function compose(funcs, thisp) {
        _refute(isFunction(thisp) || arguments.length > 2, composeSignature);

        var fns = toSeq(funcs);

        _assert(all(isFunction, fns), composeSignature);

        return function () {
            var i = fns.length;
            var result = arguments;
            while (i--) {
                result = [fns[i].apply(thisp || this, result)];
            }
            return result[0];
        };
    }

    function callWith() {
        var args = arguments;
        return function (fn) {
            return fn.apply(this, args);
        };
    }

    function partial(fn) {
        var args = slice.call(arguments, 1);
        return function () {
            return fn.apply(this, args.concat(slice.call(arguments)));
        };
    }

    function bind(obj, methOrProp) {
        var fn = typeof methOrProp === "string" ? obj[methOrProp] : methOrProp;
        var args = slice.call(arguments, 2);
        return function () {
            return fn.apply(obj, args.concat(slice.call(arguments)));
        };
    }

    function handler(handlr, type) {
        if (typeof handlr === "function") { return handlr; }
        _assert(isFunction(handlr[type]),
                "Handler has no method '" + type + "'");
        return bind.apply(null, arguments);
    }

    cull.unary = unary;
    cull.prop = prop;
    cull.func = func;
    cull.eq = eq;
    cull.compose = compose;
    cull.callWith = callWith;
    cull.partial = partial;
    cull.bind = bind;
    cull.handler = handler;
    cull.keys = _.keys;
    cull.values = _.values;

    var switchArgs = function (obj, name) {
        return function (fn, seq) {
            var args = [seq, fn].concat(slice.call(arguments, 2));
            return obj[name].apply(obj, args);
        };
    };

    var flatten = _.flatten;
    var uniq = _.uniq;
    var first = switchArgs(_, "find");
    var select = switchArgs(_, "filter");
    var indexOf = switchArgs(_, "indexOf");
    var difference = _.difference;
    var seldef = partial(select, defined);

    function map(fn, coll) {
        var result = [], i, l;
        for (i = 0, l = coll.length; i < l; i++) {
            result.push(fn(coll[i]));
        }
        return result;
    }

    function negate(pred) {
        return function () {
            return !pred.apply(this, arguments);
        };
    }

    function reject(pred, seq) {
        return select(negate(pred), seq);
    }

    function concat(seq, items) {
        return toSeq(seq).concat(toSeq(items));
    }

    function partition(n, seq) {
        var result = [], i, l;
        for (i = 0, l = seq.length; i < l; i += n) {
            result.push(seq.slice(i, i + n));
        }
        return result;
    }

    function mapdef(fn, coll) {
        return seldef(map(fn, seldef(coll)));
    }

    function mapcat(fn, coll) {
        return reduce(concat, map(fn, coll));
    }

    function interpose(sep, coll) {
        var result = [], i, l;
        for (i = 0, l = coll.length; i < l; i += 1) {
            result.push(coll[i]);
            if (i < l - 1) {
                result.push(sep);
            }
        }
        return result;
    }

    cull.concat = concat;
    cull.flatten = flatten;
    cull.uniq = uniq;
    cull.first = first;
    cull.select = select;
    cull.reject = reject;
    cull.seldef = seldef;
    cull.map = map;
    cull.doall = doall;
    cull.mapdef = mapdef;
    cull.mapcat = mapcat;
    cull.partition = partition;
    cull.difference = difference;
    cull.interpose = interpose;
    cull.indexOf = indexOf;

    // cull.advice

    function after(obj, name, fn) {
        var originalFn = obj[name];
        obj[name] = function () {
            var ret1 = originalFn.apply(this, arguments);
            var ret2 = fn.apply(this, [ret1].concat(slice.call(arguments)));
            return typeof ret2 !== "undefined" ? ret2 : ret1;
        };
    }

    function before(obj, name, fn) {
        var originalFn = obj[name];
        obj[name] = function () {
            fn.apply(this, arguments);
            return originalFn.apply(this, arguments);
        };
    }

    function around(obj, name, fn) {
        var f = partial(fn, obj[name]);
        obj[name] = function () {
            return f.apply(this, arguments);
        };
    }

    cull.after = after;
    cull.before = before;
    cull.around = around;

    // cull.dom

    (function () {
        function children(elements) {
            if (isSeq(elements)) { return flatten(map(children, elements)); }
            var results = [], child = elements.firstChild;
            while (child) {
                if (child.nodeType === 1) { results.push(child); }
                child = child.nextSibling;
            }
            return results;
        }

        function id(idStr) {
            return document.getElementById(idStr);
        }

        function get(selectors, parent) {
            if (!parent) { parent = document; }
            var select = function (seq, selector) {
                if (/^#/.test(selector)) {
                    return seq.concat(id(selector.slice(1)));
                } else if (/^\./.test(selector)) {
                    var cn = selector.slice(1);
                    return concat(seq, parent.getElementsByClassName(cn));
                } else {
                    return concat(seq, parent.getElementsByTagName(selector));
                }
            };
            return uniq(reduce(select, [], toSeq(selectors)));
        }

        function remove(element) {
            element.parentNode.removeChild(element);
        }

        function hasClassName(className, element) {
            var regexp = new RegExp("(^|\\s)" + className + "(\\s|$)");
            return regexp.test(element.className);
        }

        function addClassName(cn, element) {
            if (isSeq(element)) {
                return doall(partial(addClassName, cn), element);
            }
            if (hasClassName(cn, element)) { return; }
            element.className = trim(element.className + " " + cn);
        }

        function removeClassName(cn, element) {
            if (isSeq(element)) {
                return doall(partial(removeClassName, cn), element);
            }
            if (!hasClassName(cn, element)) { return; }
            var regexp = new RegExp("(^|\\s)" + cn + "(\\s|$)");
            element.className = trim(element.className.replace(regexp, " "));
        }

        function frag(items) {
            var fragment = document.createDocumentFragment();
            doall(bind(fragment, "appendChild"), toSeq(items));
            return fragment;
        }

        cull.dom = {
            hasClassName: hasClassName,
            children: children,
            id: id,
            get: get,
            remove: remove,
            frag: frag,
            cn: {
                add: addClassName,
                rm: removeClassName
            }
        };

        var el;

        var isContent = function (content) {
            return content !== null && typeof content !== "undefined" &&
                (typeof content.nodeType !== "undefined" ||
                 typeof content === "string" ||
                 isSeq(content));
        };

        function setProp(properties, element) {
            var name, mapper;
            properties = properties || {};

            for (name in properties) {
                if (properties.hasOwnProperty(name)) {
                    mapper = el.propmap[name];
                    if (mapper) {
                        mapper(element, properties[name]);
                    } else {
                        element[name] = properties[name];
                    }
                }
            }
        }

        function append(content, element) {
            _assert(isContent(content),
                    "Content should be one or a list of [string, DOM element]");
            content = toSeq(content);
            var i, l;
            for (i = 0, l = content.length; i < l; ++i) {
                if (typeof content[i] === "string") {
                    element.appendChild(document.createTextNode(content[i]));
                } else {
                    element.appendChild(content[i]);
                }
            }
        }

        function content(children, element) {
            _assert(element && typeof element.innerHTML !== "undefined",
                    "content() needs element");
            element.innerHTML = "";
            append(children, element);
        }

        el = function (tagName, attrProps, content) {
            _refute(arguments.length > 3,
                    "Content should be one or a list of [string, DOM element]");
            if (!content && isContent(attrProps)) {
                return el(tagName, {}, attrProps);
            }
            _refute(attrProps && attrProps.tagName,
                    "Cannot set attribute property tagName. Use a list when " +
                    "adding multiple content elements.");
            var element = document.createElement(tagName);
            setProp(attrProps, element);
            append(content || [], element);
            return element;
        };

        el.toString = function () {
            return "cull.dom.el()";
        };

        el.propmap = {
            style: function (el, styles) {
                var property;
                for (property in styles) {
                    if (styles.hasOwnProperty(property)) {
                        el.style[property] = styles[property];
                    }
                }
            }
        };

        doall(function (tagName) { el[tagName] = partial(el, tagName); }, [
            "a", "br", "div", "fieldset", "form", "h2", "h3", "h4",
            "h5", "img", "input", "label", "li", "p", "span", "strong",
            "textarea", "ul", "span", "select", "option", "ol", "iframe",
            "table", "tr", "td", "pre", "button"
        ]);

        el.setProp = setProp;
        el.append = append;
        el.content = content;
        cull.dom.el = el;

    }());

    return cull;
}(this));

if (typeof require === "function" && typeof module !== "undefined") {
    module.exports = cull;
}
<commit_msg>Create cull object last.<commit_after>var cull = (function (global) {
    "use strict";

    var _ = global._ || require("underscore");
    var slice = Array.prototype.slice;
    var toString = Object.prototype.toString;

    function _assert(pred, msg) {
        if (!pred) { throw new TypeError(msg); }
    }

    function _refute(pred, msg) {
        _assert(!pred, msg);
    }

    function isSeq(seq) {
        return !!seq &&
            typeof seq === "object" &&
            typeof seq.length === "number" &&
            !seq.tagName;
    }

    function toSeq(value) {
        if (toString.call(value) === "[object Array]") { return value; }
        if (isSeq(value)) { return slice.call(value); }
        if (typeof value === "undefined" || value === null) { return []; }
        return slice.call(arguments);
    }

    function doall(fn, seq) {
        var i, l;
        for (i = 0, l = seq.length; i < l; ++i) {
            fn(seq[i], i, seq);
        }
    }

    function isFunction(fn) {
        return typeof fn === "function";
    }

    function reduce(fn, initial, seq) {
        if (arguments.length === 3) {
            return _.reduce(seq, fn, initial);
        }
        return _.reduce(initial, fn);
    }

    function all(fn, seq) {
        var i, l;
        for (i = 0, l = seq.length; i < l; ++i) {
            if (!fn(seq[i])) { return false; }
        }
        return true;
    }

    function some(fn, seq) {
        var i, l;
        for (i = 0, l = seq.length; i < l; ++i) {
            if (fn(seq[i])) { return true; }
        }
        return false;
    }

    function onlySome(fn, seq) {
        var i, l, t, f;
        for (i = 0, l = seq.length; i < l; ++i) {
            if (fn(seq[i])) {
                t = true;
            } else {
                f = true;
            }
            if (t && f) { return true; }
        }
        return false;
    }

    function trim(string) {
        return (string.trim && string.trim()) ||
            string.replace(/^\s+|\s+$/, "");
    }

    function identity(arg) { return arg; }

    function defined(o) { return typeof o !== "undefined" && o !== null; }

    function unary(fn) {
        return function (arg) {
            return fn.call(this, arg);
        };
    }

    function prop(name) {
        return function (object) {
            return object[name];
        };
    }

    function func(name, args) {
        return function (object) {
            return object[name].apply(object, toSeq(args));
        };
    }

    function eq(one) {
        return function (other) { return one === other; };
    }

    var composeSignature = "compose takes func|[funcs] " +
            "and optional thisp object";

    function compose(funcs, thisp) {
        _refute(isFunction(thisp) || arguments.length > 2, composeSignature);

        var fns = toSeq(funcs);

        _assert(all(isFunction, fns), composeSignature);

        return function () {
            var i = fns.length;
            var result = arguments;
            while (i--) {
                result = [fns[i].apply(thisp || this, result)];
            }
            return result[0];
        };
    }

    function callWith() {
        var args = arguments;
        return function (fn) {
            return fn.apply(this, args);
        };
    }

    function partial(fn) {
        var args = slice.call(arguments, 1);
        return function () {
            return fn.apply(this, args.concat(slice.call(arguments)));
        };
    }

    function bind(obj, methOrProp) {
        var fn = typeof methOrProp === "string" ? obj[methOrProp] : methOrProp;
        var args = slice.call(arguments, 2);
        return function () {
            return fn.apply(obj, args.concat(slice.call(arguments)));
        };
    }

    function handler(handlr, type) {
        if (typeof handlr === "function") { return handlr; }
        _assert(isFunction(handlr[type]),
                "Handler has no method '" + type + "'");
        return bind.apply(null, arguments);
    }

    var switchArgs = function (obj, name) {
        return function (fn, seq) {
            var args = [seq, fn].concat(slice.call(arguments, 2));
            return obj[name].apply(obj, args);
        };
    };

    var flatten = _.flatten;
    var uniq = _.uniq;
    var first = switchArgs(_, "find");
    var select = switchArgs(_, "filter");
    var indexOf = switchArgs(_, "indexOf");
    var difference = _.difference;
    var seldef = partial(select, defined);

    function map(fn, coll) {
        var result = [], i, l;
        for (i = 0, l = coll.length; i < l; i++) {
            result.push(fn(coll[i]));
        }
        return result;
    }

    function negate(pred) {
        return function () {
            return !pred.apply(this, arguments);
        };
    }

    function reject(pred, seq) {
        return select(negate(pred), seq);
    }

    function concat(seq, items) {
        return toSeq(seq).concat(toSeq(items));
    }

    function partition(n, seq) {
        var result = [], i, l;
        for (i = 0, l = seq.length; i < l; i += n) {
            result.push(seq.slice(i, i + n));
        }
        return result;
    }

    function mapdef(fn, coll) {
        return seldef(map(fn, seldef(coll)));
    }

    function mapcat(fn, coll) {
        return reduce(concat, map(fn, coll));
    }

    function interpose(sep, coll) {
        var result = [], i, l;
        for (i = 0, l = coll.length; i < l; i += 1) {
            result.push(coll[i]);
            if (i < l - 1) {
                result.push(sep);
            }
        }
        return result;
    }

    // cull.advice

    function after(obj, name, fn) {
        var originalFn = obj[name];
        obj[name] = function () {
            var ret1 = originalFn.apply(this, arguments);
            var ret2 = fn.apply(this, [ret1].concat(slice.call(arguments)));
            return typeof ret2 !== "undefined" ? ret2 : ret1;
        };
    }

    function before(obj, name, fn) {
        var originalFn = obj[name];
        obj[name] = function () {
            fn.apply(this, arguments);
            return originalFn.apply(this, arguments);
        };
    }

    function around(obj, name, fn) {
        var f = partial(fn, obj[name]);
        obj[name] = function () {
            return f.apply(this, arguments);
        };
    }

    // cull.dom

    var dom;

    (function () {
        function children(elements) {
            if (isSeq(elements)) { return flatten(map(children, elements)); }
            var results = [], child = elements.firstChild;
            while (child) {
                if (child.nodeType === 1) { results.push(child); }
                child = child.nextSibling;
            }
            return results;
        }

        function id(idStr) {
            return document.getElementById(idStr);
        }

        function get(selectors, parent) {
            if (!parent) { parent = document; }
            var select = function (seq, selector) {
                if (/^#/.test(selector)) {
                    return seq.concat(id(selector.slice(1)));
                } else if (/^\./.test(selector)) {
                    var cn = selector.slice(1);
                    return concat(seq, parent.getElementsByClassName(cn));
                } else {
                    return concat(seq, parent.getElementsByTagName(selector));
                }
            };
            return uniq(reduce(select, [], toSeq(selectors)));
        }

        function remove(element) {
            element.parentNode.removeChild(element);
        }

        function hasClassName(className, element) {
            var regexp = new RegExp("(^|\\s)" + className + "(\\s|$)");
            return regexp.test(element.className);
        }

        function addClassName(cn, element) {
            if (isSeq(element)) {
                return doall(partial(addClassName, cn), element);
            }
            if (hasClassName(cn, element)) { return; }
            element.className = trim(element.className + " " + cn);
        }

        function removeClassName(cn, element) {
            if (isSeq(element)) {
                return doall(partial(removeClassName, cn), element);
            }
            if (!hasClassName(cn, element)) { return; }
            var regexp = new RegExp("(^|\\s)" + cn + "(\\s|$)");
            element.className = trim(element.className.replace(regexp, " "));
        }

        function frag(items) {
            var fragment = document.createDocumentFragment();
            doall(bind(fragment, "appendChild"), toSeq(items));
            return fragment;
        }

        dom = {
            hasClassName: hasClassName,
            children: children,
            id: id,
            get: get,
            remove: remove,
            frag: frag,
            cn: {
                add: addClassName,
                rm: removeClassName
            }
        };

        var el;

        var isContent = function (content) {
            return content !== null && typeof content !== "undefined" &&
                (typeof content.nodeType !== "undefined" ||
                 typeof content === "string" ||
                 isSeq(content));
        };

        function setProp(properties, element) {
            var name, mapper;
            properties = properties || {};

            for (name in properties) {
                if (properties.hasOwnProperty(name)) {
                    mapper = el.propmap[name];
                    if (mapper) {
                        mapper(element, properties[name]);
                    } else {
                        element[name] = properties[name];
                    }
                }
            }
        }

        function append(content, element) {
            _assert(isContent(content),
                    "Content should be one or a list of [string, DOM element]");
            content = toSeq(content);
            var i, l;
            for (i = 0, l = content.length; i < l; ++i) {
                if (typeof content[i] === "string") {
                    element.appendChild(document.createTextNode(content[i]));
                } else {
                    element.appendChild(content[i]);
                }
            }
        }

        function content(children, element) {
            _assert(element && typeof element.innerHTML !== "undefined",
                    "content() needs element");
            element.innerHTML = "";
            append(children, element);
        }

        el = function (tagName, attrProps, content) {
            _refute(arguments.length > 3,
                    "Content should be one or a list of [string, DOM element]");
            if (!content && isContent(attrProps)) {
                return el(tagName, {}, attrProps);
            }
            _refute(attrProps && attrProps.tagName,
                    "Cannot set attribute property tagName. Use a list when " +
                    "adding multiple content elements.");
            var element = document.createElement(tagName);
            setProp(attrProps, element);
            append(content || [], element);
            return element;
        };

        el.toString = function () {
            return "cull.dom.el()";
        };

        el.propmap = {
            style: function (el, styles) {
                var property;
                for (property in styles) {
                    if (styles.hasOwnProperty(property)) {
                        el.style[property] = styles[property];
                    }
                }
            }
        };

        doall(function (tagName) { el[tagName] = partial(el, tagName); }, [
            "a", "br", "div", "fieldset", "form", "h2", "h3", "h4",
            "h5", "img", "input", "label", "li", "p", "span", "strong",
            "textarea", "ul", "span", "select", "option", "ol", "iframe",
            "table", "tr", "td", "pre", "button"
        ]);

        el.setProp = setProp;
        el.append = append;
        el.content = content;
        dom.el = el;
    }());

    return {
        _assert: _assert,
        _refute: _refute,
        trim: trim,
        doall: doall,
        reduce: reduce,
        all: all,
        some: some,
        onlySome: onlySome,
        isFunction: isFunction,
        isSeq: isSeq,
        toSeq: toSeq,
        identity: identity,
        defined: defined,
        unary: unary,
        prop: prop,
        func: func,
        eq: eq,
        compose: compose,
        callWith: callWith,
        partial: partial,
        bind: bind,
        handler: handler,
        keys: _.keys,
        values: _.values,
        concat: concat,
        flatten: flatten,
        uniq: uniq,
        first: first,
        select: select,
        reject: reject,
        seldef: seldef,
        map: map,
        mapdef: mapdef,
        mapcat: mapcat,
        partition: partition,
        difference: difference,
        interpose: interpose,
        indexOf: indexOf,
        after: after,
        before: before,
        around: around,
        dom: dom
    };
}(this));

if (typeof require === "function" && typeof module !== "undefined") {
    module.exports = cull;
}
<|endoftext|>


<commit_before>'use strict';

var fs     = require('./file');
var logger = require('./log');
var cgf    = require('./cfg');

exports = module.exports = {

  /**
   * Expose the version.
   * @return {String} Version number
   */
  version: require('../package.json').version,

  /**
   * Main API function, running the whole thing
   * @param {String} source - Source folder
   * @param {String} destination - Destination folder
   * @param {Object} config - Configuration from `view.json`
   * @example
   * documentize('examples/sass', 'examples/dist', config)
   * @return {Q.promise}
   */
  documentize: function (source, destination, config) {
    config = cgf(config);

    return fs.folder.refresh(destination)
      .then(function () {
        logger.log('Folder `' + destination + '` successfully generated.');
        return fs.getData(source);
      })
      .then(function (data) {
        var group, i;
        var count = 0;
        var shouldBeDisplayed = function (item) {
          return (config.display.access.indexOf(item.access[0]) !== -1) && !(!config.display.alias && item.alias);
        };

        // Adding a `display` key to each item
        for (group in data) {
          for (i = 0; i < data[group].length; i++) {
            data[group][i].display = shouldBeDisplayed(data[group][i]);

            if (data[group][i].display === true) {
              count++;
            }
          }
        }

        config.dataCount = count;

        return data;
      })
      .then(function (data) {
        logger.log('Folder `' + source + '` successfully parsed.');
        config.data = data;

        var promise = config.theme(destination, config);

        if (promise && typeof promise.then === 'function') {
          return promise;
        }

        throw 'Theme didn\'t return a promise, got ' +
              Object.prototype.toString.call(promise) + '.';
      })
      .then(function () {
        logger.log('Theme successfully rendered.');
        logger.log('Process over. Everything okay!');
      })
      .fail(function (err) {
        logger.error(err);
        throw err;
      });
  },

  /**
   * Parse a folder and returns a promise yielding an array of documented items
   * @param {String} source - Source folder
   * @example
   * sassdoc.parse('examples/sass')
   * @return {Q.promise}
   */
  parse: function (source) {
    return fs.getData(source);
  },

  /**
   * Expose the logger used by sassdoc
   * @return {Logger}
   */
  logger: logger
};
<commit_msg>Remove trailing whitespace.<commit_after>'use strict';

var fs     = require('./file');
var logger = require('./log');
var cgf    = require('./cfg');

exports = module.exports = {

  /**
   * Expose the version.
   * @return {String} Version number
   */
  version: require('../package.json').version,

  /**
   * Main API function, running the whole thing
   * @param {String} source - Source folder
   * @param {String} destination - Destination folder
   * @param {Object} config - Configuration from `view.json`
   * @example
   * documentize('examples/sass', 'examples/dist', config)
   * @return {Q.promise}
   */
  documentize: function (source, destination, config) {
    config = cgf(config);

    return fs.folder.refresh(destination)
      .then(function () {
        logger.log('Folder `' + destination + '` successfully generated.');
        return fs.getData(source);
      })
      .then(function (data) {
        var group, i;
        var count = 0;
        var shouldBeDisplayed = function (item) {
          return (config.display.access.indexOf(item.access[0]) !== -1) && !(!config.display.alias && item.alias);
        };

        // Adding a `display` key to each item
        for (group in data) {
          for (i = 0; i < data[group].length; i++) {
            data[group][i].display = shouldBeDisplayed(data[group][i]);

            if (data[group][i].display === true) {
              count++;
            }
          }
        }

        config.dataCount = count;

        return data;
      })
      .then(function (data) {
        logger.log('Folder `' + source + '` successfully parsed.');
        config.data = data;

        var promise = config.theme(destination, config);

        if (promise && typeof promise.then === 'function') {
          return promise;
        }

        throw 'Theme didn\'t return a promise, got ' +
              Object.prototype.toString.call(promise) + '.';
      })
      .then(function () {
        logger.log('Theme successfully rendered.');
        logger.log('Process over. Everything okay!');
      })
      .fail(function (err) {
        logger.error(err);
        throw err;
      });
  },

  /**
   * Parse a folder and returns a promise yielding an array of documented items
   * @param {String} source - Source folder
   * @example
   * sassdoc.parse('examples/sass')
   * @return {Q.promise}
   */
  parse: function (source) {
    return fs.getData(source);
  },

  /**
   * Expose the logger used by sassdoc
   * @return {Logger}
   */
  logger: logger
};
<|endoftext|>


<commit_before>/**
 * Welcome to Pebble.js!
 *
 * This is where you write your app.
 */

var UI = require('ui');
var Vector2 = require('vector2');

var totalCoins = 0;
var totalHealth = 20;

var main = new UI.Card({
  title: 'tile5',
  icon: 'images/menu_icon.png',
  subtitle: 'True time tower defense',
  body: 'Press any button.'
});

main.show();

/*main.on('click', 'up', function(e) {
  var menu = new UI.Menu({
    sections: [{
      items: [{
        title: 'Pebble.js',
        icon: 'images/menu_icon.png',
        subtitle: 'Can do Menus'
      }, {
        title: 'Second Item',
        subtitle: 'Subtitle Text'
      }]
    }]
  });
  menu.on('select', function(e) {
    console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
    console.log('The item is titled "' + e.item.title + '"');
  });
  menu.show();
});

main.on('click', 'select', function(e) {
  var wind = new UI.Window();
  var textfield = new UI.Text({
    position: new Vector2(0, 50),
    size: new Vector2(144, 30),
    font: 'gothic-24-bold',
    text: 'Text Anywhere!',
    textAlign: 'center'
  });
  wind.add(textfield);
  wind.show();
});

main.on('click', 'down', function(e) {
  var card = new UI.Card();
  card.title('A Card');
  card.subtitle('Is a Window');
  card.body('The simplest window type in Pebble.js.');
  card.show();
});*/

main.on('click', 'select', function(e) {
  var menu = new UI.Menu({
    sections: [{
      // Items are instant use upon purchase
      items: [{
        title: 'Buy Health (2)',
        subtitle: 'Heals for 1 hp'
      }, {
        title: 'Buy Wall (3)',
        subtitle: 'Takes the next hit'
      }, {
        title: 'Buy Nuke (4)',
        subtitle: 'Clears every tile'
      }]
    }]
  });

  menu.on('select', function(e) {
    // If Health was purchased
    if (e.sectionIndex === 0 && e.itemIndex === 0) {
      if (totalHealth == 20 || totalCoins < 2) {
        totalHealth = totalHealth + 1;
        console.log(totalHealth);
      }
    }
    // If Wall was purchased
    if (e.sectionIndex === 0 && e.itemIndex === 1) {
      console.log("Wall was purchased");
    }

    // If Nuke was purchased
    if (e.sectionIndex === 0 && e.itemIndex === 2) {
      console.log("Nuke was purchased");
    }
  });
  menu.show();
});<commit_msg>functionality for wall and nuke, health validation<commit_after>/**
 * Welcome to Pebble.js!
 *
 * This is where you write your app.
 */

var UI = require('ui');
var Vector2 = require('vector2');

var totalCoins = 10;
var totalHealth = 20;

var main = new UI.Card({
  title: 'tile5',
  icon: 'images/menu_icon.png',
  subtitle: 'True time tower defense',
  body: 'Press any button.'
});

main.show();

/*main.on('click', 'up', function(e) {
  var menu = new UI.Menu({
    sections: [{
      items: [{
        title: 'Pebble.js',
        icon: 'images/menu_icon.png',
        subtitle: 'Can do Menus'
      }, {
        title: 'Second Item',
        subtitle: 'Subtitle Text'
      }]
    }]
  });
  menu.on('select', function(e) {
    console.log('Selected item #' + e.itemIndex + ' of section #' + e.sectionIndex);
    console.log('The item is titled "' + e.item.title + '"');
  });
  menu.show();
});

main.on('click', 'select', function(e) {
  var wind = new UI.Window();
  var textfield = new UI.Text({
    position: new Vector2(0, 50),
    size: new Vector2(144, 30),
    font: 'gothic-24-bold',
    text: 'Text Anywhere!',
    textAlign: 'center'
  });
  wind.add(textfield);
  wind.show();
});

main.on('click', 'down', function(e) {
  var card = new UI.Card();
  card.title('A Card');
  card.subtitle('Is a Window');
  card.body('The simplest window type in Pebble.js.');
  card.show();
});*/

main.on('click', 'select', function(e) {
  var menu = new UI.Menu({
    sections: [{
      // Items are instant use upon purchase
      items: [{
        title: 'Buy Health (2)',
        subtitle: 'Heals for 1 hp'
      }, {
        title: 'Buy Wall (3)',
        subtitle: 'Takes the next hit'
      }, {
        title: 'Buy Nuke (4)',
        subtitle: 'Clears every tile'
      }]
    }]
  });

  menu.on('select', function(e) {
    // If Health was purchased
    if (e.sectionIndex === 0 && e.itemIndex === 0) {
      if (totalHealth == 20 || totalCoins < 2) {
        totalHealth = totalHealth + 1;
        console.log(totalHealth);
      }
    }
    // If Wall was purchased
    if (e.sectionIndex === 0 && e.itemIndex === 1) {
      console.log("Wall was purchased");
    }

    // If Nuke was purchased
    if (e.sectionIndex === 0 && e.itemIndex === 2) {
      console.log("Nuke was purchased");
    }
  });
  menu.show();
});<|endoftext|>