<commit_before>var http = new XMLHttpRequest();
var texto = document.getElementById("input");
var speech = 'poxa';
//teste
var isShow = true;

var iniciar = {
    input: 'comecar_conversar'
}

jsonStringify = JSON.stringify(iniciar);

send(jsonStringify);

// http.onreadystatechange = function() {
//     if (http.readyState == XMLHttpRequest.DONE) {
//         var obj = JSON.parse(http.responseText);
//         speech = "";
//         obj.forEach(function(element) {
//             $(".ms-body").append('

' + element + '
 ' + Date() + '

');
//             speech += element + " ";
//         }, this);
//
//         scroll();
//         //para o watson falar pode ser encontrado no textToSpeech
//         sendTextToSpeech(speech);
//         //alert(http.responseText);
//     }
// }

function enviarMensagem() {

    var frase = texto.value;
    if (frase.trim() != '') {

        var json = {
            input: frase
        }

        jsonStringify = JSON.stringify(json);

        console.log(jsonStringify);

        send(jsonStringify);
    } else {
        alert("é nescessario escrever alguma coisa para iniciar uma conversa com o watson")
    }
}

function handle(e) {
    if (e.keyCode === 13) {
        enviarMensagem();

        var audio = document.getElementById('audio');
        var url = '/api/synthesize?voice=pt-BR_IsabelaVoice&text=' + "a google é muito ruim comigo, na bad";
        audio.src = url;
        audio.play();

        http.onreadystatechange = function() {
            if (http.readyState == XMLHttpRequest.DONE) {
                var obj = JSON.parse(http.responseText);
                speech = "";
                obj.forEach(function(element) {
                    $(".ms-body").append('

' + element + '
 ' + Date() + '

');
                    speech += element + " ";
                }, this);

                scroll();
                //para o watson falar pode ser encontrado no textToSpeech
                // sendTextToSpeech(speech);
                //alert(http.responseText);
            }
        }

        if (event.preventDefault) event.preventDefault();
        return false; // evita da espaco no input
    }
}

function send(json) {

    http.open('POST', '/api/message', true);
    http.setRequestHeader('Content-type', 'application/json');
    http.send(json);

    obj = JSON.parse(json);

    if (obj.input != 'comecar_conversar') {
        $(".ms-body").append('

' + obj.input + '
 ' + Date() + '

');
        scroll();
        texto.value = '';
    }

}

function button_animation() {
    if (isShow) {
        isShow = false;
        $('#animation').attr('class', 'animated bounceOutRight');
    } else {
        isShow = true;
        $('#animation').attr('class', 'animated bounceInRight');
    }
}
<commit_msg>mais um teste conversation novamente<commit_after>var http = new XMLHttpRequest();
var texto = document.getElementById("input");
var speech = 'poxa';
//teste
var isShow = true;

var iniciar = {
    input: 'comecar_conversar'
}

jsonStringify = JSON.stringify(iniciar);

send(jsonStringify);

// http.onreadystatechange = function() {
//     if (http.readyState == XMLHttpRequest.DONE) {
//         var obj = JSON.parse(http.responseText);
//         speech = "";
//         obj.forEach(function(element) {
//             $(".ms-body").append('

' + element + '
 ' + Date() + '

');
//             speech += element + " ";
//         }, this);
//
//         scroll();
//         //para o watson falar pode ser encontrado no textToSpeech
//         sendTextToSpeech(speech);
//         //alert(http.responseText);
//     }
// }

function enviarMensagem() {

    var frase = texto.value;
    if (frase.trim() != '') {

        var json = {
            input: frase
        }

        jsonStringify = JSON.stringify(json);

        console.log(jsonStringify);

        send(jsonStringify);
    } else {
        alert("é nescessario escrever alguma coisa para iniciar uma conversa com o watson")
    }
}

function handle(e) {
    if (e.keyCode === 13) {
        enviarMensagem();

        var audio = document.getElementById('audio');

        http.onreadystatechange = function() {
            if (http.readyState == XMLHttpRequest.DONE) {
                var obj = JSON.parse(http.responseText);
                speech = "";
                obj.forEach(function(element) {
                    $(".ms-body").append('

' + element + '
 ' + Date() + '

');
                    speech += element + " ";
                }, this);

                scroll();
                //para o watson falar pode ser encontrado no textToSpeech
                // sendTextToSpeech(speech);
                //alert(http.responseText);

                var audio = document.getElementById('audio');
                var url = '/api/synthesize?voice=pt-BR_IsabelaVoice&text=' + conversation;
                audio.src = url;
                audio.play();
            }
        }

        if (event.preventDefault) event.preventDefault();
        return false; // evita da espaco no input
    }
}

function send(json) {

    http.open('POST', '/api/message', true);
    http.setRequestHeader('Content-type', 'application/json');
    http.send(json);

    obj = JSON.parse(json);

    if (obj.input != 'comecar_conversar') {
        $(".ms-body").append('

' + obj.input + '
 ' + Date() + '

');
        scroll();
        texto.value = '';
    }

}

function button_animation() {
    if (isShow) {
        isShow = false;
        $('#animation').attr('class', 'animated bounceOutRight');
    } else {
        isShow = true;
        $('#animation').attr('class', 'animated bounceInRight');
    }
}
<|endoftext|>


<commit_before>/**
 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. 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. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file 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.
 */

var zlib = require('zlib');
var url = require('url');
var domain = require('domain');
var builder = require('./browser-builder');
var _ = require('underscore');
var express = require('express');

var port = process.argv[2] || 8080;

function domainHandler(request, response, callback) {
  var dom = domain.create();
  dom.add(request);
  dom.add(response);
  dom.on('error', function (err) {
    response.writeHead(400, err.message, {'content-type': 'text/plain'});
    response.end(err.message);
  }).run(function() { callback(dom) });
}

function buildSDK(request, response, options) {
  domainHandler(request, response, function(dom) {
    var query = url.parse(request.url).query;
    if (query) query = query.replace(/=?&/g, ',').replace(/=/, '-');
    options = _.defaults(options || {}, { stream: null, minify: true });

    builder(query, options, function (err, stream) {
      if (err) return dom.emit('error', err);

      response.setHeader('content-type', 'text/javascript');
      response.writeHead(200);
      stream.pipe(response);
    });
  });
}

function buildUnminifiedSDK(req, res) {
  buildSDK(req, res, { minify: false });
}

var app = express();
app.use(express.compress());
app.use(express.favicon());
if (require.main === module) {
  app.use(express.logger()); // enable logging only for executable
}
app.get('/', buildSDK);
app.get('/aws-sdk.min.js', buildSDK);
app.get('/aws-sdk.js', buildUnminifiedSDK);

module.exports = app;

// run if we called this tool directly
if (require.main === module) {
  app.listen(port);
  console.log('* aws-sdk builder listening on http://localhost:' + port);
}
<commit_msg>Listen on PORT environment variable<commit_after>/**
 * Copyright 2012-2013 Amazon.com, Inc. or its affiliates. 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. A copy of
 * the License is located at
 *
 *     http://aws.amazon.com/apache2.0/
 *
 * or in the "license" file accompanying this file. This file 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.
 */

var zlib = require('zlib');
var url = require('url');
var domain = require('domain');
var builder = require('./browser-builder');
var _ = require('underscore');
var express = require('express');

var port = process.argv[2] || process.env.PORT || 8080;

function domainHandler(request, response, callback) {
  var dom = domain.create();
  dom.add(request);
  dom.add(response);
  dom.on('error', function (err) {
    response.writeHead(400, err.message, {'content-type': 'text/plain'});
    response.end(err.message);
  }).run(function() { callback(dom) });
}

function buildSDK(request, response, options) {
  domainHandler(request, response, function(dom) {
    var query = url.parse(request.url).query;
    if (query) query = query.replace(/=?&/g, ',').replace(/=/, '-');
    options = _.defaults(options || {}, { stream: null, minify: true });

    builder(query, options, function (err, stream) {
      if (err) return dom.emit('error', err);

      response.setHeader('content-type', 'text/javascript');
      response.writeHead(200);
      stream.pipe(response);
    });
  });
}

function buildUnminifiedSDK(req, res) {
  buildSDK(req, res, { minify: false });
}

var app = express();
app.use(express.compress());
app.use(express.favicon());
if (require.main === module) {
  app.use(express.logger()); // enable logging only for executable
}
app.get('/', buildSDK);
app.get('/aws-sdk.min.js', buildSDK);
app.get('/aws-sdk.js', buildUnminifiedSDK);

module.exports = app;

// run if we called this tool directly
if (require.main === module) {
  app.listen(port);
  console.log('* aws-sdk builder listening on http://localhost:' + port);
}
<|endoftext|>


<commit_before>import { toBeDeepCloseTo } from 'jest-matcher-deep-close-to';
import { getClasses } from 'ml-dataset-iris';

import { sampleAClass } from '../sampleAClass.js';

expect.extend({ toBeDeepCloseTo });

const metadata = getClasses();

describe('get sample of class', () => {
  it('check length', () => {
    expect(metadata).toHaveLength(150);
  });
  let c = sampleAClass(metadata, 0.1).trainIndex;
  it('check length', () => {
    expect(c).toHaveLength(15);
  });
});
<commit_msg>correct test for sampleAClass<commit_after>import { toBeDeepCloseTo } from 'jest-matcher-deep-close-to';
import { getClasses } from 'ml-dataset-iris';

import { sampleAClass } from '../sampleAClass.js';

expect.extend({ toBeDeepCloseTo });

const metadata = getClasses();

describe('get sample of class', () => {
  let c = sampleAClass(metadata, 0.1).trainIndex;
  it('check length 0.1', () => {
    expect(c).toHaveLength(15);
  });
  let d = sampleAClass(metadata, 0.2).trainIndex;
  it('check length 1', () => {
    expect(d).toHaveLength(30);
  });
  let e = sampleAClass(metadata, 0.0).trainIndex;
  it('check length 0', () => {
    expect(e).toHaveLength(0);
  });
});
<|endoftext|>


<commit_before>var FirebugLoadManager = function () {
    try
    {
        // Get ModuleLoader implementation (it's Mozilla JS code module)
        Components.utils["import"]("resource://firebug/moduleLoader.js");
        if (FBTrace.DBG_MODULES)
            FBTrace.sysout("Loaded ModuleLoader");
    }
    catch (exc)
    {
        var msg = exc.toString() +" "+(exc.fileName || exc.sourceName) + "@" + exc.lineNumber;
        if (FBTrace.DBG_MODULES)
        {
            dump("Import moduleLoader.js FAILS: "+msg+"\n");
            FBTrace.sysout("Import moduleLoader.js ERROR "+msg, exc);
        }
        Components.utils.reportError(msg);
        throw exc;
    }

    function preLoadInitialization()
    {
        // FIXME, create options.js as dependent of loader. Firebug.architecture = this.getPref(this.prefDomain, "architecture");
    }

    function getModuleLoaderScope(config)
    {
        Firebug.loadConfiguration = config;  // we need to get the values to options.js somehow.

        var firebugScope = // pump the objects from this scope down into module loader
        {
            window : window,
            Firebug: Firebug,
            fbXPCOMUtils: fbXPCOMUtils,
            FBL: FBL,
            FirebugReps: FirebugReps,
            FBTrace: FBTrace,
            domplate: domplate,
            setTimeout: function(fn, delay) { return window.setTimeout(fn, delay); }, // bind window via closure
            clearTimeout: function(timeout) { return window.clearTimeout(timeout); }, // bind window via closure
            setInterval: function(fn, delay) { return window.setInterval(fn, delay); }, // bind window via closure
            clearInterval: function(timeout) { return window.clearInterval(timeout); }, // bind window via closure
        };
        return firebugScope;
    }

    function getModuleLoaderConfig(config)
    {
        var uid = Math.random();  // to give each XUL window its own loader (for now)
        var config = {
            context:"Firebug "+uid, // TODO XUL window id on FF4.0+
            baseUrl: config.baseUrl,
            paths: config.paths,
            onDebug: function() {
                if (!this.FBTrace)
                {
                    // traceConsoleService is a global of |window| frome trace.js.
                    // on the first call we use it to get a ref to the Cu.import module object
                    this.FBTrace = traceConsoleService.getTracer("extensions.firebug");
                }
                if (this.FBTrace.DBG_MODULES)
                    this.FBTrace.sysout.apply(this.FBTrace,arguments);
            },
            onError: function()
            {
                Components.utils.reportError(arguments[0]);  // put something out for sure
                if (!this.FBTrace)
                {
                    // traceConsoleService is a global of |window| frome trace.js.
                    // on the first call we use it to get a ref to the Cu.import module object
                    this.FBTrace = traceConsoleService.getTracer("extensions.firebug");
                }
                if (this.FBTrace.DBG_ERRORS || this.FBTrace.DBG_MODULES)
                    this.FBTrace.sysout.apply(this.FBTrace, arguments);
                throw arguments[0];
            },
            waitSeconds: 0,
            debug: true,
            /* edit: function(errorMsg, errorURL, errorLineNumber)
            {
                window.alert(errorMsg+" "+errorURL+"@"+errorLineNumber);
            },
            edit: function(context, url, module)
            {
                FBTrace.sysout("opening window modal on "+url);
                var a = {url: url};
                return window.showModalDialog("chrome://firebug/content/external/editors.xul",{}, "resizable:yes;scroll:yes;dialogheight:480;dialogwidth:600;center:yes");
            }
            */
        };
        return config;
    }

    function createLoader(config)
    {
        preLoadInitialization();
        var firebugScope = getModuleLoaderScope(config);// pump the objects from this scope down into module loader
        var require_js_config = getModuleLoaderConfig(config);
        var loader = new ModuleLoader(firebugScope, require_js_config);
        return loader;
    }

    /*
     * config.arch: architecture to load, 'inProcess', 'remoteClient', 'remoteServer'
     * config.prefDomain: base for preferences systems, eg 'extension.firebug'
     * config.baseUrl: base for load path
     */

    function loadCore(config, coreInitialize)
    {
        setConfigurationDefaults(config);

        var loader = createLoader(config);

        if (Firebug.alwaysOpenTraceConsole || true)
        {
            loader.define(['traceModule.js'],function(traceModule)
            {
                FBTrace.sysout("traceModule scope includes FBL: "+FBL+" Firebug "+Firebug);
                traceModule.openConsole(config.prefDomain);
            } );  // synchronous

        }

        var coreModules = [];

        if (config.arch === 'inProcess')
        {
            coreModules.push("inProcess/tools.js");  // must be first
            coreModules.push("inProcess/options.js");  // debugger needs Firebug.Options because of $STR() in property initializes, TODO
            coreModules.push("inProcess/firebugadapter.js");
            coreModules.push("debugger.js");
            coreModules.push("inProcess/javascripttool.js");
        }
        else if (config.arch == "remoteClient")
        {
            coreModules.push("crossfireModules/tools.js");
            coreModules.push("inProcess/options.js");  // debugger needs Firebug.Options because of $STR() in property initializes, TODO
            coreModules.push("debugger.js");

        }
        else if (config.arch == "remoteServer")
        {

            coreModules.push("inProcess/tools.js");  // must be first
            coreModules.push("inProcess/options.js");  // debugger needs Firebug.Options because of $STR() in property initializes, TODO
            coreModules.push("debugger.js");

            coreModules.push("crossfireModules/crossfire-server.js");
        }
        else
        {
            throw new Error("ERROR Firebug.LoadManager.loadCore unknown architechture requested: "+Firebug.arch);
        }

        var defaultModules = [
         "tabContext.js",  // should be loaded by being a dep of tabWatcher
         "sourceBox.js",
         "script.js",
        ];

        var modules = coreModules.concat(defaultModules);

        loader.define(modules, coreInitialize);
    }

    function setConfigurationDefaults(config)
    {
        config.arch = config.arch || 'inProcess';
        config.prefDomain = config.prefDomain || 'extensions.firebug';
        config.baseUrl = config.baseUrl || 'resource://firebug_rjs/';
        config.paths = {"arch": config.arch};
    }

    return {loadCore: loadCore, arch: "inProcess"};
}();<commit_msg>[1.8] module load tracingModule, but the UI is not wired correctly<commit_after>var FirebugLoadManager = function () {
    try
    {
        // Get ModuleLoader implementation (it's Mozilla JS code module)
        Components.utils["import"]("resource://firebug/moduleLoader.js");
        if (FBTrace.DBG_MODULES)
            FBTrace.sysout("Loaded ModuleLoader");
    }
    catch (exc)
    {
        var msg = exc.toString() +" "+(exc.fileName || exc.sourceName) + "@" + exc.lineNumber;
        if (FBTrace.DBG_MODULES)
        {
            dump("Import moduleLoader.js FAILS: "+msg+"\n");
            FBTrace.sysout("Import moduleLoader.js ERROR "+msg, exc);
        }
        Components.utils.reportError(msg);
        throw exc;
    }

    function preLoadInitialization()
    {
        // FIXME, create options.js as dependent of loader. Firebug.architecture = this.getPref(this.prefDomain, "architecture");
    }

    function getModuleLoaderScope(config)
    {
        Firebug.loadConfiguration = config;  // we need to get the values to options.js somehow.

        var firebugScope = // pump the objects from this scope down into module loader
        {
            window : window,
            Firebug: Firebug,
            fbXPCOMUtils: fbXPCOMUtils,
            FBL: FBL,
            FirebugReps: FirebugReps,
            FBTrace: FBTrace,
            domplate: domplate,
            setTimeout: function(fn, delay) { return window.setTimeout(fn, delay); }, // bind window via closure
            clearTimeout: function(timeout) { return window.clearTimeout(timeout); }, // bind window via closure
            setInterval: function(fn, delay) { return window.setInterval(fn, delay); }, // bind window via closure
            clearInterval: function(timeout) { return window.clearInterval(timeout); }, // bind window via closure
        };
        return firebugScope;
    }

    function getModuleLoaderConfig(config)
    {
        var uid = Math.random();  // to give each XUL window its own loader (for now)
        var config = {
            context:"Firebug "+uid, // TODO XUL window id on FF4.0+
            baseUrl: config.baseUrl,
            paths: config.paths,
            onDebug: function() {
                if (!this.FBTrace)
                {
                    // traceConsoleService is a global of |window| frome trace.js.
                    // on the first call we use it to get a ref to the Cu.import module object
                    this.FBTrace = traceConsoleService.getTracer("extensions.firebug");
                }
                if (this.FBTrace.DBG_MODULES)
                    this.FBTrace.sysout.apply(this.FBTrace,arguments);
            },
            onError: function()
            {
                Components.utils.reportError(arguments[0]);  // put something out for sure
                if (!this.FBTrace)
                {
                    // traceConsoleService is a global of |window| frome trace.js.
                    // on the first call we use it to get a ref to the Cu.import module object
                    this.FBTrace = traceConsoleService.getTracer("extensions.firebug");
                }
                if (this.FBTrace.DBG_ERRORS || this.FBTrace.DBG_MODULES)
                    this.FBTrace.sysout.apply(this.FBTrace, arguments);
                throw arguments[0];
            },
            waitSeconds: 0,
            debug: true,
            /* edit: function(errorMsg, errorURL, errorLineNumber)
            {
                window.alert(errorMsg+" "+errorURL+"@"+errorLineNumber);
            },
            edit: function(context, url, module)
            {
                FBTrace.sysout("opening window modal on "+url);
                var a = {url: url};
                return window.showModalDialog("chrome://firebug/content/external/editors.xul",{}, "resizable:yes;scroll:yes;dialogheight:480;dialogwidth:600;center:yes");
            }
            */
        };
        return config;
    }

    function createLoader(config)
    {
        preLoadInitialization();
        var firebugScope = getModuleLoaderScope(config);// pump the objects from this scope down into module loader
        var require_js_config = getModuleLoaderConfig(config);
        var loader = new ModuleLoader(firebugScope, require_js_config);
        return loader;
    }

    /*
     * config.arch: architecture to load, 'inProcess', 'remoteClient', 'remoteServer'
     * config.prefDomain: base for preferences systems, eg 'extension.firebug'
     * config.baseUrl: base for load path
     */

    function loadCore(config, coreInitialize)
    {
        setConfigurationDefaults(config);

        var loader = createLoader(config);

        if (Firebug.alwaysOpenTraceConsole)
        {
            loader.define(['traceModule.js'],function(traceModule)
            {
                FBTrace.sysout("traceModule scope includes FBL: "+FBL+" Firebug "+Firebug);
                traceModule.openConsole(config.prefDomain);
            } );  // synchronous

        }

        var coreModules = [];

        if (config.arch === 'inProcess')
        {
            coreModules.push("inProcess/tools.js");  // must be first
            coreModules.push("inProcess/options.js");  // debugger needs Firebug.Options because of $STR() in property initializes, TODO
            coreModules.push("inProcess/firebugadapter.js");
            coreModules.push("debugger.js");
            coreModules.push("inProcess/javascripttool.js");
        }
        else if (config.arch == "remoteClient")
        {
            coreModules.push("crossfireModules/tools.js");
            coreModules.push("inProcess/options.js");  // debugger needs Firebug.Options because of $STR() in property initializes, TODO
            coreModules.push("debugger.js");

        }
        else if (config.arch == "remoteServer")
        {

            coreModules.push("inProcess/tools.js");  // must be first
            coreModules.push("inProcess/options.js");  // debugger needs Firebug.Options because of $STR() in property initializes, TODO
            coreModules.push("debugger.js");

            coreModules.push("crossfireModules/crossfire-server.js");
        }
        else
        {
            throw new Error("ERROR Firebug.LoadManager.loadCore unknown architechture requested: "+Firebug.arch);
        }

        var defaultModules = [
         "tabContext.js",  // should be loaded by being a dep of tabWatcher
         "sourceBox.js",
         "script.js",
         "traceModule.js"
        ];

        var modules = coreModules.concat(defaultModules);

        loader.define(modules, coreInitialize);
    }

    function setConfigurationDefaults(config)
    {
        config.arch = config.arch || 'inProcess';
        config.prefDomain = config.prefDomain || 'extensions.firebug';
        config.baseUrl = config.baseUrl || 'resource://firebug_rjs/';
        config.paths = {"arch": config.arch};
    }

    return {loadCore: loadCore, arch: "inProcess"};
}();<|endoftext|>


<commit_before>// adopted from https://github.com/isaacs/rimraf
// Copyright (c) Isaac Z. Schlueter and Contributor (ISC)
// removed rimraf.sync, windows and cli support

var assert = require('assert')
var path = require('path')
var fs = require('fs')
var glob = require('../glob/glob')

var defaultGlobOpts = {
  nosort: true,
  silent: true
}

// for EMFILE handling
var timeout = 0

function defaults (options) {
  var methods = [
    'unlink',
    'chmod',
    'stat',
    'lstat',
    'rmdir',
    'readdir'
  ]

  methods.forEach(function (m) {
    options[m] = options[m] || fs[m]
    m = m + 'Sync'
    options[m] = options[m] || fs[m]
  })

  options.maxBusyTries = options.maxBusyTries || 3
  options.emfileWait = options.emfileWait || 1000
  if (options.glob === false) options.disableGlob = true
  options.disableGlob = options.disableGlob || false
  options.glob = options.glob || defaultGlobOpts
}

function rimraf (p, options, cb) {
  if (typeof options === 'function') {
    cb = options
    options = {}
  }

  assert(p, 'rimraf: missing path')
  assert.equal(typeof p, 'string', 'rimraf: path should be a string')
  assert(options, 'rimraf: missing options')
  assert.equal(typeof options, 'object', 'rimraf: options should be object')
  assert.equal(typeof cb, 'function', 'rimraf: callback function required')

  defaults(options)

  var busyTries = 0
  var errState = null
  var n = 0

  if (options.disableGlob || !glob.hasMagic(p))
    return afterGlob(null, [p])

  fs.lstat(p, function (er, stat) {
    if (!er)
      return afterGlob(null, [p])

    glob(p, opts.glob, afterGlob)
  })

  function next (er) {
    errState = errState || er
    if (--n === 0)
      cb(errState)
  }

  function afterGlob (er, results) {
    if (er)
      return cb(er)

    n = results.length
    if (n === 0)
      return cb()

    results.forEach(function (p) {
      rimraf_(p, options, function CB (er) {
        if (er) {
          // this one won't happen if graceful-fs is used.
          if (er.code === "EMFILE" && timeout < options.emfileWait) {
            return setTimeout(function () {
              rimraf_(p, options, CB)
            }, timeout ++)
          }

          // already gone
          if (er.code === "ENOENT") er = null
        }

        timeout = 0
        next(er)
      })
    })
  }
}

// Two possible strategies.
// 1. Assume it's a file.  unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory.  readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong.  However, there
// are likely far more normal files in the world than directories.  This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow.  But until then, YAGNI.
function rimraf_ (p, options, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')

  // sunos lets the root user unlink directories, which is... weird.
  // so we have to lstat here and make sure it's not a dir.
  options.lstat(p, function (er, st) {
    if (er && er.code === "ENOENT")
      return cb(null)

    if (st && st.isDirectory())
      return rmdir(p, options, er, cb)

    options.unlink(p, function (er) {
      if (er) {
        if (er.code === "ENOENT")
          return cb(null)
        if (er.code === "EPERM")
          return rmdir(p, options, er, cb)
        if (er.code === "EISDIR")
          return rmdir(p, options, er, cb)
      }
      return cb(er)
    })
  })
}

function rmdir (p, options, originalEr, cb) {
  assert(p)
  assert(options)
  if (originalEr)
    assert(originalEr instanceof Error)
  assert(typeof cb === 'function')

  // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
  // if we guessed wrong, and it's not a directory, then
  // raise the original error.
  options.rmdir(p, function (er) {
    if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
      rmkids(p, options, cb)
    else if (er && er.code === "ENOTDIR")
      cb(originalEr)
    else
      cb(er)
  })
}

function rmkids(p, options, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')

  options.readdir(p, function (er, files) {
    if (er)
      return cb(er)
    var n = files.length
    if (n === 0)
      return options.rmdir(p, cb)
    var errState
    files.forEach(function (f) {
      rimraf(path.join(p, f), options, function (er) {
        if (errState)
          return
        if (er)
          return cb(errState = er)
        if (--n === 0)
          options.rmdir(p, cb)
      })
    })
  })
}

module.exports = rimraf
<commit_msg>bug fix rile/rimraf — typo on my part<commit_after>// adopted from https://github.com/isaacs/rimraf
// Copyright (c) Isaac Z. Schlueter and Contributor (ISC)
// removed rimraf.sync, windows and cli support

var assert = require('assert')
var path = require('path')
var fs = require('fs')
var glob = require('../glob/glob')

var defaultGlobOpts = {
  nosort: true,
  silent: true
}

// for EMFILE handling
var timeout = 0

function defaults (options) {
  var methods = [
    'unlink',
    'chmod',
    'stat',
    'lstat',
    'rmdir',
    'readdir'
  ]

  methods.forEach(function (m) {
    options[m] = options[m] || fs[m]
    m = m + 'Sync'
    options[m] = options[m] || fs[m]
  })

  options.maxBusyTries = options.maxBusyTries || 3
  options.emfileWait = options.emfileWait || 1000
  if (options.glob === false) options.disableGlob = true
  options.disableGlob = options.disableGlob || false
  options.glob = options.glob || defaultGlobOpts
}

function rimraf (p, options, cb) {
  if (typeof options === 'function') {
    cb = options
    options = {}
  }

  assert(p, 'rimraf: missing path')
  assert.equal(typeof p, 'string', 'rimraf: path should be a string')
  assert(options, 'rimraf: missing options')
  assert.equal(typeof options, 'object', 'rimraf: options should be object')
  assert.equal(typeof cb, 'function', 'rimraf: callback function required')

  defaults(options)

  var busyTries = 0
  var errState = null
  var n = 0

  if (options.disableGlob || !glob.hasMagic(p))
    return afterGlob(null, [p])

  fs.lstat(p, function (er, stat) {
    if (!er)
      return afterGlob(null, [p])

    glob(p, options.glob, afterGlob)
  })

  function next (er) {
    errState = errState || er
    if (--n === 0)
      cb(errState)
  }

  function afterGlob (er, results) {
    if (er)
      return cb(er)

    n = results.length
    if (n === 0)
      return cb()

    results.forEach(function (p) {
      rimraf_(p, options, function CB (er) {
        if (er) {
          // this one won't happen if graceful-fs is used.
          if (er.code === "EMFILE" && timeout < options.emfileWait) {
            return setTimeout(function () {
              rimraf_(p, options, CB)
            }, timeout ++)
          }

          // already gone
          if (er.code === "ENOENT") er = null
        }

        timeout = 0
        next(er)
      })
    })
  }
}

// Two possible strategies.
// 1. Assume it's a file.  unlink it, then do the dir stuff on EPERM or EISDIR
// 2. Assume it's a directory.  readdir, then do the file stuff on ENOTDIR
//
// Both result in an extra syscall when you guess wrong.  However, there
// are likely far more normal files in the world than directories.  This
// is based on the assumption that a the average number of files per
// directory is >= 1.
//
// If anyone ever complains about this, then I guess the strategy could
// be made configurable somehow.  But until then, YAGNI.
function rimraf_ (p, options, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')

  // sunos lets the root user unlink directories, which is... weird.
  // so we have to lstat here and make sure it's not a dir.
  options.lstat(p, function (er, st) {
    if (er && er.code === "ENOENT")
      return cb(null)

    if (st && st.isDirectory())
      return rmdir(p, options, er, cb)

    options.unlink(p, function (er) {
      if (er) {
        if (er.code === "ENOENT")
          return cb(null)
        if (er.code === "EPERM")
          return rmdir(p, options, er, cb)
        if (er.code === "EISDIR")
          return rmdir(p, options, er, cb)
      }
      return cb(er)
    })
  })
}

function rmdir (p, options, originalEr, cb) {
  assert(p)
  assert(options)
  if (originalEr)
    assert(originalEr instanceof Error)
  assert(typeof cb === 'function')

  // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS)
  // if we guessed wrong, and it's not a directory, then
  // raise the original error.
  options.rmdir(p, function (er) {
    if (er && (er.code === "ENOTEMPTY" || er.code === "EEXIST" || er.code === "EPERM"))
      rmkids(p, options, cb)
    else if (er && er.code === "ENOTDIR")
      cb(originalEr)
    else
      cb(er)
  })
}

function rmkids(p, options, cb) {
  assert(p)
  assert(options)
  assert(typeof cb === 'function')

  options.readdir(p, function (er, files) {
    if (er)
      return cb(er)
    var n = files.length
    if (n === 0)
      return options.rmdir(p, cb)
    var errState
    files.forEach(function (f) {
      rimraf(path.join(p, f), options, function (er) {
        if (errState)
          return
        if (er)
          return cb(errState = er)
        if (--n === 0)
          options.rmdir(p, cb)
      })
    })
  })
}

module.exports = rimraf
<|endoftext|>


<commit_before><commit_msg>fix var name<commit_after><|endoftext|>


<commit_before>/*
 File that will be injected in the page by the content script in order to retrieve angular
 performance metrics.

 Heavily inspired by:
 - ng stats
 - ng inspector
 - Angular Inspector
 - Batarang

 */
(function() {
  'use strict';

  var
    _angularInjector,
    _isMonitoringActive = true,
    _backUp = {
      digest: null,
      modules: {}
    };

  if (document.readyState === 'complete'){
    detectAngular();
  } else {
    window.onload(detectAngular)
  }

  /**
   * If angular is detected, bootstraps the inspector
   */
  function detectAngular(){
    if (typeof angular !== 'undefined') {

      window.postMessage({
        task: 'initDevToolPanel',
        source: 'angular-performance-inspector'
      }, '*');

      // We listen for async instrumentation instructions
      window.addEventListener('message', function(event){
        // We only accept messages from ourselves
        if (event.source != window || event.data.source !== 'angular-performance') {
          return;
        }

        var message = event.data;

        switch (message.task){

          case 'checkModuleName':
            var moduleServices = getNgModuleServices(message.moduleName);
            // If there is no services the method will return an empty object, if the module name is
            // invalid, it will return undefined.
            sendTask('reportModuleExistence', {
              moduleName: message.moduleName,
              services: (moduleServices) ? Object.keys(moduleServices) : undefined
            });
            break;

          case 'instrumentModuleServices':
            instrumentModuleServices(message.moduleName);
            break;

          case 'cleanUpInspectedApp':
            _isMonitoringActive = false;
            cleanUpInspectedApp();
            // Once everything is cleaned up, we can remove this script from the DOM
            sendTask('removeInspector');
            break;
        }
      });

      bootstrapInspector();
    }
  }

  /**
   * Function to set up all listeners and data mining tools
   */
  function bootstrapInspector(){

    _angularInjector = angular.element(document.querySelector('[ng-app],[data-ng-app]')).injector().get;

    instrumentDigest();
    initWatcherCount();
  }

  /**
   * This should clean up all that has been instrumented by the inspector and get them back
   * to their normal behaviour. (UnWrap everything)
   */
  function cleanUpInspectedApp(){
    restoreDigest();
    restoreModuleServices();
  }

  // ------------------------------------------------------------------------------------------
  //                                     Digest Monitoring
  // ------------------------------------------------------------------------------------------

  /**
   * Wraps the angular digest so that we can measure how long it take for the digest to happen.
   */
  function instrumentDigest(){

    var scopePrototype = Object.getPrototypeOf(getRootScope());
    _backUp.digest = scopePrototype.$digest;

    scopePrototype.$digest = function $digest() {
      var start = performance.now();
      _backUp.digest.apply(this, arguments);
      var time = (performance.now() - start);
      register('DigestTiming', {
        timestamp: Date.now(),
        time: time
      });
    };
  }

  /**
   * Restores the classic angular digest.
   */
  function restoreDigest(){
    Object.getPrototypeOf(getRootScope()).$digest = _backUp.digest;
  }

  // ------------------------------------------------------------------------------------------
  //                                Scope & Watcher Exploration
  // ------------------------------------------------------------------------------------------

  /**
   * Function to be called once to init the watcher retrieval.
   */
  function initWatcherCount(){
    register('RootWatcherCount', {
      timestamp: Date.now(),
      watcher:{
        watcherCount: getWatcherCountForScope(),
        location: window.location.href
      }
    });
    if (_isMonitoringActive) {
      setTimeout(initWatcherCount, 300);
    }
  }

  /**
   * Retrieves the watcher count for a particular scope
   *
   * @param {angular.scope} [$scope] - angular scope instance
   * @returns {number}               - angular scope count
   */
  function getWatcherCountForScope($scope) {
    var count = 0;
    iterateScopes($scope, function($scope) {
      count += getWatchersFromScope($scope).length;
    });
    return count;
  }

  /**
   * Apply a function down the angular scope
   *
   * @param {angular.scope} [current] - current angular $scope
   * @param {Function}      fn        - function to apply down the scope
   * @returns {*}
   */
  function iterateScopes(current, fn) {
    if (typeof current === 'function') {
      fn = current;
      current = null;
    }
    current = current || getRootScope();
    current = makeScopeReference(current);
    if (!current) {
      return;
    }
    var ret = fn(current);
    if (ret === false) {
      return ret;
    }
    return iterateChildren(current, fn);
  }

  /**
   * Apply a function on a scope siblings (same scope level) and down to their children
   *
   * @param {angular.scope} start - starting scope of the iteration
   * @param {Function}      fn    - function to be applied on the different scopes
   * @returns {*}
   */
  function iterateSiblings(start, fn) {
    var ret;
    while (!!(start = start.$$nextSibling)) {
      ret = fn(start);
      if (ret === false) {
        break;
      }

      ret = iterateChildren(start, fn);
      if (ret === false) {
        break;
      }
    }
    return ret;
  }

  /**
   * Apply a function on all the children scopes and their respective siblings
   *
   * @param {angular.scope} start - start node of the
   * @param {Function}      fn    - function to apply
   * @returns {*}
   */
  function iterateChildren(start, fn) {
    var ret;
    while (!!(start = start.$$childHead)) {
      ret = fn(start);
      if (ret === false) {
        break;
      }

      ret = iterateSiblings(start, fn);
      if (ret === false) {
        break;
      }
    }
    return ret;
  }

  /**
   * Gets the angular root scope
   *
   * @returns {angular.scope}
   */
  function getRootScope(){
    if (typeof $rootScope !== 'undefined') {
      return $rootScope;
    }
    var scopeEl = document.querySelector('.ng-scope');
    if (!scopeEl) {
      return null;
    }
    return angular.element(scopeEl).scope().$root;
  }

  /**
   * Retrieve all watchers from a scope
   *
   * @param {angular.scope} scope - angular scope to get the watchers from
   * @returns {Array}
   */
  function getWatchersFromScope(scope) {
    return scope && scope.$$watchers ? scope.$$watchers : [];
  }

  /**
   * Gets the id of a scope
   *
   * @param {angular.scope} scope - angular scope to get the id from
   * @returns {angular.scope}
   */
  function makeScopeReference(scope) {
    if (isScopeId(scope)) {
      scope = getScopeById(scope);
    }
    return scope;
  }

  /**
   * Gets the scope from an ID
   *
   * @param {String|Number} id - scope id
   * @returns {angular.scope}
   */
  function getScopeById(id) {
    var myScope = null;
    iterateScopes(function(scope) {
      if (scope.$id === id) {
        myScope = scope;
        return false;
      }
    });
    return myScope;
  }

  /**
   * Check if the scope passed as an argument is an id or not.
   *
   * @param {angular.scope} scope
   * @returns {boolean}
   */
  function isScopeId(scope) {
    return typeof scope === 'string' || typeof scope === 'number';
  }

  // ------------------------------------------------------------------------------------------
  //                                     Module & Services
  // ------------------------------------------------------------------------------------------

  /**
   * Gets all the services name from the specified module
   *
   * @param {String}  moduleName - name of the module to get the services from
   * @param {Object}  [services] - already found services (parent module) can be null
   * @returns {Object|undefined} map of all the angular services linked to the specified module.
   *                             returns undefined if the module isn't defined
   */
  function getNgModuleServices(moduleName, services){

    if (!services) {
      services = {};
    }

    var module;

    try {
      module = angular.module(moduleName);
    } catch(e){
      return;
    }

    angular.forEach(module._invokeQueue, function(service) {
      if (service[0] === '$provide' && service[1] === 'service') {
        services[service[2][0]] = _angularInjector(service[2][0]);
      }
    });

    angular.forEach(module.requires, function(dependencyModule) {
      getNgModuleServices(dependencyModule, services)
    });

    return services;
  }

  /**
   * This methods adds timers to all the functions of all the services of a given module
   *
   * @param {String} moduleName - module name to instrument.
   */
  function instrumentModuleServices(moduleName){

    _backUp.modules[moduleName] = {};
    var services = getNgModuleServices(moduleName);

    angular.forEach(Object.keys(services), function(serviceName){

      _backUp.modules[moduleName][serviceName] = {};
      var service = services[serviceName];

      angular.forEach(Object.getOwnPropertyNames(service), function(propertyName){

        // Early return for all properties that are not functions
        // arguments is a reserved property name
        if (propertyName === 'arguments' ||
            propertyName === 'caller' ||
            propertyName === 'callee' ||
            typeof service[propertyName] !== 'function' ||
            propertyName === 'constructor') {
          return;
        }

        var functionToWrap = _backUp.modules[moduleName][serviceName][propertyName] = service[propertyName];

        // We Wrap all the service functions to measure execution time.
        service[propertyName] = function(){
          var
            start = performance.now(),
            // Execute the function as usual
            result = functionToWrap.apply(this, arguments);

          // Register execution time in the extension registry
          register('SyncServiceFunctionCall', {
            module: moduleName,
            service: serviceName,
            func: propertyName,
            time: performance.now() - start
          });

          // We only consider promises since it is the default async handling in angular.
          if (result && typeof result.then === 'function') {
            // We reset the timer so that only async time gets taken.
            start = performance.now();

            // We Append our timing promise to the actual promise
            result.then(function() {
              register('ASyncServiceFunctionCall', {
                module: moduleName,
                service: serviceName,
                func: propertyName,
                time: performance.now() - start
              });
            })
          }
          return result;
        }
      })
    });
  }

  /**
   * Restores the services functions as they were before being wrapped
   *
   * @param {String} [moduleName] - name of the module to be unwrapped. If not mentioned, everything
   *                                should be restored.
   */
  function restoreModuleServices(moduleName){

    var modules;

    if (moduleName){

      if (_backUp.modules[moduleName]) {
        modules = [moduleName];
      } else {
        throw new Error('angular performance - We tried to restore the module '+ moduleName + 'but ' +
          'we could not find any back up :(');
      }

    } else {
      modules = Object.keys(_backUp.modules);
    }

    angular.forEach(modules, function(module){
      var services = getNgModuleServices(module);

      angular.forEach(Object.keys(_backUp.modules[module]), function(service){
        angular.forEach(Object.keys(_backUp.modules[module][service]), function(fnName){
          services[service][fnName] = _backUp.modules[module][service][fnName]
        });
      });

      // Clean up back up
      delete _backUp.modules[module];
    });
  }

  // ------------------------------------------------------------------------------------------
  //                                        Utils
  // ------------------------------------------------------------------------------------------

  /**
   * Reports a metric
   *
   * @param {String} task  - task to do
   * @param {Object} [value] - data that can be sent along with the task
   */
  function sendTask(task, value){
    window.postMessage({
      source: 'angular-performance-inspector',
      task: task,
      data: value
    }, '*');
  }

  /**
   * Register a metric into the devtool instance registry
   *
   * @param {String} variable - can be 'digestTiming'
   * @param {Object} value    - value to be registered with the variable
   */
  function register(variable, value){
    sendTask('register'+variable, value);
  }
})();
<commit_msg>Update inspector.js<commit_after>/*
 File that will be injected in the page by the content script in order to retrieve angular
 performance metrics.

 Heavily inspired by:
 - ng stats
 - ng inspector
 - Angular Inspector
 - Batarang

 */
(function() {
  'use strict';

  var
    _angularInjector,
    _isMonitoringActive = true,
    _backUp = {
      digest: null,
      modules: {}
    };

  if (document.readyState === 'complete'){
    setTimeout(detectAngular, 0);
  } else {
    window.onload(function() {
     setTimeout(detectAngular, 0);
    });
  }

  /**
   * If angular is detected, bootstraps the inspector
   */
  function detectAngular(){
    if (typeof angular !== 'undefined') {

      window.postMessage({
        task: 'initDevToolPanel',
        source: 'angular-performance-inspector'
      }, '*');

      // We listen for async instrumentation instructions
      window.addEventListener('message', function(event){
        // We only accept messages from ourselves
        if (event.source != window || event.data.source !== 'angular-performance') {
          return;
        }

        var message = event.data;

        switch (message.task){

          case 'checkModuleName':
            var moduleServices = getNgModuleServices(message.moduleName);
            // If there is no services the method will return an empty object, if the module name is
            // invalid, it will return undefined.
            sendTask('reportModuleExistence', {
              moduleName: message.moduleName,
              services: (moduleServices) ? Object.keys(moduleServices) : undefined
            });
            break;

          case 'instrumentModuleServices':
            instrumentModuleServices(message.moduleName);
            break;

          case 'cleanUpInspectedApp':
            _isMonitoringActive = false;
            cleanUpInspectedApp();
            // Once everything is cleaned up, we can remove this script from the DOM
            sendTask('removeInspector');
            break;
        }
      });

      bootstrapInspector();
    }
  }

  /**
   * Function to set up all listeners and data mining tools
   */
  function bootstrapInspector(){

    _angularInjector = angular.element(document.querySelector('[ng-app],[data-ng-app]')).injector().get;

    instrumentDigest();
    initWatcherCount();
  }

  /**
   * This should clean up all that has been instrumented by the inspector and get them back
   * to their normal behaviour. (UnWrap everything)
   */
  function cleanUpInspectedApp(){
    restoreDigest();
    restoreModuleServices();
  }

  // ------------------------------------------------------------------------------------------
  //                                     Digest Monitoring
  // ------------------------------------------------------------------------------------------

  /**
   * Wraps the angular digest so that we can measure how long it take for the digest to happen.
   */
  function instrumentDigest(){

    var scopePrototype = Object.getPrototypeOf(getRootScope());
    _backUp.digest = scopePrototype.$digest;

    scopePrototype.$digest = function $digest() {
      var start = performance.now();
      _backUp.digest.apply(this, arguments);
      var time = (performance.now() - start);
      register('DigestTiming', {
        timestamp: Date.now(),
        time: time
      });
    };
  }

  /**
   * Restores the classic angular digest.
   */
  function restoreDigest(){
    Object.getPrototypeOf(getRootScope()).$digest = _backUp.digest;
  }

  // ------------------------------------------------------------------------------------------
  //                                Scope & Watcher Exploration
  // ------------------------------------------------------------------------------------------

  /**
   * Function to be called once to init the watcher retrieval.
   */
  function initWatcherCount(){
    register('RootWatcherCount', {
      timestamp: Date.now(),
      watcher:{
        watcherCount: getWatcherCountForScope(),
        location: window.location.href
      }
    });
    if (_isMonitoringActive) {
      setTimeout(initWatcherCount, 300);
    }
  }

  /**
   * Retrieves the watcher count for a particular scope
   *
   * @param {angular.scope} [$scope] - angular scope instance
   * @returns {number}               - angular scope count
   */
  function getWatcherCountForScope($scope) {
    var count = 0;
    iterateScopes($scope, function($scope) {
      count += getWatchersFromScope($scope).length;
    });
    return count;
  }

  /**
   * Apply a function down the angular scope
   *
   * @param {angular.scope} [current] - current angular $scope
   * @param {Function}      fn        - function to apply down the scope
   * @returns {*}
   */
  function iterateScopes(current, fn) {
    if (typeof current === 'function') {
      fn = current;
      current = null;
    }
    current = current || getRootScope();
    current = makeScopeReference(current);
    if (!current) {
      return;
    }
    var ret = fn(current);
    if (ret === false) {
      return ret;
    }
    return iterateChildren(current, fn);
  }

  /**
   * Apply a function on a scope siblings (same scope level) and down to their children
   *
   * @param {angular.scope} start - starting scope of the iteration
   * @param {Function}      fn    - function to be applied on the different scopes
   * @returns {*}
   */
  function iterateSiblings(start, fn) {
    var ret;
    while (!!(start = start.$$nextSibling)) {
      ret = fn(start);
      if (ret === false) {
        break;
      }

      ret = iterateChildren(start, fn);
      if (ret === false) {
        break;
      }
    }
    return ret;
  }

  /**
   * Apply a function on all the children scopes and their respective siblings
   *
   * @param {angular.scope} start - start node of the
   * @param {Function}      fn    - function to apply
   * @returns {*}
   */
  function iterateChildren(start, fn) {
    var ret;
    while (!!(start = start.$$childHead)) {
      ret = fn(start);
      if (ret === false) {
        break;
      }

      ret = iterateSiblings(start, fn);
      if (ret === false) {
        break;
      }
    }
    return ret;
  }

  /**
   * Gets the angular root scope
   *
   * @returns {angular.scope}
   */
  function getRootScope(){
    if (typeof $rootScope !== 'undefined') {
      return $rootScope;
    }
    var scopeEl = document.querySelector('.ng-scope');
    if (!scopeEl) {
      return null;
    }
    return angular.element(scopeEl).scope().$root;
  }

  /**
   * Retrieve all watchers from a scope
   *
   * @param {angular.scope} scope - angular scope to get the watchers from
   * @returns {Array}
   */
  function getWatchersFromScope(scope) {
    return scope && scope.$$watchers ? scope.$$watchers : [];
  }

  /**
   * Gets the id of a scope
   *
   * @param {angular.scope} scope - angular scope to get the id from
   * @returns {angular.scope}
   */
  function makeScopeReference(scope) {
    if (isScopeId(scope)) {
      scope = getScopeById(scope);
    }
    return scope;
  }

  /**
   * Gets the scope from an ID
   *
   * @param {String|Number} id - scope id
   * @returns {angular.scope}
   */
  function getScopeById(id) {
    var myScope = null;
    iterateScopes(function(scope) {
      if (scope.$id === id) {
        myScope = scope;
        return false;
      }
    });
    return myScope;
  }

  /**
   * Check if the scope passed as an argument is an id or not.
   *
   * @param {angular.scope} scope
   * @returns {boolean}
   */
  function isScopeId(scope) {
    return typeof scope === 'string' || typeof scope === 'number';
  }

  // ------------------------------------------------------------------------------------------
  //                                     Module & Services
  // ------------------------------------------------------------------------------------------

  /**
   * Gets all the services name from the specified module
   *
   * @param {String}  moduleName - name of the module to get the services from
   * @param {Object}  [services] - already found services (parent module) can be null
   * @returns {Object|undefined} map of all the angular services linked to the specified module.
   *                             returns undefined if the module isn't defined
   */
  function getNgModuleServices(moduleName, services){

    if (!services) {
      services = {};
    }

    var module;

    try {
      module = angular.module(moduleName);
    } catch(e){
      return;
    }

    angular.forEach(module._invokeQueue, function(service) {
      if (service[0] === '$provide' && service[1] === 'service') {
        services[service[2][0]] = _angularInjector(service[2][0]);
      }
    });

    angular.forEach(module.requires, function(dependencyModule) {
      getNgModuleServices(dependencyModule, services)
    });

    return services;
  }

  /**
   * This methods adds timers to all the functions of all the services of a given module
   *
   * @param {String} moduleName - module name to instrument.
   */
  function instrumentModuleServices(moduleName){

    _backUp.modules[moduleName] = {};
    var services = getNgModuleServices(moduleName);

    angular.forEach(Object.keys(services), function(serviceName){

      _backUp.modules[moduleName][serviceName] = {};
      var service = services[serviceName];

      angular.forEach(Object.getOwnPropertyNames(service), function(propertyName){

        // Early return for all properties that are not functions
        // arguments is a reserved property name
        if (propertyName === 'arguments' ||
            propertyName === 'caller' ||
            propertyName === 'callee' ||
            typeof service[propertyName] !== 'function' ||
            propertyName === 'constructor') {
          return;
        }

        var functionToWrap = _backUp.modules[moduleName][serviceName][propertyName] = service[propertyName];

        // We Wrap all the service functions to measure execution time.
        service[propertyName] = function(){
          var
            start = performance.now(),
            // Execute the function as usual
            result = functionToWrap.apply(this, arguments);

          // Register execution time in the extension registry
          register('SyncServiceFunctionCall', {
            module: moduleName,
            service: serviceName,
            func: propertyName,
            time: performance.now() - start
          });

          // We only consider promises since it is the default async handling in angular.
          if (result && typeof result.then === 'function') {
            // We reset the timer so that only async time gets taken.
            start = performance.now();

            // We Append our timing promise to the actual promise
            result.then(function() {
              register('ASyncServiceFunctionCall', {
                module: moduleName,
                service: serviceName,
                func: propertyName,
                time: performance.now() - start
              });
            })
          }
          return result;
        }
      })
    });
  }

  /**
   * Restores the services functions as they were before being wrapped
   *
   * @param {String} [moduleName] - name of the module to be unwrapped. If not mentioned, everything
   *                                should be restored.
   */
  function restoreModuleServices(moduleName){

    var modules;

    if (moduleName){

      if (_backUp.modules[moduleName]) {
        modules = [moduleName];
      } else {
        throw new Error('angular performance - We tried to restore the module '+ moduleName + 'but ' +
          'we could not find any back up :(');
      }

    } else {
      modules = Object.keys(_backUp.modules);
    }

    angular.forEach(modules, function(module){
      var services = getNgModuleServices(module);

      angular.forEach(Object.keys(_backUp.modules[module]), function(service){
        angular.forEach(Object.keys(_backUp.modules[module][service]), function(fnName){
          services[service][fnName] = _backUp.modules[module][service][fnName]
        });
      });

      // Clean up back up
      delete _backUp.modules[module];
    });
  }

  // ------------------------------------------------------------------------------------------
  //                                        Utils
  // ------------------------------------------------------------------------------------------

  /**
   * Reports a metric
   *
   * @param {String} task  - task to do
   * @param {Object} [value] - data that can be sent along with the task
   */
  function sendTask(task, value){
    window.postMessage({
      source: 'angular-performance-inspector',
      task: task,
      data: value
    }, '*');
  }

  /**
   * Register a metric into the devtool instance registry
   *
   * @param {String} variable - can be 'digestTiming'
   * @param {Object} value    - value to be registered with the variable
   */
  function register(variable, value){
    sendTask('register'+variable, value);
  }
})();
<|endoftext|>


<commit_before>import fs from 'fs';
import path from 'path';
import base from './base';
import semver from 'semver';
import moment from 'moment';
import request from 'request';
import {exec} from 'child_process';
import pack from '../../../../package.json';

const cluster = require('cluster');

request.defaults({
  timeout: 1000,
  strictSSL: false,
  rejectUnauthorized: false
});

const reqIns = think.promisify(request.get);

export default class extends base {

  init(http) {
    super.init(http);

    this.modelInstance = this.model('options');
  }

  async getAction() {
    let needUpdate = false;
    try {
      let res = await reqIns('http://firekylin.org/release/.latest');
      let onlineVersion = res.body.trim();
      if( semver.gt(onlineVersion, pack.version) ) {
        needUpdate = onlineVersion;
      }
    } catch(e) {
      console.log(e);
    }

    let mysql = await this.modelInstance.query('SELECT VERSION() as version');
    let data = {
      nodeVersion: process.versions.node,
      v8Version: process.versions.v8,
      platform: process.platform,
      thinkjsVersion: think.version,
      firekylinVersion: pack.version,
      mysqlVersion: mysql[0].version,
      needUpdate
    };

    //非管理员只统计当前用户文章
    let where = this.userInfo.type !== 1 ? {user_id: this.userInfo.id} : {};
    return this.success({
      versions: data,
      config: await this.getConfig(),
      count: {
        posts: await this.model('post').where(where).count(),
        cates: await this.model('cate').count(),
        comments: await this.model('post').where(where).sum('comment_num')
      }
    });
  }

  async updateAction() {
    if( /^win/.test(process.platform) ) {
      return this.fail('PLATFORM_NOT_SUPPORT');
    }

    let {step} = this.get();
    switch(step) {
      /** 下载文件 */
      case '1':
      default:
        return request({uri: 'http://firekylin.org/release/latest.tar.gz'})
          .pipe(fs.createWriteStream(path.join(think.RESOURCE_PATH, 'latest.tar.gz')))
          .on('close', () => this.success())
          .on('error', err => this.fail(err));

      /** 解压覆盖，删除更新文件 */
      case '2':
        return exec(`
          cd ${think.RESOURCE_PATH};
          tar zvxf latest.tar.gz;
          cp -r firekylin/* ../;
          rm -rf firekylin latest.tar.gz`, (error, stdout, stderr) => {
          if(error) {
            this.fail(error);
          }

          this.success();
        });

      /** 安装依赖 */
      case '3':
        let registry = think.config('registry') || 'https://registry.npm.taobao.org';
        return exec(`npm install --registry=${registry}`, (error, stdout, stderr) => {
          if(error) {
            this.fail(error);
          }

          this.success();
        });

      /** 重启服务 */
      case '4':
        if( cluster.isWorker ) {
          this.success();
          setTimeout(() => cluster.worker.kill(), 200);
        } else {
          this.fail();
        }
        break;
    }
  }

  async getConfig() {
    let items = await this.modelInstance.select();
    let siteConfig = {};

    items.forEach(item => siteConfig[item.key] = item.value);

    return siteConfig;
  }

}
<commit_msg>remv auto-update restart error tip<commit_after>import fs from 'fs';
import path from 'path';
import base from './base';
import semver from 'semver';
import moment from 'moment';
import request from 'request';
import {exec} from 'child_process';
import pack from '../../../../package.json';

const cluster = require('cluster');

request.defaults({
  timeout: 1000,
  strictSSL: false,
  rejectUnauthorized: false
});

const reqIns = think.promisify(request.get);

export default class extends base {

  init(http) {
    super.init(http);

    this.modelInstance = this.model('options');
  }

  async getAction() {
    let needUpdate = false;
    try {
      let res = await reqIns('http://firekylin.org/release/.latest');
      let onlineVersion = res.body.trim();
      if( semver.gt(onlineVersion, pack.version) ) {
        needUpdate = onlineVersion;
      }
    } catch(e) {
      console.log(e);
    }

    let mysql = await this.modelInstance.query('SELECT VERSION() as version');
    let data = {
      nodeVersion: process.versions.node,
      v8Version: process.versions.v8,
      platform: process.platform,
      thinkjsVersion: think.version,
      firekylinVersion: pack.version,
      mysqlVersion: mysql[0].version,
      needUpdate
    };

    //非管理员只统计当前用户文章
    let where = this.userInfo.type !== 1 ? {user_id: this.userInfo.id} : {};
    return this.success({
      versions: data,
      config: await this.getConfig(),
      count: {
        posts: await this.model('post').where(where).count(),
        cates: await this.model('cate').count(),
        comments: await this.model('post').where(where).sum('comment_num')
      }
    });
  }

  async updateAction() {
    if( /^win/.test(process.platform) ) {
      return this.fail('PLATFORM_NOT_SUPPORT');
    }

    let {step} = this.get();
    switch(step) {
      /** 下载文件 */
      case '1':
      default:
        return request({uri: 'http://firekylin.org/release/latest.tar.gz'})
          .pipe(fs.createWriteStream(path.join(think.RESOURCE_PATH, 'latest.tar.gz')))
          .on('close', () => this.success())
          .on('error', err => this.fail(err));

      /** 解压覆盖，删除更新文件 */
      case '2':
        return exec(`
          cd ${think.RESOURCE_PATH};
          tar zvxf latest.tar.gz;
          cp -r firekylin/* ../;
          rm -rf firekylin latest.tar.gz`, (error, stdout, stderr) => {
          if(error) {
            this.fail(error);
          }

          this.success();
        });

      /** 安装依赖 */
      case '3':
        let registry = think.config('registry') || 'https://registry.npm.taobao.org';
        return exec(`npm install --registry=${registry}`, (error, stdout, stderr) => {
          if(error) {
            this.fail(error);
          }

          this.success();
        });

      /** 重启服务 */
      case '4':
        if( cluster.isWorker ) {
          this.success();
          setTimeout(() => cluster.worker.kill(), 200);
        }

        break;
    }
  }

  async getConfig() {
    let items = await this.modelInstance.select();
    let siteConfig = {};

    items.forEach(item => siteConfig[item.key] = item.value);

    return siteConfig;
  }

}
<|endoftext|>


<commit_before>// Copyright (c) 2017 Kari Karvonen, OH1KK

var ant_switch_ext_name = 'ant_switch';		// NB: must match ant_switch.c:ant_switch_ext.name
var ant_switch_first_time = true;
var ant_switch_poll_interval;
var ant_switch_exantennas=0; // to avoid console.log spam on timerupdates
var ant_switch_denymixing = ext_get_cfg_param_string('ant_switch.denymixing', '', EXT_NO_SAVE);
var ant_switch_denyswitching = ext_get_cfg_param_string('ant_switch.denyswitching', '', EXT_NO_SAVE);

function ant_switch_main()
{
	ext_switch_to_client(ant_switch_ext_name, ant_switch_first_time, ant_switch_recv);		// tell server to use us (again)
	if (!ant_switch_first_time)
		ant_switch_controls_setup();
	ant_switch_first_time = false;
}

var ant_switch_cmd_e = { CMD1:0 };

function ant_switch_recv(data)
{
	var firstChars = getFirstChars(data, 3);

	// process data sent from server/C by ext_send_data_msg()
	if (firstChars == "DAT") {
		var ba = new Uint8Array(data, 4);
		var cmd = ba[0];

		if (cmd == ant_switch_cmd_e.CMD1) {
			// do something ...
		} else {
			console.log('ant_switch_recv: DATA UNKNOWN cmd='+ cmd +' len='+ (ba.length-1));
		}
		return;
	}

	// process command sent from server/C by ext_send_msg() or ext_send_encoded_msg()
	var stringData = arrayBufferToString(data);
	var params = stringData.substring(4).split(" ");

	for (var i=0; i < params.length; i++) {
		var param = params[i].split("=");

		switch (param[0]) {

			case "ready":
				ant_switch_controls_setup();
				break;

			case "Antenna":
				var arg = param[1];
                                ant_switch_process_reply(arg);
				break;
                        case "AntennaDenySwitching":
                                var arg = param[1];
                                if (arg == 1) ant_switch_denyswitching=1; else ant_switch_denyswitching=0;
                                ant_switch_showpermissions();
                                break;
                        case "AntennaDenyMixing":
                                var arg = param[1];
                                if (arg == 1) ant_switch_denymixing=1; else ant_switch_denymixing=0;
                                ant_switch_showpermissions();
                                break;
			default:
				console.log('ant_switch_recv: UNKNOWN CMD '+ param[0]);
				break;
		}
	}
}

function ant_switch_controls_setup()
{

   var buttons_html = '';
   var antdesc = [ ];
   var tmp;
   for (tmp=1; tmp<8; tmp++) antdesc[tmp] = ext_get_cfg_param_string('ant_switch.ant'+tmp+'desc', '', EXT_NO_SAVE);
   console.log('ant_switch: Antenna configuration');
   for (tmp = 1; tmp<8; tmp++) {
           if (antdesc[tmp] == undefined || antdesc[tmp] == null || antdesc[tmp] == '') {
                antdesc[tmp] = '';
           }  else {
                buttons_html+=w3_divs('','', w3_inline('', '', w3_btn('Antenna '+tmp, 'ant_switch_select_'+tmp),antdesc[tmp]));
           }
           console.log('ant_switch: Antenna '+ tmp +': '+ antdesc[tmp]);
   }

   buttons_html+=w3_inline('', '', w3_btn('Ground all', 'ant_switch_select_groundall'), 'Ground all antennas');
   console.log('ant_switch: Antenna g: Ground all antennas');
   var data_html =
      '

';
	var controls_html =
		w3_divs('id-ant_display-controls w3-text-white', '',
			data_html,
        		w3_divs('w3-container', 'w3-tspace-8',
			        w3_divs('', 'w3-medium w3-text-aqua', 'Antenna switch'),
                                w3_divs('id-ant-display-selected', '','Selected antenna: unknown'),
                                w3_divs('id-ant-display-permissions', '','Permissions: unknown'),
                                w3_divs('', '',buttons_html),
                                w3_divs('', '','')
                        )
		);

	ext_panel_show(controls_html, null, null);
	ant_switch_visible(1);
        ant_switch_poll();
}

function ant_switch_blur()
{
        kiwi_clearInterval(ant_switch_poll_interval);
	console.log('### ant_switch_blur');
	ant_switch_visible(0);		// hook to be called when controls panel is closed
}

// called to display HTML for configuration parameters in admin interface
function ant_switch_config_html()
{
        var denyswitching = ext_get_cfg_param('ant_switch.denyswitching', '', EXT_NO_SAVE);
        var denymixing = ext_get_cfg_param('ant_switch.denymixing', '', EXT_NO_SAVE);
	ext_admin_config(ant_switch_ext_name, 'Antenna switch',
		w3_divs('id-ant_switch w3-text-teal w3-hide', '',
			'Antenna switch configuration' +
			'
' +
			w3_divs('', 'w3-container',
				w3_divs('', 'w3-margin-bottom',
                                        w3_divs('', '','If antenna switching is denied then users cannot switch antennas. Admin can always switch antennas from KiwiSDR ssh root console using /usr/local/bin/ms-s7-web script.'),
                                        w3_divs('', '', 'Deny antenna switching? ' +
                                                w3_radio_btn('No', 'ant_switch.denyswitching', denyswitching? 0:1, 'ant_switch_conf_denyswitching') +
                                                w3_radio_btn('Yes', 'ant_switch.denyswitching', denyswitching? 1:0, 'ant_switch_conf_denyswitching')
                                        ),
                                        w3_divs('', '','If antenna mixing is denied then users can select only one antenna at time.'),
                                        w3_divs('', '', 'Deny antenna mixing? ' +
                                                w3_radio_btn('No', 'ant_switch.denymixing', denymixing? 0:1, 'ant_switch_conf_denymixing') +
                                                w3_radio_btn('Yes', 'ant_switch.denymixing', denymixing? 1:0, 'ant_switch_conf_denymixing')
                                        ),
                                        w3_divs('', '','
Antenna buttons configuration
'),
                                        w3_divs('', '','Leave Antenna description field empty if you want to hide antenna button from users
'),
					w3_input_get_param('Antenna 1 description', 'ant_switch.ant1desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna 2 description', 'ant_switch.ant2desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna 3 description', 'ant_switch.ant3desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna 4 description', 'ant_switch.ant4desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna 5 description', 'ant_switch.ant5desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna 6 description', 'ant_switch.ant6desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna 7 description', 'ant_switch.ant7desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna switch failure or unknown status decription', 'ant_switch.ant0desc', 'w3_string_set_cfg_cb')
				), '', ''
			)
		)
	);
}

function ant_switch_visible(v)
{
	visible_block('id-ant_switch-data', v);
}

function ant_switch_select_1(path,val) {
        ant_switch_select_antenna('1');
}
function ant_switch_select_2(path,val) {
        ant_switch_select_antenna('2');
}
function ant_switch_select_3(path,val) {
        ant_switch_select_antenna('3');
}
function ant_switch_select_4(path,val) {
        ant_switch_select_antenna('4');
}
function ant_switch_select_5(path,val) {
        ant_switch_select_antenna('5');
}
function ant_switch_select_6(path,val) {
        ant_switch_select_antenna('6');
}
function ant_switch_select_7(path,val) {
        ant_switch_select_antenna('7');
}

function ant_switch_select_groundall(path,val) {
        setTimeout('w3_radio_unhighlight('+ q(path) +')', w3_highlight_time);
        ant_switch_select_antenna('g');
}

function ant_switch_select_antenna(ant) {
        console.log('ant_switch: switching antenna '+ant);
	ext_send('SET Antenna='+ant);
        ext_send('GET Antenna');
}

function ant_switch_poll() {
        kiwi_clearInterval(ant_switch_poll_interval);
        ant_switch_poll_interval = setInterval(ant_switch_poll, 10000);
        ext_send('GET Antenna');
}

function ant_switch_process_reply(ant) {
        ant_selected_antenna = ant;
        var need_to_inform = false;

        if (ant_switch_exantennas != ant) {
                // antenna changed.
                need_to_inform = true;
                ant_switch_exantennas = ant;
        }

        if (ant == 'g') {
                if (need_to_inform) console.log('ant_switch: all antennas grouded');
                ant_switch_display_update('Thunderstorm mode. All antennas are grounded.');
        } else {
                if (need_to_inform) console.log('ant_switch: antenna '+ ant_selected_antenna +' in use');
                ant_switch_display_update('Selected antennas are now: '+ant_selected_antenna);
        }

        // update highlight
	var selected_antennas_list = ant.match(/([0-9])/g);
        var inputs = document.getElementsByTagName("button");
        for (var i = 0; i < inputs.length; i++) {
                var re=/^Antenna ([1-7])/i;
                if (inputs[i].textContent.match(re)) {
                        w3_unhighlight(inputs[i]);
                        for (var tmp=1; tmp<8; tmp++) {
                                var chr = String.fromCharCode(48 + tmp);
        		        if (selected_antennas_list != null && selected_antennas_list.indexOf(chr) >= 0) {
			                 if (inputs[i].textContent == 'Antenna '+tmp) w3_highlight(inputs[i]);
                                }
                        }
                }
	}
}

function ant_switch_lock_buttons(lock) {
        var inputs = document.getElementsByTagName("button");
        for (var i = 0; i < inputs.length; i++) {
                // ant 1-7
                var re=/^Antenna ([1-7])/i;
                if (inputs[i].textContent.match(re)) {
                        if (lock == true) {
                                inputs[i].disabled = true;
                        } else {
                                inputs[i].disabled = false;
                        }
                }
                // Ground All
                var re=/^Ground all$/i;
                if (inputs[i].textContent.match(re)) {
                        if (lock == true) {
                                inputs[i].disabled = true;
                        } else {
                                inputs[i].disabled = false;
                        }
                }

        }
}

function ant_switch_showpermissions() {
        if (ant_switch_denyswitching == 1) {
                ant_switch_lock_buttons(true);
                html('id-ant-display-permissions').innerHTML = 'Antenna switching is disabled by admin';
        } else {
                ant_switch_lock_buttons(false);
                if (ant_switch_denymixing == 1) {
                        html('id-ant-display-permissions').innerHTML = 'Antenna switching is allowed.';
                } else {
                        html('id-ant-display-permissions').innerHTML = 'Antenna switching and mixing is allowed.';
                }
        }
}

function ant_switch_display_update(ant) {
        // FIXME: How to notify other users about antenna changes?
        html('id-ant-display-selected').innerHTML = ant;
}

function ant_switch_conf_denyswitching(id, idx) {
        var tmp = ext_set_cfg_param(id, idx, EXT_SAVE);
}
function ant_switch_conf_denymixing(id, idx) {
        var tmp = ext_set_cfg_param(id, idx, EXT_SAVE);
}

<commit_msg>Update ant_switch.js<commit_after>// Copyright (c) 2017 Kari Karvonen, OH1KK

var ant_switch_ext_name = 'ant_switch';		// NB: must match ant_switch.c:ant_switch_ext.name
var ant_switch_first_time = true;
var ant_switch_poll_interval;
var ant_switch_exantennas=0; // to avoid console.log spam on timerupdates
var ant_switch_denymixing = ext_get_cfg_param_string('ant_switch.denymixing', '', EXT_NO_SAVE);
var ant_switch_denyswitching = ext_get_cfg_param_string('ant_switch.denyswitching', '', EXT_NO_SAVE);

function ant_switch_main()
{
	ext_switch_to_client(ant_switch_ext_name, ant_switch_first_time, ant_switch_recv);		// tell server to use us (again)
	if (!ant_switch_first_time)
		ant_switch_controls_setup();
	ant_switch_first_time = false;
}

var ant_switch_cmd_e = { CMD1:0 };

function ant_switch_recv(data)
{
	var firstChars = getFirstChars(data, 3);

	// process data sent from server/C by ext_send_data_msg()
	if (firstChars == "DAT") {
		var ba = new Uint8Array(data, 4);
		var cmd = ba[0];

		if (cmd == ant_switch_cmd_e.CMD1) {
			// do something ...
		} else {
			console.log('ant_switch_recv: DATA UNKNOWN cmd='+ cmd +' len='+ (ba.length-1));
		}
		return;
	}

	// process command sent from server/C by ext_send_msg() or ext_send_encoded_msg()
	var stringData = arrayBufferToString(data);
	var params = stringData.substring(4).split(" ");

	for (var i=0; i < params.length; i++) {
		var param = params[i].split("=");

		switch (param[0]) {

			case "ready":
				ant_switch_controls_setup();
				break;

			case "Antenna":
				var arg = param[1];
                                ant_switch_process_reply(arg);
				break;
                        case "AntennaDenySwitching":
                                var arg = param[1];
                                if (arg == 1) ant_switch_denyswitching=1; else ant_switch_denyswitching=0;
                                ant_switch_showpermissions();
                                break;
                        case "AntennaDenyMixing":
                                var arg = param[1];
                                if (arg == 1) ant_switch_denymixing=1; else ant_switch_denymixing=0;
                                ant_switch_showpermissions();
                                break;
			default:
				console.log('ant_switch_recv: UNKNOWN CMD '+ param[0]);
				break;
		}
	}
}

function ant_switch_controls_setup()
{

   var buttons_html = '';
   var antdesc = [ ];
   var tmp;
   for (tmp=1; tmp<8; tmp++) antdesc[tmp] = ext_get_cfg_param_string('ant_switch.ant'+tmp+'desc', '', EXT_NO_SAVE);
   console.log('ant_switch: Antenna configuration');
   for (tmp = 1; tmp<8; tmp++) {
           if (antdesc[tmp] == undefined || antdesc[tmp] == null || antdesc[tmp] == '') {
                antdesc[tmp] = '';
           }  else {
                buttons_html+=w3_divs('','', w3_inline('', '', w3_btn('Antenna '+tmp, 'ant_switch_select_'+tmp),antdesc[tmp]));
           }
           console.log('ant_switch: Antenna '+ tmp +': '+ antdesc[tmp]);
   }

   buttons_html+=w3_inline('', '', w3_btn('Ground all', 'ant_switch_select_groundall'), 'Ground all antennas');
   console.log('ant_switch: Antenna g: Ground all antennas');
   var data_html =
      '

';
	var controls_html =
		w3_divs('id-ant_display-controls w3-text-white', '',
			data_html,
        		w3_divs('w3-container', 'w3-tspace-8',
			        w3_divs('', 'w3-medium w3-text-aqua', 'Antenna switch'),
                                w3_divs('id-ant-display-selected', '','Selected antenna: unknown'),
                                w3_divs('id-ant-display-permissions', '','Permissions: unknown'),
                                w3_divs('', '',buttons_html),
                                w3_divs('', '','')
                        )
		);

	ext_panel_show(controls_html, null, null);
	ant_switch_visible(1);
        ant_switch_poll();
}

function ant_switch_blur()
{
        kiwi_clearInterval(ant_switch_poll_interval);
	console.log('### ant_switch_blur');
	ant_switch_visible(0);		// hook to be called when controls panel is closed
}

// called to display HTML for configuration parameters in admin interface
function ant_switch_config_html()
{
        var denyswitching = ext_get_cfg_param('ant_switch.denyswitching', '', EXT_NO_SAVE);
        var denymixing = ext_get_cfg_param('ant_switch.denymixing', '', EXT_NO_SAVE);
	ext_admin_config(ant_switch_ext_name, 'Antenna switch',
		w3_divs('id-ant_switch w3-text-teal w3-hide', '',
			'Antenna switch configuration' +
			'
' +
			w3_divs('', 'w3-container',
				w3_divs('', 'w3-margin-bottom',
                                        w3_divs('', '','If antenna switching is denied then users cannot switch antennas. Admin can always switch antennas from KiwiSDR ssh root console using /root/extensions/ant_switch/frontend/ant-switch-frontend script.'),
                                        w3_divs('', '', 'Deny antenna switching? ' +
                                                w3_radio_btn('No', 'ant_switch.denyswitching', denyswitching? 0:1, 'ant_switch_conf_denyswitching') +
                                                w3_radio_btn('Yes', 'ant_switch.denyswitching', denyswitching? 1:0, 'ant_switch_conf_denyswitching')
                                        ),
                                        w3_divs('', '','If antenna mixing is denied then users can select only one antenna at time.'),
                                        w3_divs('', '', 'Deny antenna mixing? ' +
                                                w3_radio_btn('No', 'ant_switch.denymixing', denymixing? 0:1, 'ant_switch_conf_denymixing') +
                                                w3_radio_btn('Yes', 'ant_switch.denymixing', denymixing? 1:0, 'ant_switch_conf_denymixing')
                                        ),
                                        w3_divs('', '','
Antenna buttons configuration
'),
                                        w3_divs('', '','Leave Antenna description field empty if you want to hide antenna button from users
'),
					w3_input_get_param('Antenna 1 description', 'ant_switch.ant1desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna 2 description', 'ant_switch.ant2desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna 3 description', 'ant_switch.ant3desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna 4 description', 'ant_switch.ant4desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna 5 description', 'ant_switch.ant5desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna 6 description', 'ant_switch.ant6desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna 7 description', 'ant_switch.ant7desc', 'w3_string_set_cfg_cb'),
					w3_input_get_param('Antenna switch failure or unknown status decription', 'ant_switch.ant0desc', 'w3_string_set_cfg_cb')
				), '', ''
			)
		)
	);
}

function ant_switch_visible(v)
{
	visible_block('id-ant_switch-data', v);
}

function ant_switch_select_1(path,val) {
        ant_switch_select_antenna('1');
}
function ant_switch_select_2(path,val) {
        ant_switch_select_antenna('2');
}
function ant_switch_select_3(path,val) {
        ant_switch_select_antenna('3');
}
function ant_switch_select_4(path,val) {
        ant_switch_select_antenna('4');
}
function ant_switch_select_5(path,val) {
        ant_switch_select_antenna('5');
}
function ant_switch_select_6(path,val) {
        ant_switch_select_antenna('6');
}
function ant_switch_select_7(path,val) {
        ant_switch_select_antenna('7');
}

function ant_switch_select_groundall(path,val) {
        setTimeout('w3_radio_unhighlight('+ q(path) +')', w3_highlight_time);
        ant_switch_select_antenna('g');
}

function ant_switch_select_antenna(ant) {
        console.log('ant_switch: switching antenna '+ant);
	ext_send('SET Antenna='+ant);
        ext_send('GET Antenna');
}

function ant_switch_poll() {
        kiwi_clearInterval(ant_switch_poll_interval);
        ant_switch_poll_interval = setInterval(ant_switch_poll, 10000);
        ext_send('GET Antenna');
}

function ant_switch_process_reply(ant) {
        ant_selected_antenna = ant;
        var need_to_inform = false;

        if (ant_switch_exantennas != ant) {
                // antenna changed.
                need_to_inform = true;
                ant_switch_exantennas = ant;
        }

        if (ant == 'g') {
                if (need_to_inform) console.log('ant_switch: all antennas grouded');
                ant_switch_display_update('Thunderstorm mode. All antennas are grounded.');
        } else {
                if (need_to_inform) console.log('ant_switch: antenna '+ ant_selected_antenna +' in use');
                ant_switch_display_update('Selected antennas are now: '+ant_selected_antenna);
        }

        // update highlight
	var selected_antennas_list = ant.match(/([0-9])/g);
        var inputs = document.getElementsByTagName("button");
        for (var i = 0; i < inputs.length; i++) {
                var re=/^Antenna ([1-7])/i;
                if (inputs[i].textContent.match(re)) {
                        w3_unhighlight(inputs[i]);
                        for (var tmp=1; tmp<8; tmp++) {
                                var chr = String.fromCharCode(48 + tmp);
        		        if (selected_antennas_list != null && selected_antennas_list.indexOf(chr) >= 0) {
			                 if (inputs[i].textContent == 'Antenna '+tmp) w3_highlight(inputs[i]);
                                }
                        }
                }
	}
}

function ant_switch_lock_buttons(lock) {
        var inputs = document.getElementsByTagName("button");
        for (var i = 0; i < inputs.length; i++) {
                // ant 1-7
                var re=/^Antenna ([1-7])/i;
                if (inputs[i].textContent.match(re)) {
                        if (lock == true) {
                                inputs[i].disabled = true;
                        } else {
                                inputs[i].disabled = false;
                        }
                }
                // Ground All
                var re=/^Ground all$/i;
                if (inputs[i].textContent.match(re)) {
                        if (lock == true) {
                                inputs[i].disabled = true;
                        } else {
                                inputs[i].disabled = false;
                        }
                }

        }
}

function ant_switch_showpermissions() {
        if (ant_switch_denyswitching == 1) {
                ant_switch_lock_buttons(true);
                html('id-ant-display-permissions').innerHTML = 'Antenna switching is disabled by admin';
        } else {
                ant_switch_lock_buttons(false);
                if (ant_switch_denymixing == 1) {
                        html('id-ant-display-permissions').innerHTML = 'Antenna switching is allowed.';
                } else {
                        html('id-ant-display-permissions').innerHTML = 'Antenna switching and mixing is allowed.';
                }
        }
}

function ant_switch_display_update(ant) {
        // FIXME: How to notify other users about antenna changes?
        html('id-ant-display-selected').innerHTML = ant;
}

function ant_switch_conf_denyswitching(id, idx) {
        var tmp = ext_set_cfg_param(id, idx, EXT_SAVE);
}
function ant_switch_conf_denymixing(id, idx) {
        var tmp = ext_set_cfg_param(id, idx, EXT_SAVE);
}

<|endoftext|>