<commit_before>'use strict';

let datafire = require('datafire');
let nodepath = require('path');
let fs = require('fs');

let CONTENT_TYPES = {
  '.html': 'text/html',
  '.js': 'application/javascript',
  '.json': 'application/json',
  '.xml': 'application/xml',
  '.zip': 'application/zip',
  '.pdf': 'application/pdf',
  '.sql': 'application/sql',
  '.mpeg': 'audio/mpeg',
  '.css': 'text/css',
  '.csv': 'text/csv',
  '.png': 'image/png',
  '.jpeg': 'image/jpeg',
  '.gif': 'image/gif',
}

let fileserver = module.exports = new datafire.Integration({
  id: 'fileserver',
  title: "File Server",
  description: "Serve static files, such as HTML, CSS, JavaScript, and images",
});

fileserver.addAction('serve', {
  inputs: [{
    title: 'filename',
    type: 'string',
  }, {
    title: 'contentType',
    type: 'string',
    default: '',
  }],

  security: {
    fileserver: {
      fields: {
        baseDirectory: 'The directory to use as the file server\'s root',
      }
    }
  },

  handler: (input, context) => {
    let baseDir = context.accounts.fileserver.baseDirectory;
    if (!baseDir) throw new Error("Must specify context.accounts.fileserver.baseDirectory");
    return new Promise((resolve, reject) => {
      let filename = nodepath.join('/', input.filename);
      filename = nodepath.join(baseDir, filename);
      let ctype = input.contentType;
      if (!ctype) {
        let extname = nodepath.extname(filename);
        ctype = CONTENT_TYPES[extname] || 'text/plain';
      }
      fs.readFile(filename, 'utf8', (err, contents) => {
        if (err) {
          let resp = {statusCode: 500, body: "Error retrieving file " + input.filename};
          if (err.code === 'ENOENT') {
            resp = {statusCode: 404, body: "File not found: " + input.filename};
          } else {
            return reject(new datafire.Response({
              statusCode: 500,
              body: "Error retrieving file " + input.filename,
            }));
          }
          return reject(new datafire.Response(resp));
        }
        resolve(new datafire.Response({
          headers: {'Content-Type': ctype},
          body: contents,
        }))
      })
    })
  }
})
<commit_msg>add font content types<commit_after>'use strict';

let datafire = require('datafire');
let nodepath = require('path');
let fs = require('fs');

let CONTENT_TYPES = {
  '.html': 'text/html',
  '.js': 'application/javascript',
  '.json': 'application/json',
  '.xml': 'application/xml',
  '.zip': 'application/zip',
  '.pdf': 'application/pdf',
  '.sql': 'application/sql',
  '.mpeg': 'audio/mpeg',
  '.css': 'text/css',
  '.csv': 'text/csv',
  '.png': 'image/png',
  '.jpeg': 'image/jpeg',
  '.gif': 'image/gif',
  '.eot': 'application/vnd.ms-fontobject',
  '.otf': 'application/font-sfnt',
  '.svg': 'image/svg+xml',
  '.ttf': 'application/font-sfnt',
  '.woff': 'application/font-woff',
}

let fileserver = module.exports = new datafire.Integration({
  id: 'fileserver',
  title: "File Server",
  description: "Serve static files, such as HTML, CSS, JavaScript, and images",
});

fileserver.addAction('serve', {
  inputs: [{
    title: 'filename',
    type: 'string',
  }, {
    title: 'contentType',
    type: 'string',
    default: '',
  }],

  security: {
    fileserver: {
      fields: {
        baseDirectory: 'The directory to use as the file server\'s root',
      }
    }
  },

  handler: (input, context) => {
    let baseDir = context.accounts.fileserver.baseDirectory;
    if (!baseDir) throw new Error("Must specify context.accounts.fileserver.baseDirectory");
    return new Promise((resolve, reject) => {
      let filename = nodepath.join('/', input.filename);
      filename = nodepath.join(baseDir, filename);
      let ctype = input.contentType;
      if (!ctype) {
        let extname = nodepath.extname(filename);
        ctype = CONTENT_TYPES[extname] || 'text/plain';
      }
      fs.readFile(filename, 'utf8', (err, contents) => {
        if (err) {
          let resp = {statusCode: 500, body: "Error retrieving file " + input.filename};
          if (err.code === 'ENOENT') {
            resp = {statusCode: 404, body: "File not found: " + input.filename};
          } else {
            return reject(new datafire.Response({
              statusCode: 500,
              body: "Error retrieving file " + input.filename,
            }));
          }
          return reject(new datafire.Response(resp));
        }
        resolve(new datafire.Response({
          headers: {'Content-Type': ctype},
          body: contents,
        }))
      })
    })
  }
})
<|endoftext|>


<commit_before>var EventEmitter = require("events").EventEmitter;
require('rootpath')();
var mcu = require('hardware/mcu.js');
var power = require('hardware/power.js');
var watchdog = require('system/watchdog.js');
var _ = require('underscore');
var net = require('net');

var core = new EventEmitter();

var cbStore = {};
var cbIndex = 0;

console.log(">>>>>>>>>>>>>>>>>>>>> starting intervalometer client >>>>>>>>>>>>>>>>>>>");

function getCallbackId(callerName, cb) {
    if (!cb) return 0;
    cbIndex++;
    if (cbIndex > 300) cbIndex = 1;
    cbStore[cbIndex.toString()] = {callback: cb, name: callerName};
    return cbIndex;
}

function runCallback(cbData) {
    if (cbData && cbData.id && cbStore[cbData.id.toString()]) {
        var cb = cbStore[cbData.id.toString()];
        console.log("running callback for ", cb.name);
        cb && cb.callback && cb.callback(cbData.err, cbData.data);
        delete cbStore[cbData.id.toString()];
    }
}

function errorCallbacks(err, port) {
    console.log("running remaining callbacks:", JSON.stringify(cbStore));
    for (var i in cbStore) {
        runCallback({
            id: i,
            err: err,
            data: null
        });
    }
}

// buffered data
core.cameraSettings = {};
core.cameraConnected = false;
core.cameraModel = "";
core.cameraCount = 0;
core.cameraSupports = {};
core.intervalometerStatus = {};
core.histogram = [];
core.motionStatus = {};

var dataBuf = new Buffer(0);
var client;
function connect() {
    client = net.connect('/tmp/intervalometer.sock', function() {
      console.log('connected to server!');
      client.ready = true;
    });
    client.on('data', function(rawChunk) {
      var data;
      try {
        if(!rawChunk.length) return;
        dataBuf = Buffer.concat([dataBuf, rawChunk]);
        if(rawChunk[rawChunk.length - 1] != 0) {
            return;
        }
        var chunk = dataBuf.toString('utf8');
        dataBuf = new Buffer(0);
        var pieces = chunk.split('\0');
        for(var i = 0; i < pieces.length; i++) {
            pieces[i] = pieces[i].trim();
            if(!pieces[i]) continue;
            data = JSON.parse(pieces[i]);
            if(data.type == 'callback') {
                runCallback(data.data);
            } else if(data.type == 'watchdog') {
                var pid = parseInt(data.data);
                watchdog.watch(pid);
            } else {
                if(data.type == 'camera.photo') {
                    if(data.data.base64) {
                        data.data.jpeg = new Buffer(data.data.base64, 'base64');
                    }
                    core.photo = data.data;
                    data.data = null;
                } else if(data.type == 'camera.settings') {
                    core.cameraSettings = data.data;
                } else if(data.type == 'camera.histogram') {
                    core.histogram = data.data;
                } else if(data.type == 'camera.connected') {
                    core.cameraConnected = data.data.connected;
                    core.cameraModel = data.data.model;
                    core.cameraCount = data.data.count;
                    core.cameraSupports = data.data.supports;
                    core.getSettings();
                } else if(data.type == 'camera.exiting') {
                    core.cameraConnected = data.data.connected;
                    core.cameraModel = data.data.model;
                    core.cameraCount = data.data.count;
                    core.cameraSupports = data.data.supports;
                } else if(data.type == 'motion.status') {
                    core.motionStatus = data.data;
                } else if(data.type == 'media.present') {
                    core.sdMounted = data.data;
                    core.sdPresent = true;
                } else if(data.type == 'media.insert') {
                    core.sdPresent = true;
                } else if(data.type == 'media.remove') {
                    core.sdPresent = false;
                } else if(data.type == 'intervalometer.status') {
                    core.intervalometerStatus = data.data;
                    if(core.intervalometerStatus.running == false) {
                        power.performance('low');
                    }
                }
                console.log("CORE:", data.type, "event");
                core.emit(data.type, data.data);
            }
        }
      } catch(e) {
        console.log("Error parsing data:", data, e);
      }
    });
    client.on('end', function() {
      client.ready = false;
      console.log('disconnected from server');
      setTimeout(connect, 2000);
    });
    client.on('error', function(err) {
        if(err && err.code && (err.code == 'ECONNREFUSED' || err.code == 'ENOENT')) {
            console.log("Error: server not ready");
            setTimeout(connect, 1000);
        } else {
            console.log("error: ", err);
        }
        client.ready = false;
        client.end();
    });
}
connect();

function call(method, args, callback) {
    if(!client.ready) return;
    var cbId = getCallbackId(method, callback);
    var payload = JSON.stringify({
        type: method,
        args: args,
        id: cbId
    });
    if(client.ready) client.write(payload+'\0');
}

core.connectSonyWifi = function(callback) {
    call('camera.ptp.connectSonyWifi', {}, callback);
};
core.lvOff = function(callback) {
    call('camera.ptp.lvOff', {}, callback);
};
core.zoom = function(xPercent, yPercent, callback) {
    call('camera.ptp.zoom', {x:xPercent,y:yPercent}, function(err, data) {
        core.cameraZoomed = data.zoomed;
        callback(err, data);
    });
};
core.focus = function(step, repeat, callback) {
    call('camera.ptp.focus', {step:step, repeat:repeat}, callback);
};
core.setEv = function(ev, options, callback) {
    call('camera.setEv', {ev:ev, options:options}, callback);
};
core.preview = function(callback) {
    call('camera.ptp.preview', {}, callback);
};
core.getSettings = function(callback) {
    call('camera.ptp.getSettings', {}, callback);
};
core.cameraList = function(callback) {
    call('camera.ptp.cameraList', {}, callback);
};
core.switchPrimary = function(cameraObject, callback) {
    call('camera.ptp.switchPrimary', {cameraObject:cameraObject}, callback);
};
core.capture = function(options, callback) {
    call('camera.ptp.capture', {options:options}, callback);
};
core.captureTest = function(callback) {
    call('camera.ptp.capture-test', {}, callback);
};
core.runSupportTest = function(callback) {
    call('camera.ptp.runSupportTest', {}, callback);
};
core.set = function(key, val, callback) {
    call('camera.ptp.set', {key:key, val:val}, callback);
};
core.mountSd = function(callback) {
    call('camera.ptp.mountSd', {}, function(err, res){
        core.sdMounted = res;
        callback(err, res)
    });
};
core.unmountSd = function(callback) {
    call('camera.ptp.unmountSd', {}, callback);
};

core.moveMotion = function(driver, motor, steps, callback) {
    call('motion.move', {driver:driver, motor:motor, steps:steps}, callback);
};

core.zeroMotion = function(driver, motor, callback) {
    call('motion.zero', {driver:driver, motor:motor}, callback);
};

core.motionStatusUpdate = function(callback) {
    call('motion.status', {}, callback);
};

core.moveMotionJoystick = function(driver, motor, speed, callback) {
    call('motion.joystick', {driver:driver, motor:motor, speed:speed}, callback);
};

core.getCurrentTimelapseFrames = function(cameraIndex, callback) {
    call('db.currentTimelapseFrames', {cameraIndex:cameraIndex}, callback);
};

var wdtInterval = null;
core.watchdogEnable = function(callback) {
    if(!wdtInterval) {
        wdtInterval = setInterval(core.watchdogEnable, 5000); // this will have the server kill this process if it ever gets stuck
    }
    call('watchdog.set', {pid:process.pid}, callback);
};

core.watchdogDisable = function(callback) {
    if(wdtInterval) {
        clearInterval(wdtInterval);
        wdtInterval = null;
    }
    call('watchdog.disable', {pid:process.pid}, function(err){
        callback && callback(err);
    });
};

core.resetBt = function(callback) {
    call('bt.reset', {}, callback);
};

defaultProgram = {
    rampMode: "fixed",
    intervalMode: "fixed",
    rampAlgorithm: "lum",
    interval: 5,
    dayInterval: 5,
    nightInterval: 35,
    frames: 300,
    destination: 'camera',
    nightCompensation: -1,
    isoMax: -6,
    isoMin:  0,
    rampParameters:  'S+I',
    apertureMax: -2,
    apertureMin:  -4,
    manualAperture: -5,
    hdrCount: 0,
    hdrStops: 1,
    exposurePlans: [],
    keyframes: [{
        focus: 0,
        ev: "not set",
        motor: {}
    }]
};

core.intervalometerStatus = {
    running: false,
    frames: 0,
    framesRemaining: 0,
    rampRate: 0,
    intervalMs: 0,
    message: "",
    rampEv: null,
    autoSettings: {
        paddingTimeMs: 5000
    }
}
(args.parameter, args.newValue, args.frames, callback);
core.moveTracking = function(axis, degrees, callback) {
    call('intervalometer.moveTracking', {axis:axis, degrees:degrees}, callback);
}

core.dynamicChange = function(parameter, newValue, frames, callback) {
    call('intervalometer.dynamicChange', {parameter:parameter, newValue:newValue, frames:frames}, callback);
}

core.loadProgram = function(program, callback) {
    if(!program.frames) program.frames = Infinity; // Infinity comes back as null from the DB
    if(program.keyframes) { // arrays come back as object in the VIEW db
        var kfs = [];
        for(var key in program.keyframes) {
            if(program.keyframes.hasOwnProperty(key)) {
                kfs.push(program.keyframes[key]);
            }
        }
        if(kfs.length > 0) program.keyframes = kfs;
    }
    if(program.exposurePlans) { // arrays come back as object in the VIEW db
        var plans = [];
        for(var key in program.exposurePlans) {
            if(program.exposurePlans.hasOwnProperty(key)) {
                plans.push(program.exposurePlans[key]);
            }
        }
        if(plans.length > 0) program.exposurePlans = plans;
    }

    core.currentProgram = _.extendOwn(defaultProgram, core.currentProgram, program);
    callback && callback();
}
core.loadProgram(defaultProgram);

core.stopIntervalometer = function(callback) {
    call('intervalometer.cancel', {}, callback);
}
core.startIntervalometer = function(program, callback) {
    power.performance('high');
    core.addGpsData(mcu.validCoordinates());
    call('intervalometer.run', {program:program}, callback);
}
core.addGpsData = function(gpsData, callback) {
    call('gps', {gpsData:gpsData}, callback);
}

mcu.on('gps', function(status){
    if(status == 2) {
        core.addGpsData(mcu.gps);
    }
});

module.exports = core;<commit_msg>live-change paramters<commit_after>var EventEmitter = require("events").EventEmitter;
require('rootpath')();
var mcu = require('hardware/mcu.js');
var power = require('hardware/power.js');
var watchdog = require('system/watchdog.js');
var _ = require('underscore');
var net = require('net');

var core = new EventEmitter();

var cbStore = {};
var cbIndex = 0;

console.log(">>>>>>>>>>>>>>>>>>>>> starting intervalometer client >>>>>>>>>>>>>>>>>>>");

function getCallbackId(callerName, cb) {
    if (!cb) return 0;
    cbIndex++;
    if (cbIndex > 300) cbIndex = 1;
    cbStore[cbIndex.toString()] = {callback: cb, name: callerName};
    return cbIndex;
}

function runCallback(cbData) {
    if (cbData && cbData.id && cbStore[cbData.id.toString()]) {
        var cb = cbStore[cbData.id.toString()];
        console.log("running callback for ", cb.name);
        cb && cb.callback && cb.callback(cbData.err, cbData.data);
        delete cbStore[cbData.id.toString()];
    }
}

function errorCallbacks(err, port) {
    console.log("running remaining callbacks:", JSON.stringify(cbStore));
    for (var i in cbStore) {
        runCallback({
            id: i,
            err: err,
            data: null
        });
    }
}

// buffered data
core.cameraSettings = {};
core.cameraConnected = false;
core.cameraModel = "";
core.cameraCount = 0;
core.cameraSupports = {};
core.intervalometerStatus = {};
core.histogram = [];
core.motionStatus = {};

var dataBuf = new Buffer(0);
var client;
function connect() {
    client = net.connect('/tmp/intervalometer.sock', function() {
      console.log('connected to server!');
      client.ready = true;
    });
    client.on('data', function(rawChunk) {
      var data;
      try {
        if(!rawChunk.length) return;
        dataBuf = Buffer.concat([dataBuf, rawChunk]);
        if(rawChunk[rawChunk.length - 1] != 0) {
            return;
        }
        var chunk = dataBuf.toString('utf8');
        dataBuf = new Buffer(0);
        var pieces = chunk.split('\0');
        for(var i = 0; i < pieces.length; i++) {
            pieces[i] = pieces[i].trim();
            if(!pieces[i]) continue;
            data = JSON.parse(pieces[i]);
            if(data.type == 'callback') {
                runCallback(data.data);
            } else if(data.type == 'watchdog') {
                var pid = parseInt(data.data);
                watchdog.watch(pid);
            } else {
                if(data.type == 'camera.photo') {
                    if(data.data.base64) {
                        data.data.jpeg = new Buffer(data.data.base64, 'base64');
                    }
                    core.photo = data.data;
                    data.data = null;
                } else if(data.type == 'camera.settings') {
                    core.cameraSettings = data.data;
                } else if(data.type == 'camera.histogram') {
                    core.histogram = data.data;
                } else if(data.type == 'camera.connected') {
                    core.cameraConnected = data.data.connected;
                    core.cameraModel = data.data.model;
                    core.cameraCount = data.data.count;
                    core.cameraSupports = data.data.supports;
                    core.getSettings();
                } else if(data.type == 'camera.exiting') {
                    core.cameraConnected = data.data.connected;
                    core.cameraModel = data.data.model;
                    core.cameraCount = data.data.count;
                    core.cameraSupports = data.data.supports;
                } else if(data.type == 'motion.status') {
                    core.motionStatus = data.data;
                } else if(data.type == 'media.present') {
                    core.sdMounted = data.data;
                    core.sdPresent = true;
                } else if(data.type == 'media.insert') {
                    core.sdPresent = true;
                } else if(data.type == 'media.remove') {
                    core.sdPresent = false;
                } else if(data.type == 'intervalometer.status') {
                    core.intervalometerStatus = data.data;
                    if(core.intervalometerStatus.running == false) {
                        power.performance('low');
                    }
                }
                console.log("CORE:", data.type, "event");
                core.emit(data.type, data.data);
            }
        }
      } catch(e) {
        console.log("Error parsing data:", data, e);
      }
    });
    client.on('end', function() {
      client.ready = false;
      console.log('disconnected from server');
      setTimeout(connect, 2000);
    });
    client.on('error', function(err) {
        if(err && err.code && (err.code == 'ECONNREFUSED' || err.code == 'ENOENT')) {
            console.log("Error: server not ready");
            setTimeout(connect, 1000);
        } else {
            console.log("error: ", err);
        }
        client.ready = false;
        client.end();
    });
}
connect();

function call(method, args, callback) {
    if(!client.ready) return;
    var cbId = getCallbackId(method, callback);
    var payload = JSON.stringify({
        type: method,
        args: args,
        id: cbId
    });
    if(client.ready) client.write(payload+'\0');
}

core.connectSonyWifi = function(callback) {
    call('camera.ptp.connectSonyWifi', {}, callback);
};
core.lvOff = function(callback) {
    call('camera.ptp.lvOff', {}, callback);
};
core.zoom = function(xPercent, yPercent, callback) {
    call('camera.ptp.zoom', {x:xPercent,y:yPercent}, function(err, data) {
        core.cameraZoomed = data.zoomed;
        callback(err, data);
    });
};
core.focus = function(step, repeat, callback) {
    call('camera.ptp.focus', {step:step, repeat:repeat}, callback);
};
core.setEv = function(ev, options, callback) {
    call('camera.setEv', {ev:ev, options:options}, callback);
};
core.preview = function(callback) {
    call('camera.ptp.preview', {}, callback);
};
core.getSettings = function(callback) {
    call('camera.ptp.getSettings', {}, callback);
};
core.cameraList = function(callback) {
    call('camera.ptp.cameraList', {}, callback);
};
core.switchPrimary = function(cameraObject, callback) {
    call('camera.ptp.switchPrimary', {cameraObject:cameraObject}, callback);
};
core.capture = function(options, callback) {
    call('camera.ptp.capture', {options:options}, callback);
};
core.captureTest = function(callback) {
    call('camera.ptp.capture-test', {}, callback);
};
core.runSupportTest = function(callback) {
    call('camera.ptp.runSupportTest', {}, callback);
};
core.set = function(key, val, callback) {
    call('camera.ptp.set', {key:key, val:val}, callback);
};
core.mountSd = function(callback) {
    call('camera.ptp.mountSd', {}, function(err, res){
        core.sdMounted = res;
        callback(err, res)
    });
};
core.unmountSd = function(callback) {
    call('camera.ptp.unmountSd', {}, callback);
};

core.moveMotion = function(driver, motor, steps, callback) {
    call('motion.move', {driver:driver, motor:motor, steps:steps}, callback);
};

core.zeroMotion = function(driver, motor, callback) {
    call('motion.zero', {driver:driver, motor:motor}, callback);
};

core.motionStatusUpdate = function(callback) {
    call('motion.status', {}, callback);
};

core.moveMotionJoystick = function(driver, motor, speed, callback) {
    call('motion.joystick', {driver:driver, motor:motor, speed:speed}, callback);
};

core.getCurrentTimelapseFrames = function(cameraIndex, callback) {
    call('db.currentTimelapseFrames', {cameraIndex:cameraIndex}, callback);
};

var wdtInterval = null;
core.watchdogEnable = function(callback) {
    if(!wdtInterval) {
        wdtInterval = setInterval(core.watchdogEnable, 5000); // this will have the server kill this process if it ever gets stuck
    }
    call('watchdog.set', {pid:process.pid}, callback);
};

core.watchdogDisable = function(callback) {
    if(wdtInterval) {
        clearInterval(wdtInterval);
        wdtInterval = null;
    }
    call('watchdog.disable', {pid:process.pid}, function(err){
        callback && callback(err);
    });
};

core.resetBt = function(callback) {
    call('bt.reset', {}, callback);
};

defaultProgram = {
    rampMode: "fixed",
    intervalMode: "fixed",
    rampAlgorithm: "lum",
    interval: 5,
    dayInterval: 5,
    nightInterval: 35,
    frames: 300,
    destination: 'camera',
    nightCompensation: -1,
    isoMax: -6,
    isoMin:  0,
    rampParameters:  'S+I',
    apertureMax: -2,
    apertureMin:  -4,
    manualAperture: -5,
    hdrCount: 0,
    hdrStops: 1,
    exposurePlans: [],
    keyframes: [{
        focus: 0,
        ev: "not set",
        motor: {}
    }]
};

core.intervalometerStatus = {
    running: false,
    frames: 0,
    framesRemaining: 0,
    rampRate: 0,
    intervalMs: 0,
    message: "",
    rampEv: null,
    autoSettings: {
        paddingTimeMs: 5000
    }
}

core.moveTracking = function(axis, degrees, callback) {
    call('intervalometer.moveTracking', {axis:axis, degrees:degrees}, callback);
}

core.dynamicChange = function(parameter, newValue, frames, callback) {
    call('intervalometer.dynamicChange', {parameter:parameter, newValue:newValue, frames:frames}, callback);
}

core.loadProgram = function(program, callback) {
    if(!program.frames) program.frames = Infinity; // Infinity comes back as null from the DB
    if(program.keyframes) { // arrays come back as object in the VIEW db
        var kfs = [];
        for(var key in program.keyframes) {
            if(program.keyframes.hasOwnProperty(key)) {
                kfs.push(program.keyframes[key]);
            }
        }
        if(kfs.length > 0) program.keyframes = kfs;
    }
    if(program.exposurePlans) { // arrays come back as object in the VIEW db
        var plans = [];
        for(var key in program.exposurePlans) {
            if(program.exposurePlans.hasOwnProperty(key)) {
                plans.push(program.exposurePlans[key]);
            }
        }
        if(plans.length > 0) program.exposurePlans = plans;
    }

    core.currentProgram = _.extendOwn(defaultProgram, core.currentProgram, program);
    callback && callback();
}
core.loadProgram(defaultProgram);

core.stopIntervalometer = function(callback) {
    call('intervalometer.cancel', {}, callback);
}
core.startIntervalometer = function(program, callback) {
    power.performance('high');
    core.addGpsData(mcu.validCoordinates());
    call('intervalometer.run', {program:program}, callback);
}
core.addGpsData = function(gpsData, callback) {
    call('gps', {gpsData:gpsData}, callback);
}

mcu.on('gps', function(status){
    if(status == 2) {
        core.addGpsData(mcu.gps);
    }
});

module.exports = core;<|endoftext|>


<commit_before>'use strict';

// Get current license(s) & file status etc
var _ = require('lodash');
var colors = require('colors/safe');
var fs = require('fs');
var path = require('path');
var jsonFile = require('json-file-plus');
var packageJsonPath = path.join(process.cwd(), 'package.json');
var assert = require('assert');
var ini = require('node-ini');

var globalDefaults = require('../config.json');
var spdxLicensesPath = __dirname + '/../node_modules/spdx-license-list/licenses/';

// read node package.json
var packageJson;
console.log('exists file:', packageJsonPath);
if (fs.existsSync(packageJsonPath)) {
	try {
		packageJson = fs.readFileSync(packageJsonPath, 'utf8');
		packageJson = JSON.parse(packageJson);

	} catch(err) {
		console.log(colors.magenta('failed to open package.json'));
		console.log(err);
	}
}

function getCurrentAuthor() {
	if (packageJson && packageJson.author) {
		if (typeof packageJson.author === 'string') {
			var parseAuthors = require('parse-authors');
			var authors = parseAuthors(packageJson.author);
			if (authors.length) {
				return authors[0];
			}

		} else {
			return packageJson.author;
		}
	}

	if (globalDefaults.author) {
		return {
			name: globalDefaults.author,
			email: globalDefaults.email
		};
	}

	var author = {
		name: '',
		email: ''
	};

	var gitPath = path.join(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE, '.gitconfig');
	console.log('gity path:', gitPath);
	if (fs.existsSync(gitPath)) {
		var git = ini.parseSync(gitPath);
		if (git.user) {
			author.name = git.user.name;
			author.email = git.user.email;
		}
	}

	return author;
}

function getCurrentProject() {
	if (packageJson) {
		return {
			years: new Date().getFullYear(),
			name: packageJson.name,
			desc: packageJson.description
		};
	}

	var name = path.normalize(__dirname + '/../').split(path.sep);
	assert(name[name.length -1] === '');
	name = name[name.length - 2];
	return {
		years: new Date().getFullYear(),
		name: name,
		desc: ''
	};
}

function getCurrentLicense() {
	if (packageJson && packageJson.license) {
		return packageJson.license;
	}

	if (globalDefaults.license) {
		return globalDefaults.license;
	}

	return '';
}

var currentLicense = getCurrentLicense();
var currentAuthor = getCurrentAuthor();
var currentProject = getCurrentProject();

// Combine license jsons
var licenseModelBuilder = require('./licenseModelBuilder.js');
var licenses = licenseModelBuilder({
	spdx: require('spdx-license-list'),
	common: require('../licenses.json')
});

var licenseFileConfig = {
	names: ['LICENSE', 'COPYING'],
	exts: ['', '.md', '.txt'],
	defaultFileName: globalDefaults.defaultFileName || 'LICENSE'
};

function getLicenseFileName() {
	var existing;
	_.forEach(licenseFileConfig.names, function(name) {
		_.forEach(licenseFileConfig.exts, function(ext) {
			var fileName = path.join(process.cwd(), name + ext);
			if (fs.existsSync(fileName)) {
				existing = name + ext;
			}
		});
	});
	return existing || licenseFileConfig.defaultFileName;
}

var config;
var fileName = getLicenseFileName();
var filePath = path.join(process.cwd(), fileName);

module.exports = {
	getConfig: function(spdxlicenses) {
		config = {
			global: globalDefaults,
			fileName: fileName,
			fileExists: function() {
				return fs.existsSync(filePath);
			},
			license: this.getDetails(currentLicense),
			licenses: licenses,
			hasNpmPackage: packageJson !== undefined,
			packageJson: packageJson,
			defaults: {
				license: currentLicense,
				author: currentAuthor,
				project: currentProject
			},
			update: function(opts) {
				if (opts.force) {
					this.defaults.license = globalDefaults.license;
					opts.license = globalDefaults.license;

					if (opts._[0] === 'set' && fileName !== licenseFileConfig.defaultFileName) {
						// Zie uglyness
						fs.unlinkSync(filePath);

						fileName = licenseFileConfig.defaultFileName;
						config.fileName = fileName;
						filePath = path.join(process.cwd(), fileName);
					}

				} else if (opts.license) {
					this.defaults.license = opts.license;
				}

				if (opts.author) {
					this.defaults.author.name = opts.author;
				}
				if (opts.year) {
					this.defaults.project.years = opts.year;
				}
				if (opts.email) {
					this.defaults.author.email = opts.email;
				}
				if (opts.project) {
					this.defaults.project.name = opts.project;
				}
				if (opts.desc) {
					this.defaults.project.desc = opts.desc;
				}
			}
		};

		return config;
	},
	getMatches: function(needle, returnAll) {
		needle = needle.toLowerCase();

		var i;
		var list = [];
		var descMatches = [];

		var keys = Object.keys(licenses);
		for (i = 0; i < keys.length; i++) {
			if (needle === keys[i].toLowerCase()) {
				if (returnAll) {
					list.push(keys[i]);
					continue;
				} else {
					return [keys[i]];
				}
			}

			var lic = licenses[keys[i]];
			if (lic.alias) {
				var aliasRegex = new RegExp(lic.alias, 'i');
				if (needle.match(aliasRegex)) {
					if (returnAll) {
						list.push(keys[i]);
						continue;
					} else {
						return [keys[i]];
					}
				}
			}

			if (keys[i].toLowerCase().indexOf(needle) !== -1) {
				list.push(keys[i]);
			} else {
				assert(lic.name !== undefined, "lic.name undefined. (means a licenses.json key that does not exist in the spdx json)", lic);
				if (lic.name.toLowerCase().indexOf(needle) !== -1) {
					descMatches.push(keys[i]);
				}
			}
		}

		if (returnAll || list.length === 0) {
			return descMatches.concat(list);
		}
		return list;
	},
	getDetails: function(licenseKey, getFullText) {
		getFullText = getFullText || false;

		var lic = _.merge({
			key: licenseKey,
			valid: licenses[licenseKey] !== undefined
		}, licenses[licenseKey]);

		if (getFullText && lic.valid) {
			try {
				lic.full = fs.readFileSync(spdxLicensesPath + licenseKey +'.txt').toString();
				if (lic.header) {
					lic.header = new RegExp(lic.header).exec(lic.full)[0];
					if (lic.headerClean) {
						lic.header = lic.header.replace(new RegExp(lic.headerClean, 'mg'), '');
					}
					lic.header = replacePlaceHolders(lic.match, lic.replace, lic.header);
				} else {
					lic.full = replacePlaceHolders(lic.match, lic.replace, lic.full);
				}

			} catch(err) {
				console.log('Error reading ' + licenseKey + ' license content ', err);
			}
		}

		return lic;
	},
	updatePackageJson: function(licenseKey) {
		jsonFile(packageJsonPath, function (err, file) {
			file.set({
				license: licenseKey
			});

			file.save(function(err) {

			}).then(function () {
				console.log('Node package.json updated!');
			}).catch(function (err) {
				console.log('Whoops! Error updating package.json', err);
			});
		});
	},
	readLicenseFile: function() {
		return fs.readFileSync(filePath).toString();
	},
	writeLicense: function(license) {
		var doWrite = false;
		if (!config.fileExists()) {
			doWrite = true;

		} else {
			var currentContent = this.readLicenseFile();
			if (currentContent !== license.full) {
				doWrite = true;
				console.log('Overwriting existing ' + fileName + ' file');
			} else {
				console.log(fileName + ' file was up to date');
			}
		}

		if (doWrite) {
			try {
				fs.writeFileSync(filePath, license.full, 'utf8');
				console.log(fileName + ' written');
			} catch(err) {
				console.log('Error writing license file', err);
			}
		}
	},
	setGlobal: function(opts) {
		var paramsGiven = false;
		if (opts.author) {
			globalDefaults.author = opts.author;
			console.log('Default author name set to ', opts.author);
			paramsGiven = true;
		}
		if (opts.email) {
			globalDefaults.email = opts.email;
			console.log('Default author email set to ', opts.email);
			paramsGiven = true;
		}
		if (opts.license) {
			var matched = this.getMatches(opts.license);
			if (matched.length === 1) {
				globalDefaults.license = matched[0];
				console.log('Default license set to ', matched[0]);
				paramsGiven = true;
			} else {
				console.log('Couldn\'t set license: ' + opts.license);
			}
		}
		if (opts.defaultFileName && globalDefaults.defaultFileName !== opts.defaultFileName) {
			globalDefaults.defaultFileName = opts.defaultFileName;
			console.log('Default license filename set to ', opts.defaultFileName);
			paramsGiven = true;
		}

		if (paramsGiven === false) {
			console.log('No configuration passed...? Try: licenser config --author=yourname');
			return;
		}

		try {
			var globalConfigPath = path.normalize(__dirname + '/../config.json');
			console.log('Updating global settings file: ', globalConfigPath);
			fs.writeFileSync(globalConfigPath, JSON.stringify(globalDefaults, null, 2), 'utf8');
			console.log('Global settings updated!');
		} catch(err) {
			console.log('ERR writing ' + globalConfigPath, err);
		}
	}
};

function replacePlaceHolders(matcher, replacer, licenseText) {
	if (matcher) {
		var named = require('named-regexp').named;
		var re = named(new RegExp(matcher, 'g'));

		return re.replace(licenseText, function(matched) {
			return replacer
				.replace('$years', currentProject.years)
				.replace('$author', currentAuthor.name)
				.replace('$email', currentAuthor.email)
				.replace('$url', currentProject.url)
				.replace('$project', currentProject.name + ' - ' + currentProject.desc);
		});
	}
	return licenseText;
}<commit_msg>more information when using config command<commit_after>'use strict';

// Get current license(s) & file status etc
var _ = require('lodash');
var colors = require('colors/safe');
var fs = require('fs');
var path = require('path');
var jsonFile = require('json-file-plus');
var packageJsonPath = path.join(process.cwd(), 'package.json');
var assert = require('assert');
var ini = require('node-ini');

var globalDefaults = require('../config.json');
var spdxLicensesPath = __dirname + '/../node_modules/spdx-license-list/licenses/';

// read node package.json
var packageJson;
console.log('exists file:', packageJsonPath);
if (fs.existsSync(packageJsonPath)) {
	try {
		packageJson = fs.readFileSync(packageJsonPath, 'utf8');
		packageJson = JSON.parse(packageJson);

	} catch(err) {
		console.log(colors.magenta('failed to open package.json'));
		console.log(err);
	}
}

function getCurrentAuthor() {
	if (packageJson && packageJson.author) {
		if (typeof packageJson.author === 'string') {
			var parseAuthors = require('parse-authors');
			var authors = parseAuthors(packageJson.author);
			if (authors.length) {
				return authors[0];
			}

		} else {
			return packageJson.author;
		}
	}

	if (globalDefaults.author) {
		return {
			name: globalDefaults.author,
			email: globalDefaults.email
		};
	}

	var author = {
		name: '',
		email: ''
	};

	var gitPath = path.join(process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE, '.gitconfig');
	console.log('gity path:', gitPath);
	if (fs.existsSync(gitPath)) {
		var git = ini.parseSync(gitPath);
		if (git.user) {
			author.name = git.user.name;
			author.email = git.user.email;
		}
	}

	return author;
}

function getCurrentProject() {
	if (packageJson) {
		return {
			years: new Date().getFullYear(),
			name: packageJson.name,
			desc: packageJson.description
		};
	}

	var name = path.normalize(__dirname + '/../').split(path.sep);
	assert(name[name.length -1] === '');
	name = name[name.length - 2];
	return {
		years: new Date().getFullYear(),
		name: name,
		desc: ''
	};
}

function getCurrentLicense() {
	if (packageJson && packageJson.license) {
		return packageJson.license;
	}

	if (globalDefaults.license) {
		return globalDefaults.license;
	}

	return '';
}

var currentLicense = getCurrentLicense();
var currentAuthor = getCurrentAuthor();
var currentProject = getCurrentProject();

// Combine license jsons
var licenseModelBuilder = require('./licenseModelBuilder.js');
var licenses = licenseModelBuilder({
	spdx: require('spdx-license-list'),
	common: require('../licenses.json')
});

var licenseFileConfig = {
	names: ['LICENSE', 'COPYING'],
	exts: ['', '.md', '.txt'],
	defaultFileName: globalDefaults.defaultFileName || 'LICENSE'
};

function getLicenseFileName() {
	var existing;
	_.forEach(licenseFileConfig.names, function(name) {
		_.forEach(licenseFileConfig.exts, function(ext) {
			var fileName = path.join(process.cwd(), name + ext);
			if (fs.existsSync(fileName)) {
				existing = name + ext;
			}
		});
	});
	return existing || licenseFileConfig.defaultFileName;
}

var config;
var fileName = getLicenseFileName();
var filePath = path.join(process.cwd(), fileName);

module.exports = {
	getConfig: function(spdxlicenses) {
		config = {
			global: globalDefaults,
			fileName: fileName,
			fileExists: function() {
				return fs.existsSync(filePath);
			},
			license: this.getDetails(currentLicense),
			licenses: licenses,
			hasNpmPackage: packageJson !== undefined,
			packageJson: packageJson,
			defaults: {
				license: currentLicense,
				author: currentAuthor,
				project: currentProject
			},
			update: function(opts) {
				if (opts.force) {
					this.defaults.license = globalDefaults.license;
					opts.license = globalDefaults.license;

					if (opts._[0] === 'set' && fileName !== licenseFileConfig.defaultFileName) {
						// Zie uglyness
						fs.unlinkSync(filePath);

						fileName = licenseFileConfig.defaultFileName;
						config.fileName = fileName;
						filePath = path.join(process.cwd(), fileName);
					}

				} else if (opts.license) {
					this.defaults.license = opts.license;
				}

				if (opts.author) {
					this.defaults.author.name = opts.author;
				}
				if (opts.year) {
					this.defaults.project.years = opts.year;
				}
				if (opts.email) {
					this.defaults.author.email = opts.email;
				}
				if (opts.project) {
					this.defaults.project.name = opts.project;
				}
				if (opts.desc) {
					this.defaults.project.desc = opts.desc;
				}
			}
		};

		return config;
	},
	getMatches: function(needle, returnAll) {
		needle = needle.toLowerCase();

		var i;
		var list = [];
		var descMatches = [];

		var keys = Object.keys(licenses);
		for (i = 0; i < keys.length; i++) {
			if (needle === keys[i].toLowerCase()) {
				if (returnAll) {
					list.push(keys[i]);
					continue;
				} else {
					return [keys[i]];
				}
			}

			var lic = licenses[keys[i]];
			if (lic.alias) {
				var aliasRegex = new RegExp(lic.alias, 'i');
				if (needle.match(aliasRegex)) {
					if (returnAll) {
						list.push(keys[i]);
						continue;
					} else {
						return [keys[i]];
					}
				}
			}

			if (keys[i].toLowerCase().indexOf(needle) !== -1) {
				list.push(keys[i]);
			} else {
				assert(lic.name !== undefined, "lic.name undefined. (means a licenses.json key that does not exist in the spdx json)", lic);
				if (lic.name.toLowerCase().indexOf(needle) !== -1) {
					descMatches.push(keys[i]);
				}
			}
		}

		if (returnAll || list.length === 0) {
			return descMatches.concat(list);
		}
		return list;
	},
	getDetails: function(licenseKey, getFullText) {
		getFullText = getFullText || false;

		var lic = _.merge({
			key: licenseKey,
			valid: licenses[licenseKey] !== undefined
		}, licenses[licenseKey]);

		if (getFullText && lic.valid) {
			try {
				lic.full = fs.readFileSync(spdxLicensesPath + licenseKey +'.txt').toString();
				if (lic.header) {
					lic.header = new RegExp(lic.header).exec(lic.full)[0];
					if (lic.headerClean) {
						lic.header = lic.header.replace(new RegExp(lic.headerClean, 'mg'), '');
					}
					lic.header = replacePlaceHolders(lic.match, lic.replace, lic.header);
				} else {
					lic.full = replacePlaceHolders(lic.match, lic.replace, lic.full);
				}

			} catch(err) {
				console.log('Error reading ' + licenseKey + ' license content ', err);
			}
		}

		return lic;
	},
	updatePackageJson: function(licenseKey) {
		jsonFile(packageJsonPath, function (err, file) {
			file.set({
				license: licenseKey
			});

			file.save(function(err) {

			}).then(function () {
				console.log('Node package.json updated!');
			}).catch(function (err) {
				console.log('Whoops! Error updating package.json', err);
			});
		});
	},
	readLicenseFile: function() {
		return fs.readFileSync(filePath).toString();
	},
	writeLicense: function(license) {
		var doWrite = false;
		if (!config.fileExists()) {
			doWrite = true;

		} else {
			var currentContent = this.readLicenseFile();
			if (currentContent !== license.full) {
				doWrite = true;
				console.log('Overwriting existing ' + fileName + ' file');
			} else {
				console.log(fileName + ' file was up to date');
			}
		}

		if (doWrite) {
			try {
				fs.writeFileSync(filePath, license.full, 'utf8');
				console.log(fileName + ' written');
			} catch(err) {
				console.log('Error writing license file', err);
			}
		}
	},
	setGlobal: function(opts) {
		function getVerb(wasSame) {
			return !wasSame ? 'set to' : 'was already';
		}

		var paramsGiven = false;
		if (opts.author) {
			console.log('Default author name ' + getVerb(globalDefaults.author === opts.author), opts.author);
			globalDefaults.author = opts.author;
			paramsGiven = true;
		}
		if (opts.email) {
			console.log('Default author email ' + getVerb(globalDefaults.email === opts.email), opts.email);
			globalDefaults.email = opts.email;
			paramsGiven = true;
		}
		if (opts.license) {
			var matched = this.getMatches(opts.license);
			if (matched.length === 1) {
				console.log('Default license ' + getVerb(globalDefaults.license === opts.license), matched[0]);
				globalDefaults.license = matched[0];
				paramsGiven = true;
			} else {
				console.log('Couldn\'t set license: ' + opts.license);
			}
		}
		if (opts.defaultFileName) {
			console.log('Default license filename ' + getVerb(globalDefaults.defaultFileName === opts.defaultFileName), opts.defaultFileName);
			globalDefaults.defaultFileName = opts.defaultFileName;
			paramsGiven = true;
		}

		if (paramsGiven === false) {
			console.log('No configuration passed...? Try: licenser config --author=yourname');
			return;
		}

		try {
			var globalConfigPath = path.normalize(__dirname + '/../config.json');
			console.log('Updating global settings file: ', globalConfigPath);
			fs.writeFileSync(globalConfigPath, JSON.stringify(globalDefaults, null, 2), 'utf8');
			console.log('Global settings updated!');
		} catch(err) {
			console.log('ERR writing ' + globalConfigPath, err);
		}
	}
};

function replacePlaceHolders(matcher, replacer, licenseText) {
	if (matcher) {
		var named = require('named-regexp').named;
		var re = named(new RegExp(matcher, 'g'));

		return re.replace(licenseText, function(matched) {
			return replacer
				.replace('$years', currentProject.years)
				.replace('$author', currentAuthor.name)
				.replace('$email', currentAuthor.email)
				.replace('$url', currentProject.url)
				.replace('$project', currentProject.name + ' - ' + currentProject.desc);
		});
	}
	return licenseText;
}<|endoftext|>


<commit_before>var naf = require('../NafIndex');

// @TODO if aframevr/aframe#3042 gets merged, this should just delegate to the aframe sound component
AFRAME.registerComponent('networked-audio-source', {
  schema: {
    positional: { default: true }
  },

  init: function () {
    this.listener = null;
    this.stream = null;

    this._setMediaStream = this._setMediaStream.bind(this);

    const networkedEl = NAF.utils.getNetworkedEntity(this.el);
    const ownerId = networkedEl && networkedEl.components.networked.data.owner;
    if (ownerId) {
      NAF.connection.adapter.getMediaStream(ownerId)
        .then(this._setMediaStream)
        .catch((e) => naf.log.error(`Error getting media stream for ${ownerId}`, e));
    } else if(ownerId === '') {
      // Correctly configured local entity, perhaps do something here for enabling debug audio loopback
    } else {
      naf.log.error('[networked-audio-source] must be added on an entity, or a child of an entity, with the [networked] component.');
    }
  },

  _setMediaStream(newStream) {
    if(!this.sound) {
      this.setupSound();
    }

    if(newStream != this.stream) {
      if(this.stream) {
        this.sound.disconnect();
      }
      if(newStream) {
        // Chrome seems to require a MediaStream be attached to an AudioElement before AudioNodes work correctly
        this.audioEl = new Audio();
        this.audioEl.srcObject = newStream;

        this.sound.setNodeSource(this.sound.context.createMediaStreamSource(newStream));
      }
      this.stream = newStream;
    }
  },

  remove: function() {
    if (!this.sound) return;

    this.el.removeObject3D(this.attrName);
    if (this.stream) {
      this.sound.disconnect();
    }
  },

  setupSound: function() {
    var el = this.el;
    var sceneEl = el.sceneEl;

    if (this.sound) {
      el.removeObject3D(this.attrName);
    }

    if (!sceneEl.audioListener) {
      sceneEl.audioListener = new THREE.AudioListener();
      sceneEl.camera && sceneEl.camera.add(sceneEl.audioListener);
      sceneEl.addEventListener('camera-set-active', function(evt) {
        evt.detail.cameraEl.getObject3D('camera').add(sceneEl.audioListener);
      });
    }
    this.listener = sceneEl.audioListener;

    this.sound = this.data.positional
      ? new THREE.PositionalAudio(this.listener)
      : new THREE.Audio(this.listener);
    el.setObject3D(this.attrName, this.sound);
  }
});
<commit_msg>fix playback on IOS<commit_after>var naf = require('../NafIndex');

// @TODO if aframevr/aframe#3042 gets merged, this should just delegate to the aframe sound component
AFRAME.registerComponent('networked-audio-source', {
  schema: {
    positional: { default: true }
  },

  init: function () {
    this.listener = null;
    this.stream = null;

    this._setMediaStream = this._setMediaStream.bind(this);

    const networkedEl = NAF.utils.getNetworkedEntity(this.el);
    const ownerId = networkedEl && networkedEl.components.networked.data.owner;
    if (ownerId) {
      NAF.connection.adapter.getMediaStream(ownerId)
        .then(this._setMediaStream)
        .catch((e) => naf.log.error(`Error getting media stream for ${ownerId}`, e));
    } else if(ownerId === '') {
      // Correctly configured local entity, perhaps do something here for enabling debug audio loopback
    } else {
      naf.log.error('[networked-audio-source] must be added on an entity, or a child of an entity, with the [networked] component.');
    }
  },

  _setMediaStream(newStream) {
    if(!this.sound) {
      this.setupSound();
    }

    if(newStream != this.stream) {
      if(this.stream) {
        this.sound.disconnect();
      }
      if(newStream) {
        // Chrome seems to require a MediaStream be attached to an AudioElement before AudioNodes work correctly
        this.audioEl = new Audio();
        this.audioEl.setAttribute("autoplay", "autoplay");
        this.audioEl.setAttribute("playsinline", "playsinline");
        this.audioEl.srcObject = newStream;

        this.sound.setNodeSource(this.sound.context.createMediaStreamSource(newStream));
      }
      this.stream = newStream;
    }
  },

  remove: function() {
    if (!this.sound) return;

    this.el.removeObject3D(this.attrName);
    if (this.stream) {
      this.sound.disconnect();
    }
  },

  setupSound: function() {
    var el = this.el;
    var sceneEl = el.sceneEl;

    if (this.sound) {
      el.removeObject3D(this.attrName);
    }

    if (!sceneEl.audioListener) {
      sceneEl.audioListener = new THREE.AudioListener();
      sceneEl.camera && sceneEl.camera.add(sceneEl.audioListener);
      sceneEl.addEventListener('camera-set-active', function(evt) {
        evt.detail.cameraEl.getObject3D('camera').add(sceneEl.audioListener);
      });
    }
    this.listener = sceneEl.audioListener;

    this.sound = this.data.positional
      ? new THREE.PositionalAudio(this.listener)
      : new THREE.Audio(this.listener);
    el.setObject3D(this.attrName, this.sound);
  }
});
<|endoftext|>


<commit_before>// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
 * @fileoverview Defines the DSA PUBKEY type used in the OTR protocol.
 *
 * @author rcc@google.com (Ryan Chan)
 */

goog.provide('e2e.otr.pubkey.Dsa');

goog.require('e2e.otr');
goog.require('e2e.otr.pubkey.Pubkey');

/**
 * An OTRv3 DSA PUBKEY.
 * @constructor
 * @extends {e2e.otr.pubkey.Pubkey}
 * @param {!e2e.ByteArray} p DSA public key parameter p.
 * @param {!e2e.ByteArray} q DSA public key parameter q.
 * @param {!e2e.ByteArray} g DSA public key parameter g.
 * @param {!e2e.ByteArray} y DSA public key parameter y.
 */
e2e.otr.pubkey.Dsa = function(p, q, g, y) {
  goog.base(this);
  this.p_ = p;
  this.q_ = q;
  this.g_ = g;
  this.y_ = y;
};
goog.inherits(e2e.otr.pubkey.Dsa, e2e.otr.pubkey.Pubkey);

/**
 * Specifies the type of the public key.
 * @type {!e2e.otr.Short}
 */
e2e.otr.pubkey.Dsa.PUBKEY_TYPE = e2e.otr.constants.PubkeyType.DSA;

/** @inheritDoc */
e2e.otr.pubkey.Dsa.prototype.serializePubkey = function() {
  return e2e.otr.serializeBytes([
    new e2e.otr.Mpi(new Uint8Array(this.p_)),
    new e2e.otr.Mpi(new Uint8Array(this.q_)),
    new e2e.otr.Mpi(new Uint8Array(this.g_)),
    new e2e.otr.Mpi(new Uint8Array(this.y_))
  ]);
};

/**
 * Deconstructs DSA PUBKEY into p, q, g, and y.
 * @return {!e2e.signer.key.DsaPublicKey} The object containing p, q, g, and y.
 */
e2e.otr.pubkey.Dsa.prototype.deconstruct = function() {
  return {
    p: goog.array.clone(this.p_),
    q: goog.array.clone(this.q_),
    g: goog.array.clone(this.g_),
    y: goog.array.clone(this.y_)
  };
};

/**
 * Extracts a DSA PUBKEY from the body, and returns the DSA PUBKEY.
 * @param {!Uint8Array} body The body from where to extract the data.
 * @return {!e2e.otr.pubkey.Dsa} The generated packet.
 */
e2e.otr.pubkey.Dsa.parse = function(body) {
  var iter = new e2e.otr.util.Iterator(body);
  throw new e2e.otr.error.NotImplementedError('Not yet implemented.');
};

e2e.otr.pubkey.Pubkey.add(e2e.otr.pubkey.Dsa);
<commit_msg>Dsa Pubkey takes e2e.signer.key.DsaPublicKey for constructor ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=73725670<commit_after>// Copyright 2014 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
 * @fileoverview Defines the DSA PUBKEY type used in the OTR protocol.
 *
 * @author rcc@google.com (Ryan Chan)
 */

goog.provide('e2e.otr.pubkey.Dsa');

goog.require('e2e.otr');
goog.require('e2e.otr.pubkey.Pubkey');

/**
 * An OTRv3 DSA PUBKEY.
 * @constructor
 * @extends {e2e.otr.pubkey.Pubkey}
 * @param {!e2e.signer.key.DsaPublicKey} key DSA public key object.
 */
e2e.otr.pubkey.Dsa = function(key) {
  goog.base(this);
  this.p_ = goog.array.clone(key.p);
  this.q_ = goog.array.clone(key.q);
  this.g_ = goog.array.clone(key.g);
  this.y_ = goog.array.clone(key.y);
};
goog.inherits(e2e.otr.pubkey.Dsa, e2e.otr.pubkey.Pubkey);

/**
 * Specifies the type of the public key.
 * @type {!e2e.otr.Short}
 */
e2e.otr.pubkey.Dsa.PUBKEY_TYPE = e2e.otr.constants.PubkeyType.DSA;

/** @inheritDoc */
e2e.otr.pubkey.Dsa.prototype.serializePubkey = function() {
  return e2e.otr.serializeBytes([
    new e2e.otr.Mpi(new Uint8Array(this.p_)),
    new e2e.otr.Mpi(new Uint8Array(this.q_)),
    new e2e.otr.Mpi(new Uint8Array(this.g_)),
    new e2e.otr.Mpi(new Uint8Array(this.y_))
  ]);
};

/**
 * Deconstructs DSA PUBKEY into p, q, g, and y.
 * @return {!e2e.signer.key.DsaPublicKey} The object containing p, q, g, and y.
 */
e2e.otr.pubkey.Dsa.prototype.deconstruct = function() {
  return {
    p: goog.array.clone(this.p_),
    q: goog.array.clone(this.q_),
    g: goog.array.clone(this.g_),
    y: goog.array.clone(this.y_)
  };
};

/**
 * Extracts a DSA PUBKEY from the body, and returns the DSA PUBKEY.
 * @param {!Uint8Array} body The body from where to extract the data.
 * @return {!e2e.otr.pubkey.Dsa} The generated packet.
 */
e2e.otr.pubkey.Dsa.parse = function(body) {
  var iter = new e2e.otr.util.Iterator(body);
  throw new e2e.otr.error.NotImplementedError('Not yet implemented.');
};

e2e.otr.pubkey.Pubkey.add(e2e.otr.pubkey.Dsa);
<|endoftext|>


<commit_before>import React from 'react';
import { StyleSheet, Text, View, ActivityIndicator } from 'react-native';
import { List, ListItem, Button } from 'react-native-elements';

import { colors, fonts } from 'config';

type Props = {
  loading: boolean,
  title: React.Element,
  children?: React.Element<*>,
  showButton: boolean,
  buttonTitle: string,
  noOuterBorders: boolean,
  noItems: boolean,
  noItemsMessage: string,
  buttonAction: Function,
};

const styles = StyleSheet.create({
  section: {
    marginTop: 15,
  },
  topHeader: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  sectionTitle: {
    color: colors.black,
    padding: 15,
    ...fonts.fontPrimaryBold,
  },
  listTitle: {
    color: colors.black,
    ...fonts.fontPrimary,
  },
  button: {
    backgroundColor: colors.white,
    borderColor: colors.primaryDark,
    borderWidth: 1,
    borderRadius: 3,
    paddingVertical: 5,
    paddingHorizontal: 10,
    marginTop: -8,
  },
  list: {
    marginTop: 0,
  },
  noOuterBorders: {
    borderTopWidth: 0,
    borderBottomWidth: 0,
  },
  loadingIcon: {
    marginVertical: 20,
  },
});

export const SectionList = ({
  loading,
  title,
  showButton,
  buttonTitle,
  buttonAction,
  noOuterBorders,
  noItems,
  noItemsMessage,
  children,
}: Props) => {
  let listDisplay;

  if (loading) {
    listDisplay = (
      <ActivityIndicator animating={loading} style={styles.loadingIcon} />
    );
  } else if (noItems) {
    listDisplay = (
      <ListItem
        title={noItemsMessage}
        titleStyle={styles.listTitle}
        hideChevron
      />
    );
  } else {
    listDisplay = children;
  }

  let sectionTitle = '';

  if (typeof title === 'string') {
    sectionTitle = <Text style={styles.sectionTitle}>{title}</Text>;
  } else {
    sectionTitle = <View style={{ padding: 15 }}>{title}</View>;
  }

  return (
    <View style={styles.section}>
      <View style={styles.topHeader}>
        {sectionTitle}

        {showButton &&
          !loading && (
            <Button
              title={buttonTitle}
              textStyle={fonts.fontPrimarySemiBold}
              fontSize={13}
              color={showButton ? colors.primaryDark : colors.white}
              buttonStyle={styles.button}
              onPress={buttonAction}
            />
          )}
      </View>
      <List
        containerStyle={[styles.list, noOuterBorders && styles.noOuterBorders]}
      >
        {listDisplay}
      </List>
    </View>
  );
};

SectionList.defaultProps = {
  children: null,
};
<commit_msg>fix: fix section list button height (#545)<commit_after>import React from 'react';
import { StyleSheet, Text, View, ActivityIndicator } from 'react-native';
import { List, ListItem, Button } from 'react-native-elements';

import { colors, fonts } from 'config';

type Props = {
  loading: boolean,
  title: React.Element,
  children?: React.Element<*>,
  showButton: boolean,
  buttonTitle: string,
  noOuterBorders: boolean,
  noItems: boolean,
  noItemsMessage: string,
  buttonAction: Function,
};

const styles = StyleSheet.create({
  section: {
    marginTop: 15,
  },
  topHeader: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  sectionTitle: {
    color: colors.black,
    padding: 15,
    ...fonts.fontPrimaryBold,
  },
  listTitle: {
    color: colors.black,
    ...fonts.fontPrimary,
  },
  button: {
    backgroundColor: colors.white,
    borderColor: colors.primaryDark,
    borderWidth: 1,
    borderRadius: 3,
    paddingVertical: 5,
    paddingHorizontal: 10,
  },
  list: {
    marginTop: 0,
  },
  noOuterBorders: {
    borderTopWidth: 0,
    borderBottomWidth: 0,
  },
  loadingIcon: {
    marginVertical: 20,
  },
});

export const SectionList = ({
  loading,
  title,
  showButton,
  buttonTitle,
  buttonAction,
  noOuterBorders,
  noItems,
  noItemsMessage,
  children,
}: Props) => {
  let listDisplay;

  if (loading) {
    listDisplay = (
      <ActivityIndicator animating={loading} style={styles.loadingIcon} />
    );
  } else if (noItems) {
    listDisplay = (
      <ListItem
        title={noItemsMessage}
        titleStyle={styles.listTitle}
        hideChevron
      />
    );
  } else {
    listDisplay = children;
  }

  let sectionTitle = '';

  if (typeof title === 'string') {
    sectionTitle = <Text style={styles.sectionTitle}>{title}</Text>;
  } else {
    sectionTitle = <View style={{ padding: 15 }}>{title}</View>;
  }

  return (
    <View style={styles.section}>
      <View style={styles.topHeader}>
        {sectionTitle}

        {showButton &&
          !loading && (
            <Button
              title={buttonTitle}
              textStyle={fonts.fontPrimarySemiBold}
              fontSize={13}
              color={showButton ? colors.primaryDark : colors.white}
              buttonStyle={styles.button}
              onPress={buttonAction}
            />
          )}
      </View>
      <List
        containerStyle={[styles.list, noOuterBorders && styles.noOuterBorders]}
      >
        {listDisplay}
      </List>
    </View>
  );
};

SectionList.defaultProps = {
  children: null,
};
<|endoftext|>


<commit_before>export { InputsOutputs };

import * as FloatValue from "../../Unpacker/FloatValue.js";
import * as ValueDesc from "../../Unpacker/ValueDesc.js";
//import * as Weights from "../../Unpacker/Weights.js";

/**
 * Element value bounds (per channel) for inputs and outputs of an operation.
 *
 *
 * @member {FloatValue.BoundsArray[]} inputs
 *   The element value bounds (per channel) of all inputs (i.e. the domain of the operation). This array (which is past into
 * constructor) will be kept (not cloned) directly. So caller should not modify them.
 *
 * @member {number} inputTensorCount
 *   How many input tensors (i.e. this.inputs.length).
 *
 * @member {FloatValue.BoundsArray} input0
 *   The element value bounds (per channel) of 1st input (i.e. this.inputs[ 0 ]).
 *
 * @member {FloatValue.BoundsArray} input1
 *   The element value bounds (per channel) of 2nd input (i.e. this.inputs[ 1 ]).
 *
 * @member {number} inputChannelCount0
 *   The channel count of 1st input (i.e. this.input0.length).
 *
 * @member {number} inputChannelCount1
 *   The channel count of 2nd input (i.e. this.input1.length).
 *
 * @member {FloatValue.BoundsArray[]} outputs
 *   The element value bounds (per channel) of all outputs (i.e. the range of the operation). The array is created by constructor
 * according to outputChannelCount0 and outputChannelCount1.
 *
 * @member {number} outputTensorCount
 *   How many output tensors (i.e. this.outputs.length).
 *
 * @member {FloatValue.BoundsArray} output0
 *   The element value bounds (per channel) of 1st output (i.e. this.outputs[ 0 ]).
 *
 * @member {FloatValue.BoundsArray} output1
 *   The element value bounds (per channel) of 2nd output (i.e. this.outputs[ 1 ]).
 *
 * @member {number} outputChannelCount0
 *   The channel count of 1st output (i.e. this.output0.length).
 *
 * @member {number} outputChannelCount1
 *   The channel count of 2nd output (i.e. this.output1.length).
 */
class InputsOutputs {

  /**
   */
  constructor( inputs, outputChannelCount0, outputChannelCount1 ) {
    this.inputs = inputs;

    // Determine outputs array.
    if ( outputChannelCount0 > 0 ) {
      if ( outputChannelCount1 > 0 ) { // Two outputs.
        this.outputs = [ new FloatValue.BoundsArray( outputChannelCount0 ), new FloatValue.BoundsArray( outputChannelCount1 ) ];

      } else { // ( outputChannelCount1 <= 0 ), One output.
        this.outputs = [ new FloatValue.BoundsArray( outputChannelCount0 ) ];
      }

    } else { // ( outputChannelCount0 <= 0 ), Illegal.

      tf.util.assert( ( ( outputChannelCount0 <= 0 ) && ( outputChannelCount1 <= 0 ) ),
        `BoundsArraySet.InputsOutputs.constructor(): `
          + `output0 must exist (i.e. outputChannelCount0 ( ${outputChannelCount0} ) must > 0 ).`
      );
    }
  }

  /**
   * @return {InputsOutputs}
   *   Return a newly created InputsOutputs which is a copy of this InputsOutputs. The this.inputs will just past
   * to new InputsOutputs (i.e. NOT copied). But the this.outputs will be copied.
   */
  clone() {
    let result = new InputsOutputs( this.inputs, this.outputChannelCount0, this.outputChannelCount1 );

//!!! ...unfinished... (2022/04/11)
    result.set_byBoundsArraySet( this );
    return result;
  }

  /**
   * @param {FloatValue.Bounds} aBounds
   *   Set all this.outputs[] to the same as the specified aBounds.
   *
   * @return {InputsOutputs}
   *   Return this (modified) object.
   */
  set_outputs_all_byBounds( aBounds ) {
    for ( let outTensorIndex = 0; outTensorIndex < this.outputs.length; ++outTensorIndex ) {
      this.outputs[ outTensorIndex ].set_all_byBounds( aBounds );
    }
    return this;
  }

  /**
   * @param {BoundsArray} outputBoundsArray
   *   The BoundsArray to be copied to all .outputs[].
   *
   * @return {InputsOutputs}
   *   Return this (modified) object.
   */
  set_outputs_all_byBoundsArray( outputBoundsArray ) {
    for ( let outTensorIndex = 0; outTensorIndex < this.outputs.length; ++outTensorIndex ) {
      this.outputs[ outTensorIndex ].set_all_byBoundsArray( outputBoundsArray );
    }
    return this;
  }

  /**
   * Set .outputs[] by .input[ 0 ].
   *
   * @return {InputsOutputs}
   *   Return this (modified) object.
   */
  set_outputs_all_byBoundsArray_input0() {
    for ( let outTensorIndex = 0; outTensorIndex < this.outputs.length; ++outTensorIndex ) {
      this.outputs[ outTensorIndex ].set_all_byBoundsArray( this.input[ 0 ] );
    }
    return this;
  }

  /**
   * Set .outputs[] by concatenate .input[ 0 ] and .input[ 1 ].
   *
   * @return {InputsOutputs}
   *   Return this (modified) object.
   */
  set_outputs_all_byBoundsArray_concat_input0_input1() {
    let rLength = this.inputs[ 0 ].length + this.inputs[ 1 ].length;

    for ( let outTensorIndex = 0; outTensorIndex < this.outputs.length; ++outTensorIndex ) {
      this.outputs[ outTensorIndex ].length = rLength;
      this.outputs[ outTensorIndex ].set_all_byBoundsArray_concat_input0_input1( this.inputs[ 0 ], this.inputs[ 1 ] );
    }
    return this;
  }

//!!! ...unfinished... (2022/04/11)

  /**
   * @param {BoundsArraySet.InputsOutputs} aBoundsArraySet
   *   The BoundsArraySet to be copied. Precondition: ( this.outputs.length == aBoundsArraySet.outputs.length ).
   *
   * @return {InputsOutputs}
   *   Return this (modified) object which is copied from aBoundsArraySet.
   */
  set_outputs_all_byBoundsArraySet( aBoundsArraySet ) {
    for ( let outTensorIndex = 0; outTensorIndex < this.outputs.length; ++outTensorIndex ) {
      this.outputs[ outTensorIndex ].set_outputs_all_byBoundsArray( this.outputs[ outTensorIndex ] );
    }

    this.set_outputs_all_byBoundsArray( aBoundsArraySet.outputs );

    this.afterUndoPreviousActivationEscaping.set_all_byBoundsArray( aBoundsArraySet.afterUndoPreviousActivationEscaping );
    this.afterFilter                        .set_all_byBoundsArray( aBoundsArraySet.afterFilter );
    this.afterBias                          .set_all_byBoundsArray( aBoundsArraySet.afterBias );
    this.afterActivationEscaping            .set_all_byBoundsArray( aBoundsArraySet.afterActivationEscaping );
    this.afterActivation                    .set_all_byBoundsArray( aBoundsArraySet.afterActivation );
    this.activationEscaping_ScaleArraySet.set_byScaleArraySet( aBoundsArraySet.activationEscaping_ScaleArraySet );

    for ( let i = 0; i < this.bPassThrough.length; ++i ) {
      this.bPassThrough[ i ] = aBoundsArraySet.bPassThrough[ i ];
    }

    return this;
  }

  get inputTensorCount() { return this.inputs.length; }

  get input0() { return this.inputs[ 0 ]; }
  get input1() { return this.inputs[ 1 ]; }

  get inputChannelCount0() { return this.input0.length; }
  get inputChannelCount1() { return this.input1.length; }

  get outputTensorCount() { return this.outputs.length; }

  get output0() { return this.outputs[ 0 ]; }
  get output1() { return this.outputs[ 1 ]; }

  get outputChannelCount0() { return this.output0.length; }
  get outputChannelCount1() { return this.output1.length; }

}

<commit_msg>Update InputsOutputs.js<commit_after>export { InputsOutputs };

import * as FloatValue from "../../Unpacker/FloatValue.js";

/**
 * Element value bounds (per channel) for inputs and outputs of an operation.
 *
 *
 * @member {FloatValue.BoundsArray[]} inputs
 *   The element value bounds (per channel) of all inputs (i.e. the domain of the operation). This array (which is past into
 * constructor) will be kept (not cloned) directly. So caller should not modify them.
 *
 * @member {number} inputTensorCount
 *   How many input tensors (i.e. this.inputs.length).
 *
 * @member {FloatValue.BoundsArray} input0
 *   The element value bounds (per channel) of 1st input (i.e. this.inputs[ 0 ]).
 *
 * @member {FloatValue.BoundsArray} input1
 *   The element value bounds (per channel) of 2nd input (i.e. this.inputs[ 1 ]).
 *
 * @member {number} inputChannelCount0
 *   The channel count of 1st input (i.e. this.input0.length).
 *
 * @member {number} inputChannelCount1
 *   The channel count of 2nd input (i.e. this.input1.length).
 *
 * @member {FloatValue.BoundsArray[]} outputs
 *   The element value bounds (per channel) of all outputs (i.e. the range of the operation). The array is created by constructor
 * according to outputChannelCount0 and outputChannelCount1.
 *
 * @member {number} outputTensorCount
 *   How many output tensors (i.e. this.outputs.length).
 *
 * @member {FloatValue.BoundsArray} output0
 *   The element value bounds (per channel) of 1st output (i.e. this.outputs[ 0 ]).
 *
 * @member {FloatValue.BoundsArray} output1
 *   The element value bounds (per channel) of 2nd output (i.e. this.outputs[ 1 ]).
 *
 * @member {number} outputChannelCount0
 *   The channel count of 1st output (i.e. this.output0.length).
 *
 * @member {number} outputChannelCount1
 *   The channel count of 2nd output (i.e. this.output1.length).
 */
class InputsOutputs {

  /**
   */
  constructor( inputs, outputChannelCount0, outputChannelCount1 ) {
    this.inputs = inputs;

    // Determine outputs array.
    if ( outputChannelCount0 > 0 ) {
      if ( outputChannelCount1 > 0 ) { // Two outputs.
        this.outputs = [ new FloatValue.BoundsArray( outputChannelCount0 ), new FloatValue.BoundsArray( outputChannelCount1 ) ];

      } else { // ( outputChannelCount1 <= 0 ), One output.
        this.outputs = [ new FloatValue.BoundsArray( outputChannelCount0 ) ];
      }

    } else { // ( outputChannelCount0 <= 0 ), Illegal.

      tf.util.assert( ( ( outputChannelCount0 <= 0 ) && ( outputChannelCount1 <= 0 ) ),
        `BoundsArraySet.InputsOutputs.constructor(): `
          + `output0 must exist (i.e. outputChannelCount0 ( ${outputChannelCount0} ) must > 0 ).`
      );
    }
  }

  /**
   * @return {InputsOutputs}
   *   Return a newly created InputsOutputs which is a copy of this InputsOutputs. The this.inputs will just past
   * to new InputsOutputs (i.e. NOT copied). But the this.outputs will be copied.
   */
  clone() {
    let result = new InputsOutputs( this.inputs, this.outputChannelCount0, this.outputChannelCount1 );
    result.set_outputs_all_byBoundsArraySet( this );
    return result;
  }

  /**
   * @param {FloatValue.Bounds} aBounds
   *   Set all .outputs[] to the same as the specified aBounds.
   *
   * @return {InputsOutputs}
   *   Return this (modified) object.
   */
  set_outputs_all_byBounds( aBounds ) {
    for ( let outTensorIndex = 0; outTensorIndex < this.outputs.length; ++outTensorIndex ) {
      this.outputs[ outTensorIndex ].set_all_byBounds( aBounds );
    }
    return this;
  }

  /**
   * @param {BoundsArray} outputBoundsArray
   *   The BoundsArray to be copied to all .outputs[].
   *
   * @return {InputsOutputs}
   *   Return this (modified) object.
   */
  set_outputs_all_byBoundsArray( outputBoundsArray ) {
    for ( let outTensorIndex = 0; outTensorIndex < this.outputs.length; ++outTensorIndex ) {
      this.outputs[ outTensorIndex ].set_all_byBoundsArray( outputBoundsArray );
    }
    return this;
  }

  /**
   * @param {BoundsArraySet.InputsOutputs} aBoundsArraySet
   *   The BoundsArraySet to be copied. Precondition: ( this.outputs.length == aBoundsArraySet.outputs.length ).
   *
   * @return {InputsOutputs}
   *   Return this (modified) object which is copied from aBoundsArraySet.
   */
  set_outputs_all_byBoundsArraySet( aBoundsArraySet ) {
    for ( let outTensorIndex = 0; outTensorIndex < this.outputs.length; ++outTensorIndex ) {
      this.outputs[ outTensorIndex ].set_outputs_all_byBoundsArray( this.outputs[ outTensorIndex ] );
    }
    return this;
  }

  /**
   * Set .outputs[] by .input[ 0 ].
   *
   * @return {InputsOutputs}
   *   Return this (modified) object.
   */
  set_outputs_all_byBoundsArray_input0() {
    for ( let outTensorIndex = 0; outTensorIndex < this.outputs.length; ++outTensorIndex ) {
      this.outputs[ outTensorIndex ].set_all_byBoundsArray( this.input[ 0 ] );
    }
    return this;
  }

  /**
   * Set .outputs[] by concatenating .input[ 0 ] and .input[ 1 ].
   *
   * @return {InputsOutputs}
   *   Return this (modified) object.
   */
  set_outputs_all_byBoundsArray_concat_input0_input1() {
    let rLength = this.inputs[ 0 ].length + this.inputs[ 1 ].length;

    for ( let outTensorIndex = 0; outTensorIndex < this.outputs.length; ++outTensorIndex ) {
      this.outputs[ outTensorIndex ].length = rLength;
      this.outputs[ outTensorIndex ].set_all_byBoundsArray_concat_input0_input1( this.inputs[ 0 ], this.inputs[ 1 ] );
    }
    return this;
  }

  /**
   * Set .outputs[ 0 ] and .outputs[ 1 ] by splitting .input[ 0 ]. If .outputs[ 1 ] does not exist, it will be created. The length
   * of both .outputs[ 0 ] and .outputs[ 1 ] will be modified.
   *
   * @return {InputsOutputs}
   *   Return this (modified) object.
   */
  set_outputs_all_byBoundsArray_split_input0() {

    if ( !this.outputs[ 1 ] )
      this.outputs[ 1 ] = new FloatValue.BoundsArray( 0 );

    this.inputs[ 0 ].split_to_lowerHalf_higherHalf( this.outputs[ 0 ], this.outputs[ 1 ] );
    return this;
  }

  get inputTensorCount() { return this.inputs.length; }

  get input0() { return this.inputs[ 0 ]; }
  get input1() { return this.inputs[ 1 ]; }

  get inputChannelCount0() { return this.input0.length; }
  get inputChannelCount1() { return this.input1.length; }

  get outputTensorCount() { return this.outputs.length; }

  get output0() { return this.outputs[ 0 ]; }
  get output1() { return this.outputs[ 1 ]; }

  get outputChannelCount0() { return this.output0.length; }
  get outputChannelCount1() { return this.output1.length; }

}

<|endoftext|>


<commit_before>window.addEventListener('message', e => {
  if (e.source === window && e.data.vueDetected) {
    chrome.runtime.sendMessage(e.data)
  }
})

function detect (win) {
  setTimeout(() => {
    const all = document.querySelectorAll('*')
    const el = [].find.call(all, e => e.__vue__)
    if (el) {
      let Vue = Object.getPrototypeOf(el.__vue__).constructor
      while (Vue.super) {
        Vue = Vue.super
      }
      win.postMessage({
        devtoolsEnabled: Vue.config.devtools,
        vueDetected: true
      }, '*')
    }
  }, 100)
}

// inject the hook
const script = document.createElement('script')
script.textContent = ';(' + detect.toString() + ')(window)'
document.documentElement.appendChild(script)
script.parentNode.removeChild(script)
<commit_msg>Update detector.js (#240)<commit_after>window.addEventListener('message', e => {
  if (e.source === window && e.data.vueDetected) {
    chrome.runtime.sendMessage(e.data)
  }
})

function detect (win) {
  setTimeout(() => {
    const all = document.querySelectorAll('*')
    let el
    for (let i = 0; i < all.length; i++) {
      if (all[i].__vue__) {
        el = all[i]
        break
      }
    }
    if (el) {
      let Vue = Object.getPrototypeOf(el.__vue__).constructor
      while (Vue.super) {
        Vue = Vue.super
      }
      win.postMessage({
        devtoolsEnabled: Vue.config.devtools,
        vueDetected: true
      }, '*')
    }
  }, 100)
}

// inject the hook
const script = document.createElement('script')
script.textContent = ';(' + detect.toString() + ')(window)'
document.documentElement.appendChild(script)
script.parentNode.removeChild(script)
<|endoftext|>


<commit_before><commit_msg>Minor changes<commit_after><|endoftext|>


<commit_before>import fs   from 'fs';
import glob from 'glob';
import url  from 'url';
import yml  from 'yamljs';
import chokidar from 'chokidar';

import express    from 'express';
import https      from 'https';
import bodyParser from 'body-parser';
import cors       from 'cors';

// ログ用
const red   = '\u001b[31m';
const green = '\u001b[32m';
const cyab  = '\u001b[36m';
const reset = '\u001b[0m';

//------------------------------------------------------------------------------
// サポート関数
//------------------------------------------------------------------------------
const privates = {
    /**
     * リクエストパラメータの取得
     *
     * @param {object} req リクエストオブジェクト
     * @return {object} リクエストパラメーターのオブジェクト
     */
    getParams : (req) => {
        if (req.method === 'GET') {
            return req.query;
        }
        return req.body;
    },

    /**
     * is subset
     * these values assumed to be string, since object is http request params.
     *
     * @param {object} whole expect whole set object
     * @param {object} part  expect subset object
     * @return {boolean}
     */
    isSubsetObject : (whole, part) => {
        // wild card
        if (part === '*' && typeof whole !== 'undefined') {
            return true;
        }
        if (typeof whole !== typeof part) {
            return false;
        }
        if (Array.isArray(part)) {
            return part.sort().every(
                (val, index) => privates.isSubsetObject(whole[index], val),
            );
        } else if (part instanceof Object) {
            return Object.keys(part).every(
                key => privates.isSubsetObject(whole[key], part[key]),
            );
        }
        // enum string
        if (privates.isPlaceholder(String(part))) {
            const enums = part.slice(1, -1).split('|');
            return enums.findIndex(v => (v === whole)) !== -1;
        }
        // another string
        return whole === part;
    },

    /**
     * 渡された文字列がプレースホルダー部分かどうか
     *
     * @param {string} str
     * @return {boolean}
     */
    isPlaceholder : str => (str.substr(0, 1) === '{' && str.substr(-1) === '}'),

    /**
     * pathを比較する
     *
     * @param {string} stubPath スタブ設定のパス
     * @param {string} reqPath  リクエストパス
     * @return {array}
     *   0 : {boolean} マッチしたか
     *   1 : {object}  抜き出したルーティングパラメータのオブジェクト
     */
    isMatchingPathAndExtractParams : (stubPath, reqPath) => {
        const stubDirs  = stubPath.split('/');
        const reqDirs   = reqPath.split('/');
        let reqParams   = {};
        let isMatch;
        if (stubDirs.length === reqDirs.length) {
            isMatch = stubDirs.every((stubDir, j) => {
                const reqDir = reqDirs[j];
                if (privates.isPlaceholder(stubDir)) {
                    reqParams[stubDir.slice(1, -1)] = reqDir;
                    return true;
                } else if (stubDir === reqDir) {
                    return true;
                }
                // no match
                reqParams = {};
                return false;
            });
        } else {
            isMatch = false;
        }

        return [isMatch, reqParams];
    },

    /**
     * 指定ディレクトリから設定を読み込む
     */
    loadFiles : (directory) => {
        const data = {};

        [
            // YAML
            {
                extension : 'yml',
                parse     : file => yml.load(file),
            },
            // JSON
            {
                extension : 'json',
                parse     : file => JSON.parse(fs.readFileSync(file, 'utf-8')),
            },
        ].forEach((typeInfo) => {
            const files = glob.sync(`${directory}/*.${typeInfo.extension}`);
            files.forEach((file) => {
                data[file] = {};
                const parsed = typeInfo.parse(file);
                Object.keys(parsed).forEach((key) => {
                    data[file][key] = parsed[key];
                });
            });
        });

        return data;
    },

    // 出力系
    outputJson : (res, data) => {
        res.writeHead(data.status, { 'Content-Type' : 'application/json; charset=utf-8' });
        res.end(JSON.stringify(data.body));
    },

    outputNotFound : (res) => {
        res.writeHead(404);
        res.end('Not Found');
    },

    outputError : (res) => {
        res.writeHead(500);
        res.end('Server Error!');
    },
};

//------------------------------------------------------------------------------
// main
//------------------------------------------------------------------------------
/**
 * Stubon
 *
 * @prop {object}  app   express object
 * @prop {object}  stubs stub setting object
 * @prop {boolean} debug detailed log flag
 * @prop {boolean} ssl   ssl flag
 */
class Stubon {

    /**
     * constructor
     *
     * @param {string}  directory             setting file directory
     * @param {object}  options
     * @param {boolean} [options.debug=false] detailed log flag
     * @param {boolean} [options.ssl=false]   https mode
     */
    constructor(directory, options = {}) {
        this.debug = options.debug || false;
        this.ssl   = options.ssl || false;
        this.stubs = privates.loadFiles(directory);
        this.app   = express();

        // watch files
        chokidar.watch(directory, { persistent : true })
            .on('change', () => {
                this.log('\n----- stub files changed -----');
                this.stubs = privates.loadFiles(directory);
            });
    }

    /**
     * start server
     */
    server() {
        // to be able to receive request params on POST method.
        this.app.use(bodyParser.urlencoded({ extended : true }));
        this.app.use(bodyParser.json());

        // allow cors
        this.app.use(cors());

        // set routing
        this.app.all('*', (req, res) => {
            this.log('\n----- recieve request -----');
            this.router(req, res);
        });

        // set ssl (optional)
        if (this.ssl) {
            this.app = https.createServer({
                key  : fs.readFileSync(`${__dirname}/../ssl/server.key`),
                cert : fs.readFileSync(`${__dirname}/../ssl/server.crt`),
            }, this.app);
        }

        return this.app;
    }

    /**
     * router
     *
     * @param {object} req request object
     * @param {object} res respons object
     */
    router(req, res) {
        const {
            getParams,
            isMatchingPathAndExtractParams,
            isSubsetObject,
            outputJson,
            outputNotFound,
            outputError,
        } = privates;
        try {
            const reqPath    = decodeURI(url.parse(req.url).pathname);
            const reqQueries = getParams(req);

            this.log([
                { path : reqPath },
                { method : req.method },
                { query : reqQueries },
                { header : JSON.stringify(req.headers) },
            ], true);

            const isFound = Object.keys(this.stubs).some((file) => {
                this.log(`file: ${file}`, true);
                return Object.keys(this.stubs[file]).some((stubPath) => {
                    // check path
                    this.log(`  path: ${stubPath}`, true);
                    const [isMatch, reqParams] = isMatchingPathAndExtractParams(stubPath, reqPath);
                    if (!isMatch) {
                        return false;
                    }

                    this.log('  matched.', true);
                    return this.stubs[file][stubPath].some((setting, i) => {
                        this.log(`    index: ${i}`, true);
                        const exp = setting.request;

                        // check params
                        if ((!exp.method || exp.method === req.method)
                            && (!exp.params || isSubsetObject(reqParams, exp.params))
                            && (!exp.queries || isSubsetObject(reqQueries, exp.queries))
                            && (!exp.headers || isSubsetObject(req.headers, exp.headers))
                        ) {
                            this.log(`>> ${green}match!${reset} ${file} ${stubPath} [${i}]`);
                            const response = this.stubs[file][stubPath][i].response;
                            const options  = this.stubs[file][stubPath][i].options || {};
                            const lagSec   = parseInt(options.lagSec, 10) || 0;
                            setTimeout(() => outputJson(res, response), lagSec * 1000);
                            return true;
                        }

                        return false;
                    });
                });
            });
            if (!isFound) {
                this.log(`>> ${cyab}not found${reset}`);
                outputNotFound(res);
            }
        } catch (e) {
            this.log(`>> ${red}error${reset}`);
            this.log(e);
            outputError(res);
        }
    }

    /**
     * logger
     *
     * @param {string}  msg                message
     * @param {boolean} [isDebugLog=false] detailed log flag
     */
    log(msg, isDebugLog = false) {
        if ((isDebugLog && this.debug) || !isDebugLog) {
            console.log(msg);
        }
    }
}

export { privates }; // export for test
export default Stubon;
<commit_msg>[clean] Translate comments into English<commit_after>import fs   from 'fs';
import glob from 'glob';
import url  from 'url';
import yml  from 'yamljs';
import chokidar from 'chokidar';

import express    from 'express';
import https      from 'https';
import bodyParser from 'body-parser';
import cors       from 'cors';

// for log
const red   = '\u001b[31m';
const green = '\u001b[32m';
const cyab  = '\u001b[36m';
const reset = '\u001b[0m';

//------------------------------------------------------------------------------
// utilities
//------------------------------------------------------------------------------
const privates = {
    /**
     * get request parameters
     *
     * @param {Request} req request object from express
     * @return {object}
     */
    getParams : (req) => {
        if (req.method === 'GET') {
            return req.query;
        }
        return req.body;
    },

    /**
     * is subset
     * these values assumed to be string, since object is http request params.
     *
     * @param {object} whole expect whole set object
     * @param {object} part  expect subset object
     * @return {boolean}
     */
    isSubsetObject : (whole, part) => {
        // wild card
        if (part === '*' && typeof whole !== 'undefined') {
            return true;
        }
        if (typeof whole !== typeof part) {
            return false;
        }
        if (Array.isArray(part)) {
            return part.sort().every(
                (val, index) => privates.isSubsetObject(whole[index], val),
            );
        } else if (part instanceof Object) {
            return Object.keys(part).every(
                key => privates.isSubsetObject(whole[key], part[key]),
            );
        }
        // enum string
        if (privates.isPlaceholder(String(part))) {
            const enums = part.slice(1, -1).split('|');
            return enums.findIndex(v => (v === whole)) !== -1;
        }
        // another string
        return whole === part;
    },

    /**
     * is placeholder string
     *
     * @param {string} str
     * @return {boolean}
     */
    isPlaceholder : str => (str.substr(0, 1) === '{' && str.substr(-1) === '}'),

    /**
     * compare path and get requested routing params
     *
     * @param {string} stubPath path that was set to files
     * @param {string} reqPath  path that was requested
     * @return {array}
     *   0 : {boolean} is matched
     *   1 : {object}  requested routing params
     */
    isMatchingPathAndExtractParams : (stubPath, reqPath) => {
        const stubDirs  = stubPath.split('/');
        const reqDirs   = reqPath.split('/');
        let reqParams   = {};
        let isMatch;
        if (stubDirs.length === reqDirs.length) {
            isMatch = stubDirs.every((stubDir, j) => {
                const reqDir = reqDirs[j];
                if (privates.isPlaceholder(stubDir)) {
                    reqParams[stubDir.slice(1, -1)] = reqDir;
                    return true;
                } else if (stubDir === reqDir) {
                    return true;
                }
                // no match
                reqParams = {};
                return false;
            });
        } else {
            isMatch = false;
        }

        return [isMatch, reqParams];
    },

    /**
     * Read files under a specified directory
     *
     * @param {string} directory string indicating the directory
     * @return {object}
     */
    loadFiles : (directory) => {
        const data = {};

        [
            // YAML
            {
                extension : 'yml',
                parse     : file => yml.load(file),
            },
            // JSON
            {
                extension : 'json',
                parse     : file => JSON.parse(fs.readFileSync(file, 'utf-8')),
            },
        ].forEach((typeInfo) => {
            const files = glob.sync(`${directory}/*.${typeInfo.extension}`);
            files.forEach((file) => {
                data[file] = {};
                const parsed = typeInfo.parse(file);
                Object.keys(parsed).forEach((key) => {
                    data[file][key] = parsed[key];
                });
            });
        });

        return data;
    },

    /**
     * normal output (200)
     *
     * @param {Response} res  response object from express
     * @param {object}   data output data object
     */
    outputJson : (res, data) => {
        res.writeHead(data.status, { 'Content-Type' : 'application/json; charset=utf-8' });
        res.end(JSON.stringify(data.body));
    },

    /**
     * not found output (404)
     *
     * @param {Response} res  response object from express
     */
    outputNotFound : (res) => {
        res.writeHead(404);
        res.end('Not Found');
    },

    /**
     * error output (500)
     *
     * @param {Response} res  response object from express
     */
    outputError : (res) => {
        res.writeHead(500);
        res.end('Server Error!');
    },
};

//------------------------------------------------------------------------------
// main
//------------------------------------------------------------------------------
/**
 * Stubon
 *
 * @prop {object}  app   express object
 * @prop {object}  stubs stub setting object
 * @prop {boolean} debug detailed log flag
 * @prop {boolean} ssl   ssl flag
 */
class Stubon {

    /**
     * constructor
     *
     * @param {string}  directory             setting file directory
     * @param {object}  options
     * @param {boolean} [options.debug=false] detailed log flag
     * @param {boolean} [options.ssl=false]   https mode
     */
    constructor(directory, options = {}) {
        this.debug = options.debug || false;
        this.ssl   = options.ssl || false;
        this.stubs = privates.loadFiles(directory);
        this.app   = express();

        // watch files
        chokidar.watch(directory, { persistent : true })
            .on('change', () => {
                this.log('\n----- stub files changed -----');
                this.stubs = privates.loadFiles(directory);
            });
    }

    /**
     * start server
     */
    server() {
        // to be able to receive request params on POST method.
        this.app.use(bodyParser.urlencoded({ extended : true }));
        this.app.use(bodyParser.json());

        // allow cors
        this.app.use(cors());

        // set routing
        this.app.all('*', (req, res) => {
            this.log('\n----- recieve request -----');
            this.router(req, res);
        });

        // set ssl (optional)
        if (this.ssl) {
            this.app = https.createServer({
                key  : fs.readFileSync(`${__dirname}/../ssl/server.key`),
                cert : fs.readFileSync(`${__dirname}/../ssl/server.crt`),
            }, this.app);
        }

        return this.app;
    }

    /**
     * router
     *
     * @param {object} req request object
     * @param {object} res respons object
     */
    router(req, res) {
        const {
            getParams,
            isMatchingPathAndExtractParams,
            isSubsetObject,
            outputJson,
            outputNotFound,
            outputError,
        } = privates;
        try {
            const reqPath    = decodeURI(url.parse(req.url).pathname);
            const reqQueries = getParams(req);

            this.log([
                { path : reqPath },
                { method : req.method },
                { query : reqQueries },
                { header : JSON.stringify(req.headers) },
            ], true);

            const isFound = Object.keys(this.stubs).some((file) => {
                this.log(`file: ${file}`, true);
                return Object.keys(this.stubs[file]).some((stubPath) => {
                    // check path
                    this.log(`  path: ${stubPath}`, true);
                    const [isMatch, reqParams] = isMatchingPathAndExtractParams(stubPath, reqPath);
                    if (!isMatch) {
                        return false;
                    }

                    this.log('  matched.', true);
                    return this.stubs[file][stubPath].some((setting, i) => {
                        this.log(`    index: ${i}`, true);
                        const exp = setting.request;

                        // check params
                        if ((!exp.method || exp.method === req.method)
                            && (!exp.params || isSubsetObject(reqParams, exp.params))
                            && (!exp.queries || isSubsetObject(reqQueries, exp.queries))
                            && (!exp.headers || isSubsetObject(req.headers, exp.headers))
                        ) {
                            this.log(`>> ${green}match!${reset} ${file} ${stubPath} [${i}]`);
                            const response = this.stubs[file][stubPath][i].response;
                            const options  = this.stubs[file][stubPath][i].options || {};
                            const lagSec   = parseInt(options.lagSec, 10) || 0;
                            setTimeout(() => outputJson(res, response), lagSec * 1000);
                            return true;
                        }

                        return false;
                    });
                });
            });
            if (!isFound) {
                this.log(`>> ${cyab}not found${reset}`);
                outputNotFound(res);
            }
        } catch (e) {
            this.log(`>> ${red}error${reset}`);
            this.log(e);
            outputError(res);
        }
    }

    /**
     * logger
     *
     * @param {string}  msg                message
     * @param {boolean} [isDebugLog=false] detailed log flag
     */
    log(msg, isDebugLog = false) {
        if ((isDebugLog && this.debug) || !isDebugLog) {
            console.log(msg);
        }
    }
}

export { privates }; // export for test
export default Stubon;
<|endoftext|>


<commit_before><commit_msg>Making sure we destroy rays after we use them.<commit_after><|endoftext|>


<commit_before><commit_msg>Added missed skin.js file<commit_after><|endoftext|>