<commit_before>const Config = require('./config.json');
const request = require('request');
const fs = require('fs');

var containerMangerUIServer = null;

const wait = ()=> {
	return new Promise((resolve,reject)=>{
		function get () {
			request.get("http://" + Config.localAppStoreName,(error,response,body)=>{
                                if(error) {
                                        console.log("[seeding manifest] waiting for appstore");
                                        setTimeout(get,4000);
                                } else {
					resolve();
				}
			});
			resolve();
		}
		setTimeout(get,2000);
	});
}

const seedFromGithub = (name)=> {
			return new Promise(function(resolve, reject) {
				url = "https://raw.githubusercontent.com/me-box/"+name+"/master/databox-manifest.json";
				req.get(url,(error,response,body)=>{
					if(error) {
						console.log("[seeding manifest] Failed to get manifest from" + url, error);
					}
					req.post({
							uri: "http://" + Config.localAppStoreName + "/app/post",
							method: "POST",
							form: {"manifest": body}
							}, (error,response,body) => {
								if(error) {
									console.log("[seeding manifest] Failed to POST manifest " + url, error);
								}
								resolve();
							});
				});
			});
}

const seedFromDisk = (name) => {
		return new Promise(function(resolve, reject) {

			let path = "./"+name+"/databox-manifest.json";
			fs.readFile(path,'utf8', (error,body)=>{
				if(error) {
					console.log("[seeding manifest] Failed to get manifest from " + path, error);
				}
				req.post({
						uri: "http://" + Config.localAppStoreName + "/app/post",
						method: "POST",
						form: {"manifest": body}
						}, (error,response,body) => {
							if(error) {
								console.log("[seeding manifest] Failed to POST manifest " + url, error);
							}
							resolve();
						});
			});
		});
}

const req = request.defaults({jar: true});
wait()
.then(()=>{
		return  new Promise(function(resolve, reject) {

			req.get("http://" + Config.localAppStoreName,(error,response,body)=>{
				if(error) {
					console.log("[seeding manifest] get app store root to log in", error);
					return reject();
				}

				let proms = []
				if(process.env.DATABOX_DEV == 1) {
					proms = Config.localAppStoreSeedManifests.map(seedFromDisk)
				} else {
					proms = Config.localAppStoreSeedManifests.map(seedFromGithub)
				}

				resolve(proms);
			});
		});
})
.then((pArray)=>{
	return Promise.all(pArray);
})
.then(()=>{
	console.log("[seeding manifest] Done");
})
.catch(err => {
	console.log(err);
	const stack = new Error().stack;
	console.log(stack);
});

<commit_msg>Fix for App-store connection error<commit_after>const Config = require('./config.json');
const request = require('request');
const fs = require('fs');

var containerMangerUIServer = null;

const wait = ()=> {
	return new Promise((resolve,reject)=>{
		function get () {
			request.get("http://" + Config.localAppStoreName,(error,response,body)=>{
                                if(error) {
                                        console.log("[seeding manifest] waiting for appstore");
                                        setTimeout(get,4000);
                                } else {
									resolve();
								}
			});
		}
		setTimeout(get,2000);
	});
}

const seedFromGithub = (name)=> {
			return new Promise(function(resolve, reject) {
				url = "https://raw.githubusercontent.com/me-box/"+name+"/master/databox-manifest.json";
				req.get(url,(error,response,body)=>{
					if(error) {
						console.log("[seeding manifest] Failed to get manifest from" + url, error);
					}
					req.post({
							uri: "http://" + Config.localAppStoreName + "/app/post",
							method: "POST",
							form: {"manifest": body}
							}, (error,response,body) => {
								if(error) {
									console.log("[seeding manifest] Failed to POST manifest " + url, error);
								}
								resolve();
							});
				});
			});
}

const seedFromDisk = (name) => {
		return new Promise(function(resolve, reject) {

			let path = "./"+name+"/databox-manifest.json";
			fs.readFile(path,'utf8', (error,body)=>{
				if(error) {
					console.log("[seeding manifest] Failed to get manifest from " + path, error);
				}
				req.post({
						uri: "http://" + Config.localAppStoreName + "/app/post",
						method: "POST",
						form: {"manifest": body}
						}, (error,response,body) => {
							if(error) {
								console.log("[seeding manifest] Failed to POST manifest " + url, error);
							}
							resolve();
						});
			});
		});
}

const req = request.defaults({jar: true});
wait()
.then(()=>{
		return  new Promise(function(resolve, reject) {

			req.get("http://" + Config.localAppStoreName,(error,response,body)=>{
				if(error) {
					console.log("[seeding manifest] get app store root to log in", error);
					return reject();
				}

				let proms = []
				if(process.env.DATABOX_DEV == 1) {
					proms = Config.localAppStoreSeedManifests.map(seedFromDisk)
				} else {
					proms = Config.localAppStoreSeedManifests.map(seedFromGithub)
				}

				resolve(proms);
			});
		});
})
.then((pArray)=>{
	return Promise.all(pArray);
})
.then(()=>{
	console.log("[seeding manifest] Done");
})
.catch(err => {
	console.log(err);
	const stack = new Error().stack;
	console.log(stack);
});

<|endoftext|>


<commit_before>var pk = pk || {};
/**
Create a new select control
@class pk.select
@constructor
@param options {Object}
@param options.element {Object} DOM element to convert to control
@param options.options {Object} Object array of control options
@param options.options.value {String} Option value
@param options.options.name {String} Option name (displayed label)
@param options.options.selected {Boolean} Option selected state
@param [options.value=0] {String} Value of initially selected option, defaults to the attribute value set on the passed element, or `0`
@param [options.name=pk-select-RandInt] {String} Name of underlying input control, defaults to the attribute value set on the passed element, or `pk-select-RandInt`
@param [options.placeholder=Please select...] {String} Placeholder when no options selected, defaults to the attribute value set on the passed element, or `Please select...`
@param [options.multiple=false] {Boolean} Whether to allow multiple options to be selected, defaults to the attribute value set on the passed element, or `false`
@param [options.dropdown=false] {Boolean} Display options in dropdown list
@param [options.tabindex=0] {Number} Tabindex of control, defaults to the attribute value set on the passed element, or `0`
@param [options.disabled=false] {Boolean} Disabled state of control, defaults to the attribute value set on the passed element, or `false`
@returns Object {Object} Consisting of original DOM element (item `0`) and class methods (see below)
@chainable
*/
(function(pk) {
    pk.select = function(opt) {

        var el = opt.element,
            options = opt.options || [],
            inputValue = opt.value || pk.attribute(el, 'value') || [],
            inputName = opt.name || pk.attribute(el, 'name') || 'pk-select-' + pk.getRand(1, 999),
            dropdown = Boolean(opt.dropdown),
            inputMultiple = (Boolean(opt.multiple) === true || pk.attribute(el, 'multiple')) ? true : false,
            inputPlaceholder = opt.placeholder || pk.attribute(el, 'placeholder') || 'Please select...',
            // listeners=opt.listeners === undefined ? {} : opt.listeners,
            inputDisabled = (opt.disabled || el.getAttribute('disabled')) ? 'disabled' : '',
            inputTabIndex = opt.tabindex || el.getAttribute('tabindex') || 0;

        inputName = (inputMultiple && inputName.indexOf('[]') === -1) ? inputName + '[]' : inputName.replace('[]', '');

        // input value is now an array
        inputValue = pk.toArr(inputValue);

        // populate options if none present and the underlying element is SELECT or UL
        if (options.length === 0 && (el.nodeName === "SELECT" || el.nodeName === "UL")) {
            for (var i = 0; i < el.children.length; i++) {
                var oVal = pk.attribute(el.children[i], 'value'),
                    oName = el.children[i].innerHTML;
                oVal = oVal || oName;
                if (pk.attribute(el.children[i], 'selected') && inputValue.indexOf(oVal) === -1) {
                    inputValue.push(oVal);
                }
                options.push({
                    name: oName,
                    value: oVal
                });
            }
        }

		 /*jshint multistr:true */
        var tpl = "
\
                <input type='hidden' name='" + inputName + "'/>\
                <div class='pk-select-value " + (!inputValue || inputValue.length < 1 ? 'pk-placeholder' : '') + "'>sdsd
\

";
        for (var o=0;o< options.length;o++) {
            tpl += "
" + options[o].name + "
";
        }
        tpl += "

";

        el.innerHTML = '';
        el = pk.replaceEl(el, tpl);

        var triggerEl = el.children[1],
            inputEl = el.children[0],
            optionsEl = el.children[2];

        if (dropdown && !inputDisabled) {
            var overlayEl = document.body.insertBefore(pk.createEl("

"), document.body.children[0]);
            pk.bindEvent('click', overlayEl, function() {
                pk.removeClass(overlayEl, 'pk-show');
                pk.toggleClass(el, 'pk-show');
            });
            pk.bindEvent('click', el, function(e) {

                if (pk.attribute(e.target, 'data-value') && pk.hasClass(e.target, 'pk-select-value-tag')) {
                    inputValue = pk.collide(inputValue, pk.attribute(e.target, 'data-value'), 2);
                    updateValue();
                }

                if (pk.hasClass(e.target, 'pk-select-value-tag') || (inputMultiple && pk.hasClass(e.target, 'pk-option')) || !pk.hasClass(el, 'pk-show')) {
                    pk.addClass(overlayEl, 'pk-show');
                    pk.addClass(el, 'pk-show');
                } else {
                    pk.removeClass(overlayEl, 'pk-show');
                    pk.removeClass(el, 'pk-show');
                }

            });
        }

        function updateValue() {
            var valueHTML = '';
            if (!inputMultiple) {
                inputValue.splice(1, inputValue.length - 1);
            }
            for (var o =0; o < options.length; o++) {
                options[o].selected = (inputValue.indexOf(options[o].value) !== -1) ? true : false;
                pk.toggleClass(optionsEl.children[o], 'pk-selected', options[o].selected);
                if (options[o].selected) {
                    valueHTML = inputMultiple ? valueHTML += "" + options[o].name + "" : options[o].name;
                }
            }
            triggerEl.innerHTML = valueHTML ? valueHTML : inputPlaceholder;
            if (inputValue.length < 1) {
                pk.addClass(triggerEl, 'pk-placeholder');
            } else {
                pk.removeClass(triggerEl, 'pk-placeholder');
            }
            // update underlying input element
            inputEl.value = inputMultiple ? inputValue : inputValue.join('');
        }
        if (!inputDisabled) {
            pk.bindEvent('click', optionsEl, function(e) {
                if (e.target.nodeName === "LI") {
                    inputValue = inputMultiple ? pk.collide(inputValue, options[pk.getIndex(e.target)].value, 3) : pk.collide(inputValue, options[pk.getIndex(e.target)].value);
                    updateValue();
                }
            });
        }
        updateValue();
		return {
			0:el
		}
    };
    return pk;
})(pk);
<commit_msg>Update select.js<commit_after>var pk = pk || {};
/**
Create a new select control
@class pk.select
@constructor
@param options {Object}
@param options.element {Object} DOM element to convert to control
@param options.options {Object} Object array of control options
@param options.options.value {String} Option value
@param options.options.name {String} Option name (displayed label)
@param options.options.selected {Boolean} Option selected state
@param [options.value=0] {String} Value of initially selected option, defaults to the attribute value set on the passed element, or `0`
@param [options.name=pk-select-RandInt] {String} Name of underlying input control, defaults to the attribute value set on the passed element, or `pk-select-RandInt`
@param [options.placeholder=string] {String} Placeholder when no options selected, defaults to the attribute value set on the passed element, or `Please select...`
@param [options.multiple=false] {Boolean} Whether to allow multiple options to be selected, defaults to the attribute value set on the passed element, or `false`
@param [options.dropdown=false] {Boolean} Display options in dropdown list
@param [options.tabindex=0] {Number} Tabindex of control, defaults to the attribute value set on the passed element, or `0`
@param [options.disabled=false] {Boolean} Disabled state of control, defaults to the attribute value set on the passed element, or `false`
@returns Object {Object} Consisting of original DOM element (item `0`) and class methods (see below)
@chainable
*/
(function(pk) {
    pk.select = function(opt) {

        var el = opt.element,
            options = opt.options || [],
            inputValue = opt.value || pk.attribute(el, 'value') || [],
            inputName = opt.name || pk.attribute(el, 'name') || 'pk-select-' + pk.getRand(1, 999),
            dropdown = Boolean(opt.dropdown),
            inputMultiple = (Boolean(opt.multiple) === true || pk.attribute(el, 'multiple')) ? true : false,
            inputPlaceholder = opt.placeholder || pk.attribute(el, 'placeholder') || 'Please select...',
            // listeners=opt.listeners === undefined ? {} : opt.listeners,
            inputDisabled = (opt.disabled || el.getAttribute('disabled')) ? 'disabled' : '',
            inputTabIndex = opt.tabindex || el.getAttribute('tabindex') || 0;

        inputName = (inputMultiple && inputName.indexOf('[]') === -1) ? inputName + '[]' : inputName.replace('[]', '');

        // input value is now an array
        inputValue = pk.toArr(inputValue);

        // populate options if none present and the underlying element is SELECT or UL
        if (options.length === 0 && (el.nodeName === "SELECT" || el.nodeName === "UL")) {
            for (var i = 0; i < el.children.length; i++) {
                var oVal = pk.attribute(el.children[i], 'value'),
                    oName = el.children[i].innerHTML;
                oVal = oVal || oName;
                if (pk.attribute(el.children[i], 'selected') && inputValue.indexOf(oVal) === -1) {
                    inputValue.push(oVal);
                }
                options.push({
                    name: oName,
                    value: oVal
                });
            }
        }

        /*jshint multistr:true */
        var tpl = "
\
                <input type='hidden' name='" + inputName + "'/>\
                <div class='pk-select-value " + (!inputValue || inputValue.length < 1 ? 'pk-placeholder' : '') + "'>sdsd
\

";
        for (var o = 0; o < options.length; o++) {
            tpl += "
" + options[o].name + "
";
        }
        tpl += "

";

        el.innerHTML = '';
        el = pk.replaceEl(el, tpl);

        var triggerEl = el.children[1],
            inputEl = el.children[0],
            optionsEl = el.children[2];

        if (dropdown && !inputDisabled) {
            var overlayEl = document.body.insertBefore(pk.createEl("

"), document.body.children[0]);
            pk.bindEvent('click', overlayEl, function() {
                pk.removeClass(overlayEl, 'pk-show');
                pk.toggleClass(el, 'pk-show');
            });
            pk.bindEvent('click', el, function(e) {

                if (pk.attribute(e.target, 'data-value') && pk.hasClass(e.target, 'pk-select-value-tag')) {
                    inputValue = pk.collide(inputValue, pk.attribute(e.target, 'data-value'), 2);
                    updateValue();
                }

                if (pk.hasClass(e.target, 'pk-select-value-tag') || (inputMultiple && pk.hasClass(e.target, 'pk-option')) || !pk.hasClass(el, 'pk-show')) {
                    pk.addClass(overlayEl, 'pk-show');
                    pk.addClass(el, 'pk-show');
                } else {
                    pk.removeClass(overlayEl, 'pk-show');
                    pk.removeClass(el, 'pk-show');
                }

            });
        }

        function updateValue() {
            var valueHTML = '';
            if (!inputMultiple) {
                inputValue.splice(1, inputValue.length - 1);
            }
            for (var o = 0; o < options.length; o++) {
                options[o].selected = (inputValue.indexOf(options[o].value) !== -1) ? true : false;
                pk.toggleClass(optionsEl.children[o], 'pk-selected', options[o].selected);
                if (options[o].selected) {
                    valueHTML = inputMultiple ? valueHTML += "" + options[o].name + "" : options[o].name;
                }
            }
            triggerEl.innerHTML = valueHTML ? valueHTML : inputPlaceholder;
            if (inputValue.length < 1) {
                pk.addClass(triggerEl, 'pk-placeholder');
            } else {
                pk.removeClass(triggerEl, 'pk-placeholder');
            }
            // update underlying input element
            inputEl.value = inputMultiple ? inputValue : inputValue.join('');
        }
        if (!inputDisabled) {
            pk.bindEvent('click', optionsEl, function(e) {
                if (e.target.nodeName === "LI") {
                    inputValue = inputMultiple ? pk.collide(inputValue, options[pk.getIndex(e.target)].value, 3) : pk.collide(inputValue, options[pk.getIndex(e.target)].value);
                    updateValue();
                }
            });
        }
        updateValue();
        return {
            0: el
        };
    };
    return pk;
})(pk);
<|endoftext|>


<commit_before>export default (reactString, initialData, webserver) => {
  const css = process.env.NODE_ENV === 'production'
    ? `<link rel='stylesheet' href='${webserver}/dist/styles.css'>`
    : '';

  return (
    `<!doctype html>

        <meta charset='utf-8'>
        <title>Hapi Universal Redux</title>
        <link rel='shortcut icon' href='/favicon.ico'>
        ${css}

${reactString}

    `
  );
};
<commit_msg>Small syntax change in markup<commit_after>export default (reactString, initialData, webserver) => {
  const stylesheet = process.env.NODE_ENV === 'production'
    ? `<link rel='stylesheet' href='${webserver}/dist/styles.css'>`
    : '';

  return (
    `<!doctype html>

        <meta charset='utf-8'>
        <title>Hapi Universal Redux</title>
        <link rel='shortcut icon' href='/favicon.ico'>
        ${stylesheet}

${reactString}

    `
  );
};
<|endoftext|>


<commit_before>const app = require('./server-config.js');
const port = process.env.PORT || 8080;
const redis = require('redis');
const bluebird = require('bluebird');

bluebird.promisifyAll(redis.RedisClient.prototype);

const redisCl = redis.createClient();
// UNCOMMENT to run/////////////////////////
// redisCL = redis.createClient();
const server = app.listen(port);

console.log('Server now listening on port ' + port);

module.exports = {'server': server,
									'redis': redisCl}<commit_msg>(refactor) implement changes based on travis feedback<commit_after>const app = require('./server-config.js');
const port = process.env.PORT || 8080;
const redis = require('redis');
const bluebird = require('bluebird');

bluebird.promisifyAll(redis.RedisClient.prototype);

const redisCl = null;
// const redisCl = redis.createClient();
// UNCOMMENT to run/////////////////////////
// redisCL = redis.createClient();
const server = app.listen(port);

console.log('Server now listening on port ' + port);

module.exports = {'server': server,
									'redis': redisCl}<|endoftext|>


<commit_before>/**
 *
 * Server - boots the SuperCollider synthesis server
 *
 *  SuperCollider comes with an executable called scsynth
 *  which can be communicated with via udp OSC
 *
 *  The primary way to send messages in with sendMsg
 *  eg. server.sendMsg('/s_new', ['defName', 440])

 *  and the responses are emitted as 'OSC'
 *  eg. server.on('OSC', function(msg) {  ...  });
 *
 * methods:
 *   boot        - boot an scsynth process
 *   quit
 *   connect     - connect via udp OSC
 *   disconnect
 *   sendMsg     - send an OSC message
 *
 * emits:
 *    'out'   - stdout text from the server
 *    'error' - stderr text from the server or OSC error messages
 *    'exit'  - when server exits
 *    'close' - when server closes the UDP connection
 *    'OSC'   - OSC responses from the server
 */

import {EventEmitter} from 'events';
import {Observable, Subject} from 'Rx';
import {spawn} from 'child_process';
import * as _ from 'underscore';
import * as dgram from 'dgram';
import * as osc from 'osc-min';
import Immutable from 'immutable';
import {Promise} from 'bluebird';

import * as alloc from './internals/allocators';
import SendOSC from './internals/send-osc';
import {parseMessage} from './osc/utils';
import {watchNodeNotifications} from './node-watcher';
import defaultOptions from './default-server-options';
import Logger from '../utils/Logger';
import resolveOptions from '../utils/resolveOptions';

const keys = {
  NODE_IDS: 'nodeAllocator',
  CONTROL_BUSSES: 'controlBusAllocator',
  AUDIO_BUSSES: 'audioBusAllocator',
  BUFFERS: 'bufferAllocator'
};

function _noop() {}

export class Server extends EventEmitter {

  /**
   * @param {Object} options - command line options for scsynth
   */
  constructor(options={}) {
    super();
    this.options = _.defaults(options, defaultOptions);
    this.process = null;
    this.isRunning = false;

    // subscribeable streams
    this.send = new SendOSC();
    this.receive = new Subject();
    this.stdout = new Subject();
    this.processEvents = new Subject();

    this._initLogger();
    this._initEmitter();
    this._initSender();
    watchNodeNotifications(this);

    this._serverObservers = {};
    this.resetState();
  }

  _initLogger() {
    this.log = new Logger(this.options.debug, this.options.echo);
    this.send.subscribe((event) => {
      // will be a type:msg or type:bundle
      var out;
      if (event.type === 'msg') {
        out = event.payload.join(' ');
      } else {
        out = String(event.payload);
      }
      if (!this.osc) {
        out = '[NOT CONNECTED] ' + out;
      }
      this.log.sendosc(out);
    });
    this.receive.subscribe((o) => this.log.rcvosc(o), (err) => this.log.err(err));
    this.stdout.subscribe((o) => this.log.stdout(o), (o) => this.log.stderr(o));
    this.processEvents.subscribe((o) => this.log.dbug(o), (o) => this.log.err(o));
  }
  _initEmitter() {
    // emit signals are deprecated.
    // use server.{channel}.subscribe((event) => { })
    this.receive.subscribe((msg) => {
      this.emit('OSC', msg);
    });
    this.processEvents.subscribe(_noop, (err) => this.emit('exit', err));
    this.stdout.subscribe((out) => this.emit('out', out), (out) => this.emit('stderr', out));
  }
  _initSender() {
    this.send.on('msg', (msg) => {
      if (this.osc) {
        var buf = osc.toBuffer({
          address: msg[0],
          args: msg.slice(1)
        });
        this.osc.send(buf, 0, buf.length, this.options.serverPort, this.options.host);
      }
    });
  }

  resetState() {
    // mutate
    var state = Immutable.Map();
    state = state.set(keys.NODE_IDS, this.options.initialNodeID - 1);

    var numAudioChannels = this.options.numPrivateAudioBusChannels +
      this.options.numInputBusChannels +
      this.options.numOutputBusChannels;
    var ab = alloc.initialBlockState(numAudioChannels);
    ab = alloc.reserveBlock(ab, 0, this.options.numInputBusChannels + this.options.numOutputBusChannels);
    state = state.set(keys.AUDIO_BUSSES, ab);

    var cb = alloc.initialBlockState(this.options.numControlBusChannels);
    state = state.set(keys.CONTROL_BUSSES, cb);

    var bb = alloc.initialBlockState(this.options.numBuffers);
    state = state.set(keys.BUFFERS, cb);

    this.state = state;
  }

  /**
   * Format command line args for scsynth
   *
   * not yet fully implemented
   *
   * @return {array} list of non-default args
   */
  args() {
    var o = [];
    // o.push(this.options.protocol === 'udp' ? '-u' : '-t');
    o.push('-u');  // only udp socket is implemented right now
    o.push(this.options.serverPort);
    return o;
  }

  /**
   * Boot the server
   *
   * Start scsynth and establish a pipe connection to receive stdout and stderr.
   *
   * Does not connect, so UDP is not yet ready for OSC communication.
   *
   * listen for system events and emit: exit out error
   */
  boot() {
    return new Promise((resolve, reject) => {
      var
        self = this,
        execPath = this.options.scsynth,
        args = this.args();

      this.isRunning = false;

      this.processEvents.onNext('Start process: ' + execPath + ' ' + args.join(' '));
      this.process = spawn(execPath, args, {
        cwd: this.options.cwd
      });
      this.processEvents.onNext('pid: ' + this.process.pid);

      // when this parent process dies, kill child process
      process.on('exit', (code) => {
        if (this.process) {
          this.process.kill('SIGTERM');
        }
      });

      this.process.on('error', (err) => {
        this.processEvents.onError(err);
        this.isRunning = false;
        // this.disconnect()
      });
      this.process.on('close', (code, signal) => {
        this.processEvents.onError('Server closed. Exit code: ' + code + ' signal: ' + signal);
        this.isRunning = false;
        // this.disconnect()
      });
      this.process.on('exit', (code, signal) => {
        this.processEvents.onError('Server exited. Exit code: ' + code + ' signal: ' + signal);
        this.isRunning = false;
        // this.disconnect()
      });

      this._serverObservers.stdout = Observable.fromEvent(this.process.stdout, 'data', (data) => String(data));
      this._serverObservers.stdout.subscribe((e) => this.stdout.onNext(e));
      this._serverObservers.stderr = Observable.fromEvent(this.process.stderr, 'data')
        .subscribe((out) => {
          // just pipe it into the stdout object's error stream
          this.stdout.onError(out);
        });

      // watch for ready message
      this._serverObservers.stdout.takeWhile((text) => {
        return !(text.match(/SuperCollider 3 server ready/));
      })
        .subscribe((next) => {},
          this.log.err,
          () => { // onComplete
            this.isRunning = true;
            resolve(this);
          });

      setTimeout(() => {
        if (!this.isRunning) {
          reject();
        }
      }, 3000);
    });
  }

  /**
   * quit
   *
   * kill scsynth process
   * TODO: should send /quit first for shutting files
   */
  quit() {
    if (this.process) {
      this.disconnect();
      this.process.kill('SIGTERM');
      this.process = null;
    }
  }

  /**
   * Establish connection to scsynth via OSC socket
   *
   * @returns {Promise} - resolves when udp responds
   */
  connect() {
    return new Promise((resolve, reject) => {
      const udpListening = 'udp is listening';

      this.osc = dgram.createSocket('udp4');

      this.osc.on('listening', () => {
        this.processEvents.onNext(udpListening);
        resolve();
      });
      this.osc.on('close', (e) => {
        this.processEvents.onNext('udp closed: ' + e);
        this.disconnect();
      });

      // pipe events to this.receive
      this._serverObservers.oscMessage = Observable.fromEvent(this.osc, 'message', (msgbuf) => osc.fromBuffer(msgbuf));
      this._serverObservers.oscMessage.subscribe((e) => this.receive.onNext(parseMessage(e)));

      this._serverObservers.oscError = Observable.fromEvent(this.osc, 'error');
      this._serverObservers.oscError.subscribe((e) => {
        this.receive.onError(e);
        reject(e);
      });

      // this will trigger a response from server
      // and a udp listening event and the promise will resolve
      // thus we know for sure that we are connected
      this.sendMsg('/notify', [1]);
    });
  }

  disconnect() {
    if (this.osc) {
      this.osc.close();
      delete this.osc;
    }
    this._serverObservers.forEach((obs, k) => {
      obs.dispose();
    });
    this._serverObservers = {};
  }

  /**
   * Send OSC message to server
   *
   * @deprecated - use: `server.send.msg([address, arg1, arg2])``
   * @param {String} address - OSC command, referred to as address
   * @param {Array} args
   */
  sendMsg(address, args) {
    this.send.msg([address].concat(args));
  }

  /**
   * Wait for a single OSC response from server matching the supplied args.
   *
   * This is for getting responses async from the server.
   * The first part of the message matches the expected args,
   * and the rest of the message contains the response.
   *
   * The Promise fullfills with any remaining payload including in the message.
   *
   * @param {Array} matchArgs - osc message to match as a single array: `[/done, /notify]`
   * @param {int} timeout - in milliseconds before the Promise is rejected
   * @returns {Promise}
   */
  oscOnce(matchArgs, timeout=4000) {
    return new Promise((resolve, reject) => {
      var subscription = this.receive.subscribe((msg) => {
        var command = msg.slice(0, matchArgs.length);
        if (_.isEqual(command, matchArgs)) {
          var payload = msg.slice(matchArgs.length);
          resolve(payload);
          dispose();
        }
      });

      // if timeout then reject and dispose
      var tid = setTimeout(() => {
        dispose();
        reject('Timed out waiting for OSC response: ' + args);
      }, timeout);

      function dispose() {
        subscription.dispose();
        clearTimeout(tid);
      }
    });
  }

  /**
   * Send an OSC command that expects a reply from the server.
   * Promise fullfills with anything the server response includes
   * after the matched response.
   *
   * @param {Object} callAndResponse - {call: [...], response: [...]}
   * @param {int} timeout
   */
  callAndResponse(callAndResponse, timeout=4000) {
    var promise = this.oscOnce(callAndResponse.response, timeout);
    this.send.msg(callAndResponse.call);
    return promise;
  }

  /**
   * @returns {int}
   */
  nextNodeID() {
    return this.mutateStateAndReturn(keys.NODE_IDS, alloc.increment);
  }

  // temporary raw allocator calls
  allocAudioBus(numChannels=1) {
    return this._allocBlock(keys.AUDIO_BUSSES, numChannels);
  }
  allocControlBus(numChannels=1) {
    return this._allocBlock(keys.CONTROL_BUSSES, numChannels);
  }
  /**
   * Allocate a buffer id.
   *
   * Note that numChannels is specified when creating the buffer.
   *
   * @param {int} numConsecutive - consecutively numbered buffers are needed by VOsc and VOsc3.
   * @returns {int}
   */
  allocBufferID(numConsecutive=1) {
    return this._allocBlock(keys.BUFFERS, numConsecutive);
  }

  // these require you to remember the channels and mess it up
  // if you free it wrong
  freeAudioBus(index, numChannels) {
    return this._freeBlock(keys.AUDIO_BUSSES, index, numChannels);
  }
  freeControlBus(index, numChannels) {
    return this._freeBlock(keys.CONTROL_BUSSES, index, numChannels);
  }
  freeBuffer(index, numChannels) {
    return this._freeBlock(keys.BUFFERS, index, numChannels);
  }

  /**
   * Fetch one part of the state,
   * mutate it with the callback,
   * save state and return the result.
   *
   * @returns {any} result
   */
  mutateStateAndReturn(key, fn) {
    var result, state;
    [result, state] = fn(this.state.get(key));
    this.state = this.state.set(key, state);
    return result;
  }
  mutateState(key, fn) {
    this.state = this.state.update(key, Immutable.Map(), fn);
  }

  _allocBlock(key, numChannels) {
    return this.mutateStateAndReturn(key,
      (state) => alloc.allocBlock(state, numChannels));
  }
  _freeBlock(key, index, numChannels) {
    return this.mutateState(key,
      (state) => alloc.freeBlock(state, index, numChannels));
  }
}

/**
 * Boot a server with options and connect
 *
 * @returns {Promise} - resolves with the Server
 */
export function boot(options) {
  return resolveOptions(undefined, options).then((opts) => {
    var s = new Server(opts);
    return s.boot().then(() => s.connect()).then(() => s);
  });
}
<commit_msg>server: resolve after /notify has a response<commit_after>/**
 *
 * Server - boots the SuperCollider synthesis server
 *
 *  SuperCollider comes with an executable called scsynth
 *  which can be communicated with via udp OSC
 *
 *  The primary way to send messages in with sendMsg
 *  eg. server.sendMsg('/s_new', ['defName', 440])

 *  and the responses are emitted as 'OSC'
 *  eg. server.on('OSC', function(msg) {  ...  });
 *
 * methods:
 *   boot        - boot an scsynth process
 *   quit
 *   connect     - connect via udp OSC
 *   disconnect
 *   sendMsg     - send an OSC message
 *
 * emits:
 *    'out'   - stdout text from the server
 *    'error' - stderr text from the server or OSC error messages
 *    'exit'  - when server exits
 *    'close' - when server closes the UDP connection
 *    'OSC'   - OSC responses from the server
 */

import {EventEmitter} from 'events';
import {Observable, Subject} from 'Rx';
import {spawn} from 'child_process';
import * as _ from 'underscore';
import * as dgram from 'dgram';
import * as osc from 'osc-min';
import Immutable from 'immutable';
import {Promise} from 'bluebird';

import * as alloc from './internals/allocators';
import SendOSC from './internals/send-osc';
import {parseMessage} from './osc/utils';
import {notify} from './osc/msg';
import {watchNodeNotifications} from './node-watcher';
import defaultOptions from './default-server-options';
import Logger from '../utils/Logger';
import resolveOptions from '../utils/resolveOptions';

const keys = {
  NODE_IDS: 'nodeAllocator',
  CONTROL_BUSSES: 'controlBusAllocator',
  AUDIO_BUSSES: 'audioBusAllocator',
  BUFFERS: 'bufferAllocator'
};

function _noop() {}

export class Server extends EventEmitter {

  /**
   * @param {Object} options - command line options for scsynth
   */
  constructor(options={}) {
    super();
    this.options = _.defaults(options, defaultOptions);
    this.process = null;
    this.isRunning = false;

    // subscribeable streams
    this.send = new SendOSC();
    this.receive = new Subject();
    this.stdout = new Subject();
    this.processEvents = new Subject();

    this._initLogger();
    this._initEmitter();
    this._initSender();
    watchNodeNotifications(this);

    this._serverObservers = {};
    this.resetState();
  }

  _initLogger() {
    this.log = new Logger(this.options.debug, this.options.echo);
    this.send.subscribe((event) => {
      // will be a type:msg or type:bundle
      var out;
      if (event.type === 'msg') {
        out = event.payload.join(' ');
      } else {
        out = String(event.payload);
      }
      if (!this.osc) {
        out = '[NOT CONNECTED] ' + out;
      }
      this.log.sendosc(out);
    });
    this.receive.subscribe((o) => this.log.rcvosc(o), (err) => this.log.err(err));
    this.stdout.subscribe((o) => this.log.stdout(o), (o) => this.log.stderr(o));
    this.processEvents.subscribe((o) => this.log.dbug(o), (o) => this.log.err(o));
  }
  _initEmitter() {
    // emit signals are deprecated.
    // use server.{channel}.subscribe((event) => { })
    this.receive.subscribe((msg) => {
      this.emit('OSC', msg);
    });
    this.processEvents.subscribe(_noop, (err) => this.emit('exit', err));
    this.stdout.subscribe((out) => this.emit('out', out), (out) => this.emit('stderr', out));
  }
  _initSender() {
    this.send.on('msg', (msg) => {
      if (this.osc) {
        var buf = osc.toBuffer({
          address: msg[0],
          args: msg.slice(1)
        });
        this.osc.send(buf, 0, buf.length, this.options.serverPort, this.options.host);
      }
    });
  }

  resetState() {
    // mutate
    var state = Immutable.Map();
    state = state.set(keys.NODE_IDS, this.options.initialNodeID - 1);

    var numAudioChannels = this.options.numPrivateAudioBusChannels +
      this.options.numInputBusChannels +
      this.options.numOutputBusChannels;
    var ab = alloc.initialBlockState(numAudioChannels);
    ab = alloc.reserveBlock(ab, 0, this.options.numInputBusChannels + this.options.numOutputBusChannels);
    state = state.set(keys.AUDIO_BUSSES, ab);

    var cb = alloc.initialBlockState(this.options.numControlBusChannels);
    state = state.set(keys.CONTROL_BUSSES, cb);

    var bb = alloc.initialBlockState(this.options.numBuffers);
    state = state.set(keys.BUFFERS, cb);

    this.state = state;
  }

  /**
   * Format command line args for scsynth
   *
   * not yet fully implemented
   *
   * @return {array} list of non-default args
   */
  args() {
    var o = [];
    // o.push(this.options.protocol === 'udp' ? '-u' : '-t');
    o.push('-u');  // only udp socket is implemented right now
    o.push(this.options.serverPort);
    return o;
  }

  /**
   * Boot the server
   *
   * Start scsynth and establish a pipe connection to receive stdout and stderr.
   *
   * Does not connect, so UDP is not yet ready for OSC communication.
   *
   * listen for system events and emit: exit out error
   */
  boot() {
    return new Promise((resolve, reject) => {
      var
        self = this,
        execPath = this.options.scsynth,
        args = this.args();

      this.isRunning = false;

      this.processEvents.onNext('Start process: ' + execPath + ' ' + args.join(' '));
      this.process = spawn(execPath, args, {
        cwd: this.options.cwd
      });
      this.processEvents.onNext('pid: ' + this.process.pid);

      // when this parent process dies, kill child process
      process.on('exit', (code) => {
        if (this.process) {
          this.process.kill('SIGTERM');
        }
      });

      this.process.on('error', (err) => {
        this.processEvents.onError(err);
        this.isRunning = false;
        // this.disconnect()
      });
      this.process.on('close', (code, signal) => {
        this.processEvents.onError('Server closed. Exit code: ' + code + ' signal: ' + signal);
        this.isRunning = false;
        // this.disconnect()
      });
      this.process.on('exit', (code, signal) => {
        this.processEvents.onError('Server exited. Exit code: ' + code + ' signal: ' + signal);
        this.isRunning = false;
        // this.disconnect()
      });

      this._serverObservers.stdout = Observable.fromEvent(this.process.stdout, 'data', (data) => String(data));
      this._serverObservers.stdout.subscribe((e) => this.stdout.onNext(e));
      this._serverObservers.stderr = Observable.fromEvent(this.process.stderr, 'data')
        .subscribe((out) => {
          // just pipe it into the stdout object's error stream
          this.stdout.onError(out);
        });

      // watch for ready message
      this._serverObservers.stdout.takeWhile((text) => {
        return !(text.match(/SuperCollider 3 server ready/));
      })
        .subscribe((next) => {},
          this.log.err,
          () => { // onComplete
            this.isRunning = true;
            resolve(this);
          });

      setTimeout(() => {
        if (!this.isRunning) {
          reject();
        }
      }, 3000);
    });
  }

  /**
   * quit
   *
   * kill scsynth process
   * TODO: should send /quit first for shutting files
   */
  quit() {
    if (this.process) {
      this.disconnect();
      this.process.kill('SIGTERM');
      this.process = null;
    }
  }

  /**
   * Establish connection to scsynth via OSC socket
   *
   * @returns {Promise} - resolves when udp responds
   */
  connect() {
    return new Promise((resolve, reject) => {
      const udpListening = 'udp is listening';

      this.osc = dgram.createSocket('udp4');

      this.osc.on('listening', () => {
        this.processEvents.onNext(udpListening);
      });
      this.osc.on('close', (e) => {
        this.processEvents.onNext('udp closed: ' + e);
        this.disconnect();
      });

      // pipe events to this.receive
      this._serverObservers.oscMessage = Observable.fromEvent(this.osc, 'message', (msgbuf) => osc.fromBuffer(msgbuf));
      this._serverObservers.oscMessage.subscribe((e) => this.receive.onNext(parseMessage(e)));

      this._serverObservers.oscError = Observable.fromEvent(this.osc, 'error');
      this._serverObservers.oscError.subscribe((e) => {
        this.receive.onError(e);
        reject(e);
      });

      // this will trigger a response from server
      // which will cause a udp listening event.
      // After server responds then we are truly connected.
      this.callAndResponse(notify()).then(() => {
        resolve();
      });
    });
  }

  disconnect() {
    if (this.osc) {
      this.osc.close();
      delete this.osc;
    }
    this._serverObservers.forEach((obs, k) => {
      obs.dispose();
    });
    this._serverObservers = {};
  }

  /**
   * Send OSC message to server
   *
   * @deprecated - use: `server.send.msg([address, arg1, arg2])``
   * @param {String} address - OSC command, referred to as address
   * @param {Array} args
   */
  sendMsg(address, args) {
    this.send.msg([address].concat(args));
  }

  /**
   * Wait for a single OSC response from server matching the supplied args.
   *
   * This is for getting responses async from the server.
   * The first part of the message matches the expected args,
   * and the rest of the message contains the response.
   *
   * The Promise fullfills with any remaining payload including in the message.
   *
   * @param {Array} matchArgs - osc message to match as a single array: `[/done, /notify]`
   * @param {int} timeout - in milliseconds before the Promise is rejected
   * @returns {Promise}
   */
  oscOnce(matchArgs, timeout=4000) {
    return new Promise((resolve, reject) => {
      var subscription = this.receive.subscribe((msg) => {
        var command = msg.slice(0, matchArgs.length);
        if (_.isEqual(command, matchArgs)) {
          var payload = msg.slice(matchArgs.length);
          resolve(payload);
          dispose();
        }
      });

      // if timeout then reject and dispose
      var tid = setTimeout(() => {
        dispose();
        reject('Timed out waiting for OSC response: ' + args);
      }, timeout);

      function dispose() {
        subscription.dispose();
        clearTimeout(tid);
      }
    });
  }

  /**
   * Send an OSC command that expects a reply from the server.
   * Promise fullfills with anything the server response includes
   * after the matched response.
   *
   * @param {Object} callAndResponse - {call: [...], response: [...]}
   * @param {int} timeout
   */
  callAndResponse(callAndResponse, timeout=4000) {
    var promise = this.oscOnce(callAndResponse.response, timeout);
    this.send.msg(callAndResponse.call);
    return promise;
  }

  /**
   * @returns {int}
   */
  nextNodeID() {
    return this.mutateStateAndReturn(keys.NODE_IDS, alloc.increment);
  }

  // temporary raw allocator calls
  allocAudioBus(numChannels=1) {
    return this._allocBlock(keys.AUDIO_BUSSES, numChannels);
  }
  allocControlBus(numChannels=1) {
    return this._allocBlock(keys.CONTROL_BUSSES, numChannels);
  }
  /**
   * Allocate a buffer id.
   *
   * Note that numChannels is specified when creating the buffer.
   *
   * @param {int} numConsecutive - consecutively numbered buffers are needed by VOsc and VOsc3.
   * @returns {int}
   */
  allocBufferID(numConsecutive=1) {
    return this._allocBlock(keys.BUFFERS, numConsecutive);
  }

  // these require you to remember the channels and mess it up
  // if you free it wrong
  freeAudioBus(index, numChannels) {
    return this._freeBlock(keys.AUDIO_BUSSES, index, numChannels);
  }
  freeControlBus(index, numChannels) {
    return this._freeBlock(keys.CONTROL_BUSSES, index, numChannels);
  }
  freeBuffer(index, numChannels) {
    return this._freeBlock(keys.BUFFERS, index, numChannels);
  }

  /**
   * Fetch one part of the state,
   * mutate it with the callback,
   * save state and return the result.
   *
   * @returns {any} result
   */
  mutateStateAndReturn(key, fn) {
    var result, state;
    [result, state] = fn(this.state.get(key));
    this.state = this.state.set(key, state);
    return result;
  }
  mutateState(key, fn) {
    this.state = this.state.update(key, Immutable.Map(), fn);
  }

  _allocBlock(key, numChannels) {
    return this.mutateStateAndReturn(key,
      (state) => alloc.allocBlock(state, numChannels));
  }
  _freeBlock(key, index, numChannels) {
    return this.mutateState(key,
      (state) => alloc.freeBlock(state, index, numChannels));
  }
}

/**
 * Boot a server with options and connect
 *
 * @returns {Promise} - resolves with the Server
 */
export function boot(options) {
  return resolveOptions(undefined, options).then((opts) => {
    var s = new Server(opts);
    return s.boot().then(() => s.connect()).then(() => s);
  });
}
<|endoftext|>


<commit_before>// Copyright 2017 Google LLC
//
// 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.

'use strict';

async function writeLogEntry(logName) {
  // [START logging_write_log_entry]
  const {Logging} = require('@google-cloud/logging');
  const logging = new Logging();

  /**
   * TODO(developer): Uncomment the following line and replace with your values.
   */
  // const logName = 'my-log';
  const log = logging.log(logName);

  // A text log entry
  const text_entry = log.entry('Hello world!');

  // A json log entry with additional context
  const metadata = {
    severity: 'WARNING',
    labels: {
      foo: 'bar',
    },
    // A default log resource is added for some GCP environments
    // This log resource can be overwritten per spec:
    // https://cloud.google.com/logging/docs/reference/v2/rest/v2/MonitoredResource
    resource: {
      type: 'global',
    },
  };

  const message = {
    name: 'King Arthur',
    quest: 'Find the Holy Grail',
    favorite_color: 'Blue',
  };

  const json_Entry = log.entry(metadata, message);

  async function writeLogEntry() {
    // Synchronously write the log entry
    await log.write(text_entry);

    // Synchronously batch write the log entries
    await log.write([text_entry, json_Entry]);

    // Asynchronously let the logging library dispatch logs
    log.write(text_entry);

    console.log(`Wrote to ${logName}`);
  }
  writeLogEntry();
  // [END logging_write_log_entry]
}

async function listLogs() {
  // [START logging_list_logs]
  // Imports the Google Cloud client library
  const {Logging} = require('@google-cloud/logging');

  // Creates a client
  const logging = new Logging();

  async function printLogNames() {
    const [logs] = await logging.getLogs();
    console.log('Logs:');
    logs.forEach(log => {
      console.log(log.name);
    });
  }
  printLogNames();
  // [END logging_list_logs]
}

async function listLogEntries(logName) {
  // [START logging_list_log_entries]
  // Imports the Google Cloud client library
  const {Logging} = require('@google-cloud/logging');

  // Creates a client
  const logging = new Logging();

  /**
   * TODO(developer): Uncomment the following line to run the code.
   */
  // const logName = 'Name of the log from which to list entries, e.g. my-log';

  const log = logging.log(logName);

  async function printEntryMetadata() {
    // List the most recent entries for a given log
    // See https://googleapis.dev/nodejs/logging/latest/Logging.html#getEntries
    const [entries] = await log.getEntries();
    console.log('Logs:');
    entries.forEach(entry => {
      const metadata = entry.metadata;
      console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
    });
  }
  printEntryMetadata();
  // [END logging_list_log_entries]
}

async function listLogEntriesAdvanced(filter, pageSize, orderBy) {
  // [START logging_list_log_entries_advanced]
  // Imports the Google Cloud client library
  const {Logging} = require('@google-cloud/logging');

  // Creates a client
  const logging = new Logging();

  /**
   * TODO(developer): Uncomment the following lines to run the code.
   *
   * Filter results, e.g. "severity=ERROR"
   * See https://cloud.google.com/logging/docs/view/advanced_filters for more
   * filter information.
   */
  // const filter = 'severity=ERROR';
  // const pageSize = 5;
  // const orderBy = 'timestamp desc';

  const options = {
    filter: filter,
    pageSize: pageSize,
    orderBy: orderBy,
  };

  async function printEntryMetadata() {
    // See https://googleapis.dev/nodejs/logging/latest/Logging.html#getEntries
    const [entries] = await logging.getEntries(options);
    console.log('Logs:');
    entries.forEach(entry => {
      const metadata = entry.metadata;
      console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
    });
  }
  printEntryMetadata();
  // [END logging_list_log_entries_advanced]
}

async function tailLogEntries(logName) {
  // [START logging_tail_log_entries]
  const {Logging} = require('@google-cloud/logging');
  const logging = new Logging();

  /**
   * TODO(developer): Replace logName with the name of your log.
   */
  const log = logging.log(logName);
  console.log('running tail log entries test');

  const stream = log
    .tailEntries({
      filter: 'timestamp > "2021-01-01T23:00:00Z"',
    })
    .on('error', console.error)
    .on('data', resp => {
      console.log(resp.entries);
      console.log(resp.suppressionInfo);
      // If you anticipate many results, you can end a stream early to prevent
      // unnecessary processing and API requests.
      stream.end();
    })
    .on('end', () => {
      console.log('log entry stream has ended');
    });

  // Note: to get all project logs, invoke logging.tailEntries
  // [END logging_tail_log_entries]
}

async function deleteLog(logName) {
  // [START logging_delete_log]
  // Imports the Google Cloud client library
  const {Logging} = require('@google-cloud/logging');

  // Creates a client
  const logging = new Logging();

  /**
   * TODO(developer): Uncomment the following line to run the code.
   */
  // const logName = 'Name of the log to delete, e.g. my-log';

  const log = logging.log(logName);

  async function deleteLog() {
    // Deletes a logger and all its entries.
    // Note that a deletion can take several minutes to take effect.
    // See https://googleapis.dev/nodejs/logging/latest/Log.html#delete
    await log.delete();
    console.log(`Deleted log: ${logName}`);
  }
  deleteLog();
  // [END logging_delete_log]
}

async function main() {
  require('yargs')
    .demand(1)
    .command(
      'list',
      'Lists log entries, optionally filtering, limiting, and sorting results.',
      {
        filter: {
          alias: 'f',
          type: 'string',
          requiresArg: true,
          description: 'Only log entries matching the filter are written.',
        },
        limit: {
          alias: 'l',
          type: 'number',
          requiresArg: true,
          description: 'Maximum number of results to return.',
        },
        sort: {
          alias: 's',
          type: 'string',
          requiresArg: true,
          description: 'Sort results.',
        },
      },
      opts => {
        listLogEntriesAdvanced(opts.filter, opts.limit, opts.sort);
      }
    )
    .command('list-logs', 'Lists logs in your project.', {}, listLogs)
    .command('list-simple <logName>', 'Lists log entries.', {}, opts =>
      listLogEntries(opts.logName)
    )
    .command(
      'tail-logs <logName>',
      'Tails log entries for a specified log.',
      {},
      opts => tailLogEntries(opts.logName)
    )
    .command(
      'write-simple <logName>',
      'Writes a basic log entry to the specified log.',
      {},
      opts => {
        writeLogEntry(opts.logName);
      }
    )
    .command('delete <logName>', 'Deletes the specified Log.', {}, opts => {
      deleteLog(opts.logName);
    })
    .example('node $0 list', 'List all log entries.')
    .example(
      'node $0 list -f "severity=ERROR" -s "timestamp" -l 2',
      'List up to 2 error entries, sorted by timestamp ascending.'
    )
    .example(
      'node $0 list -f \'logName="my-log"\' -l 2',
      'List up to 2 log entries from the "my-log" log.'
    )
    .example(
      'node $0 write my-log \'{"type":"gae_app","labels":{"module_id":"default"}}\' \'"Hello World!"\'',
      'Write a string log entry.'
    )
    .example(
      'node $0 write my-log \'{"type":"global"}\' \'{"message":"Hello World!"}\'',
      'Write a JSON log entry.'
    )
    .example('node $0 delete my-log', 'Delete "my-log".')
    .wrap(120)
    .recommendCommands()
    .epilogue('For more information, see https://cloud.google.com/logging/docs')
    .help()
    .strict().argv;
}

main().catch(console.error);
<commit_msg>fix 186981671: [external][logging] The use of "synchronously" is a bit wrong on this page. (#1187)<commit_after>// Copyright 2017 Google LLC
//
// 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.

'use strict';

async function writeLogEntry(logName) {
  // [START logging_write_log_entry]
  const {Logging} = require('@google-cloud/logging');
  const logging = new Logging();

  /**
   * TODO(developer): Uncomment the following line and replace with your values.
   */
  // const logName = 'my-log';
  const log = logging.log(logName);

  // A text log entry
  const text_entry = log.entry('Hello world!');

  // A json log entry with additional context
  const metadata = {
    severity: 'WARNING',
    labels: {
      foo: 'bar',
    },
    // A default log resource is added for some GCP environments
    // This log resource can be overwritten per spec:
    // https://cloud.google.com/logging/docs/reference/v2/rest/v2/MonitoredResource
    resource: {
      type: 'global',
    },
  };

  const message = {
    name: 'King Arthur',
    quest: 'Find the Holy Grail',
    favorite_color: 'Blue',
  };

  const json_Entry = log.entry(metadata, message);

  async function writeLogEntry() {
    // Asynchronously write the log entry
    await log.write(text_entry);

    // Asynchronously batch write the log entries
    await log.write([text_entry, json_Entry]);

    // Asynchronously let the logging library dispatch logs
    log.write(text_entry);

    console.log(`Wrote to ${logName}`);
  }
  writeLogEntry();
  // [END logging_write_log_entry]
}

async function listLogs() {
  // [START logging_list_logs]
  // Imports the Google Cloud client library
  const {Logging} = require('@google-cloud/logging');

  // Creates a client
  const logging = new Logging();

  async function printLogNames() {
    const [logs] = await logging.getLogs();
    console.log('Logs:');
    logs.forEach(log => {
      console.log(log.name);
    });
  }
  printLogNames();
  // [END logging_list_logs]
}

async function listLogEntries(logName) {
  // [START logging_list_log_entries]
  // Imports the Google Cloud client library
  const {Logging} = require('@google-cloud/logging');

  // Creates a client
  const logging = new Logging();

  /**
   * TODO(developer): Uncomment the following line to run the code.
   */
  // const logName = 'Name of the log from which to list entries, e.g. my-log';

  const log = logging.log(logName);

  async function printEntryMetadata() {
    // List the most recent entries for a given log
    // See https://googleapis.dev/nodejs/logging/latest/Logging.html#getEntries
    const [entries] = await log.getEntries();
    console.log('Logs:');
    entries.forEach(entry => {
      const metadata = entry.metadata;
      console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
    });
  }
  printEntryMetadata();
  // [END logging_list_log_entries]
}

async function listLogEntriesAdvanced(filter, pageSize, orderBy) {
  // [START logging_list_log_entries_advanced]
  // Imports the Google Cloud client library
  const {Logging} = require('@google-cloud/logging');

  // Creates a client
  const logging = new Logging();

  /**
   * TODO(developer): Uncomment the following lines to run the code.
   *
   * Filter results, e.g. "severity=ERROR"
   * See https://cloud.google.com/logging/docs/view/advanced_filters for more
   * filter information.
   */
  // const filter = 'severity=ERROR';
  // const pageSize = 5;
  // const orderBy = 'timestamp desc';

  const options = {
    filter: filter,
    pageSize: pageSize,
    orderBy: orderBy,
  };

  async function printEntryMetadata() {
    // See https://googleapis.dev/nodejs/logging/latest/Logging.html#getEntries
    const [entries] = await logging.getEntries(options);
    console.log('Logs:');
    entries.forEach(entry => {
      const metadata = entry.metadata;
      console.log(`${metadata.timestamp}:`, metadata[metadata.payload]);
    });
  }
  printEntryMetadata();
  // [END logging_list_log_entries_advanced]
}

async function tailLogEntries(logName) {
  // [START logging_tail_log_entries]
  const {Logging} = require('@google-cloud/logging');
  const logging = new Logging();

  /**
   * TODO(developer): Replace logName with the name of your log.
   */
  const log = logging.log(logName);
  console.log('running tail log entries test');

  const stream = log
    .tailEntries({
      filter: 'timestamp > "2021-01-01T23:00:00Z"',
    })
    .on('error', console.error)
    .on('data', resp => {
      console.log(resp.entries);
      console.log(resp.suppressionInfo);
      // If you anticipate many results, you can end a stream early to prevent
      // unnecessary processing and API requests.
      stream.end();
    })
    .on('end', () => {
      console.log('log entry stream has ended');
    });

  // Note: to get all project logs, invoke logging.tailEntries
  // [END logging_tail_log_entries]
}

async function deleteLog(logName) {
  // [START logging_delete_log]
  // Imports the Google Cloud client library
  const {Logging} = require('@google-cloud/logging');

  // Creates a client
  const logging = new Logging();

  /**
   * TODO(developer): Uncomment the following line to run the code.
   */
  // const logName = 'Name of the log to delete, e.g. my-log';

  const log = logging.log(logName);

  async function deleteLog() {
    // Deletes a logger and all its entries.
    // Note that a deletion can take several minutes to take effect.
    // See https://googleapis.dev/nodejs/logging/latest/Log.html#delete
    await log.delete();
    console.log(`Deleted log: ${logName}`);
  }
  deleteLog();
  // [END logging_delete_log]
}

async function main() {
  require('yargs')
    .demand(1)
    .command(
      'list',
      'Lists log entries, optionally filtering, limiting, and sorting results.',
      {
        filter: {
          alias: 'f',
          type: 'string',
          requiresArg: true,
          description: 'Only log entries matching the filter are written.',
        },
        limit: {
          alias: 'l',
          type: 'number',
          requiresArg: true,
          description: 'Maximum number of results to return.',
        },
        sort: {
          alias: 's',
          type: 'string',
          requiresArg: true,
          description: 'Sort results.',
        },
      },
      opts => {
        listLogEntriesAdvanced(opts.filter, opts.limit, opts.sort);
      }
    )
    .command('list-logs', 'Lists logs in your project.', {}, listLogs)
    .command('list-simple <logName>', 'Lists log entries.', {}, opts =>
      listLogEntries(opts.logName)
    )
    .command(
      'tail-logs <logName>',
      'Tails log entries for a specified log.',
      {},
      opts => tailLogEntries(opts.logName)
    )
    .command(
      'write-simple <logName>',
      'Writes a basic log entry to the specified log.',
      {},
      opts => {
        writeLogEntry(opts.logName);
      }
    )
    .command('delete <logName>', 'Deletes the specified Log.', {}, opts => {
      deleteLog(opts.logName);
    })
    .example('node $0 list', 'List all log entries.')
    .example(
      'node $0 list -f "severity=ERROR" -s "timestamp" -l 2',
      'List up to 2 error entries, sorted by timestamp ascending.'
    )
    .example(
      'node $0 list -f \'logName="my-log"\' -l 2',
      'List up to 2 log entries from the "my-log" log.'
    )
    .example(
      'node $0 write my-log \'{"type":"gae_app","labels":{"module_id":"default"}}\' \'"Hello World!"\'',
      'Write a string log entry.'
    )
    .example(
      'node $0 write my-log \'{"type":"global"}\' \'{"message":"Hello World!"}\'',
      'Write a JSON log entry.'
    )
    .example('node $0 delete my-log', 'Delete "my-log".')
    .wrap(120)
    .recommendCommands()
    .epilogue('For more information, see https://cloud.google.com/logging/docs')
    .help()
    .strict().argv;
}

main().catch(console.error);
<|endoftext|>


<commit_before>/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global window, $ */

(function () {
    "use strict";

    var Handlebars = window.Handlebars;

    Handlebars.registerHelper("getStatus", function (address, currentAddress) {
        if (address === currentAddress) {
            return "active";
        } else {
            return "";
        }
    });

    var formatTimeInterval = function (prop, propName) {
        var out = "";
        if (prop) {
            out += prop + " " + propName;

            if (prop !== 1) {
                out += "s";
            }
            out += " ";
        }

        return out;
    };

    var formatTime = function (ms) {

        //var milliseconds = parseInt((duration%1000)/100)
        var seconds = parseInt((ms / 1000) % 60, 10);
        var minutes = parseInt((ms / (1000 * 60)) % 60, 10);
        var hours = parseInt((ms / (1000 * 60 * 60)) % 24, 10);

        var out = "";
        out += formatTimeInterval(hours, "hour");
        out += formatTimeInterval(minutes, "minute");
        out += formatTimeInterval(seconds, "second");

        return out;
    };

    var main = function () {

        $.ajax({
            url: "/api/getinfo",
            cache: false,
            dataType : "json"
        }).done(function (data) {
            var currentItem = data.currentItem;

            $("#currentAddressSSID").text(currentItem.ssid);
            $("#currentAddressDescription").text(currentItem.description);
            $("#currentAddressMac").text(currentItem.address);

            var temp = "Not Available";
            if (data.systemInfo.cpuTemp) {
                temp = data.systemInfo.cpuTemp + " degrees " +  data.systemInfo.tempScale;
            }
            $("#currentCPUTemp").text(temp);

            $("#updateInterval").text("Every " + formatTime(data.config.refreshInterval));

            if (currentItem.timeSinceUpdate) {
                var _t = (data.config.refreshInterval - currentItem.timeSinceUpdate);

                $("#timeToNextAP").text(formatTime(_t));
            }

            var source = $("#ap-list-template").html();
            var apListTemplate = Handlebars.compile(source);
            var html = apListTemplate({"addresses": data.addresses, "currentAddress": currentItem.address});

            $("#ap-list-body").append(html);
        });
    };

    window.onload = main;
}());<commit_msg>page now auto refreshes when there is an update. We need to test this on production, and maybe put some small buffer time in<commit_after>/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global window, $, setInterval, clearInterval */

(function () {
    "use strict";

    var Handlebars = window.Handlebars;

    Handlebars.registerHelper("getStatus", function (address, currentAddress) {
        if (address === currentAddress) {
            return "active";
        } else {
            return "";
        }
    });

    var formatTimeInterval = function (prop, propName) {
        var out = "";
        if (prop) {
            out += prop + " " + propName;

            if (prop !== 1) {
                out += "s";
            }
            out += " ";
        }

        return out;
    };

    var formatTime = function (ms) {

        //var milliseconds = parseInt((duration%1000)/100)
        var seconds = parseInt((ms / 1000) % 60, 10);
        var minutes = parseInt((ms / (1000 * 60)) % 60, 10);
        var hours = parseInt((ms / (1000 * 60 * 60)) % 24, 10);

        var out = "";
        out += formatTimeInterval(hours, "hour");
        out += formatTimeInterval(minutes, "minute");
        out += formatTimeInterval(seconds, "second");

        return out;
    };

    var loadMainInfo = function () {
        $.ajax({
            url: "/api/getinfo",
            cache: false,
            dataType : "json"
        }).done(function (data) {
            var currentItem = data.currentItem;

            $("#currentAddressSSID").text(currentItem.ssid);
            $("#currentAddressDescription").text(currentItem.description);
            $("#currentAddressMac").text(currentItem.address);

            var temp = "Not Available";
            if (data.systemInfo.cpuTemp) {
                temp = data.systemInfo.cpuTemp + " degrees " +  data.systemInfo.tempScale;
            }
            $("#currentCPUTemp").text(temp);

            $("#updateInterval").text("Every " + formatTime(data.config.refreshInterval));

            if (currentItem.timeSinceUpdate) {
                var _t = (data.config.refreshInterval - currentItem.timeSinceUpdate);

                var intervalCount = 0;
                var intervalId = setInterval(
                    function () {
                        intervalCount++;

                        var tLeft = _t - intervalCount * 1000;

                        if (tLeft <= 0) {
                            clearInterval(intervalId);
                            loadMainInfo();
                            return;
                        }

                        $("#timeToNextAP").text(formatTime(tLeft));
                    },
                    1000
                );

                $("#timeToNextAP").text(formatTime(_t));
            }

            var source = $("#ap-list-template").html();
            var apListTemplate = Handlebars.compile(source);
            var html = apListTemplate({"addresses": data.addresses, "currentAddress": currentItem.address});

            $("#ap-list-body").empty();
            $("#ap-list-body").append(html);
        });
    };

    var main = function () {
        loadMainInfo();
    };

    window.onload = main;
}());<|endoftext|>


<commit_before>var request = require('got');

var url = "http://localhost:7071/api/HttpTrigger"; // dev
// var url = "https://webpush-azurefunction.azurewebsites.net/api/HttpTrigger"; // deployed

module.exports = {
  /*
    createVapidKey
      res:
        - status: number
        - keys:
          - publicKey: string
          - privateKey: string
    */
  createVapidKey: function (req, res) {

    request.get(url + "?action=vapidkeys", {
      responseType: 'json'
    }).then(response => response.body)
      .then((response) => {
        console.log("vapid key called");
        res.send(
          {
            ...response.res,
            status: 200,
          })

      }).catch((err) => {
        res.status(400);
      });
  },
  /*
  registerVapidKey
    req
      - userEmail: string
      - publicKey: string
      - privateKey: string
    res
      - status: number
  */
  registerVapidKey: function (req, res) {
    if (req.body && !req.body.publicKey && !req.body.privateKey && !req.body.userEmail) {
      return res.send({
        status: 400,
        message: "missing publicKey, privateKey, or userEmail",
      });
    }

    request.post(url + "?action=register", {
      json: {
        subject: "mailto:" + req.body.userEmail,
        publicKey: req.body.publicKey,
        privateKey: req.body.privateKey,
      },
      responseType: 'json'
    }).then(response => response.body)
      .then(response => {
        if (response.res.status.toLowerCase() !== "ok") {
          res.status(400);
        } else {
          res.status(200);
        }
      })
      .catch(e => {
        if (e.response && e.response.body) {
          // service error
          return res.send({
            status: 400,
            message: "error from registration"
          });

        } else if (e.message) {
          // network error
          return res.status(500);
        }
      });
  },
  /*
    unregisterVapidKey
      req
        - publicKey: string
        - privateKey: string
      res
        - status: number
  */
  unregisterVapidKey: function (req, res) {
    if (req.body && !req.body.publicKey && !req.body.privateKey) {
      return res.send({
        status: 400,
        message: "missing publicKey, or privateKey",
      })
    }

    request.post(url + "?action=unregister", {
      json: {
        publicKey: req.body.publicKey,
        privateKey: req.body.privateKey,
      },
      responseType: 'json'
    }).then(response => response.body)
      .then(response => {
        if (response.res.status.toLowerCase() !== "ok") {
          res.status(400);
        } else {
          res.status(200);
        }
      })
      .catch(e => {
        res.send({
          status: 400,
          message: "failed to unregister key"
        });
      });
  },
  /*
    subscribeUser
      req
        - publicKey: string
        - subscription: url
      res
        - status: number
  */
  subscribeUser: function (req, res) {
    if (req.body && !req.body.publicKey && !req.body.subscription) {
      return res.send({
        status: 400,
        message: "missing publicKey, or subscription url",
      })
    }

    request.post(url + "?action=subscribe", {
      json: {
        publicKey: req.body.publicKey,
        subscription: req.body.subscription,
      },
      responseType: 'json'
    }).then(response => response.body)
      .then(response => {
        if (response.res.status.toLowerCase() !== "ok") {
          res.status(400);
        } else {
          res.status(200);
        }
      })
      .catch(e => {
        res.send({
          status: 400,
          message: "failed to unregister key"
        });
      });
  },
  /*
    unsubscribeUser
      req
        - publicKey: string
        - subscription: url
      res
        - status: number
  */
  unsubscribeUser: function (req, res) {
    if (req.body && !req.body.publicKey && !req.body.subscription) {
      return res.send({
        status: 400,
        message: "missing publicKey, or subscription url",
      })
    }

    request.post(url + "?action=unsubscribe", {
      json: {
        publicKey: req.body.publicKey,
        subscription: req.body.subscription,
      },
      responseType: 'json'
    }).then(response => response.body)
      .then(response => {
        if (response.res.status.toLowerCase() !== "ok") {
          res.status(400);
        } else {
          res.status(200);
        }
      }).catch(e => {
        res.send({
          status: 400,
          message: "failed to unregister key"
        });
      });
  },
  /*
      sendPushNotification
      req
        - publicKey: string
        - privateKey: string
        - subject: url/email
        - notification: string
      res
        - status code
  */
  sendPushNotification: function (req, res) {
    if (req.body && !req.body.publicKey && !req.body.subject && !req.body.privateKey && !req.body.notification) {
      return res.send({
        status: 400,
        message: "missing publicKey, privateKey, notification, or subscription url",
      })
    }

    request.post(url + "?action=register", {
      json: {
        publicKey: req.body.publicKey,
        privateKey: req.body.privateKey,
        subscription: req.body.subscription,
        notification: req.body.notification,
      },
      responseType: 'json'
    }).then(response => response.body)
      .then(response => {
        if (response.res.status.toLowerCase() !== "ok") {
          res.status(400);
        } else {
          res.status(200);
        }
      }).catch(e => {
        res.send({
          status: 400,
          message: "failed to unregister key"
        });
      });
  }
}
<commit_msg>push api finish<commit_after>var request = require('got');

var url = "http://localhost:7071/api/HttpTrigger"; // dev
// var url = "https://webpush-azurefunction.azurewebsites.net/api/HttpTrigger"; // deployed

module.exports = {
  /*
    createVapidKey
      res:
        - status: number
        - keys:
          - publicKey: string
          - privateKey: string
    */
  createVapidKey: function (req, res) {
    request.get(url + "?action=vapidkeys", {
      responseType: 'json'
    }).then(response => response.body)
      .then((response) => {
        res.send(
          {
            ...response.res,
          });
      }).catch((err) => {
        res.status(400).send({ status: 400 });
      });
  },
  /*
  registerVapidKey
    req
      - userEmail: string
      - publicKey: string
      - privateKey: string
    res
      - status: number
  */
  registerVapidKey: function (req, res) {
    if (req.body && !req.body.publicKey && !req.body.privateKey && !req.body.userEmail) {
      return res.status(400).send({
        message: "missing publicKey, privateKey, or userEmail",
      });
    }

    request.post(url + "?action=register", {
      json: {
        subject: "mailto:" + req.body.userEmail,
        publicKey: req.body.publicKey,
        privateKey: req.body.privateKey,
      },
      responseType: 'json'
    }).then(response => response.body)
      .then(response => {
        if (response.res.status.toLowerCase() !== "ok") {
          res.status(400).send({ status: 400 });
        } else {
          res.status(200).send({ status: 200 });
        }
      })
      .catch(e => {
        if (e.response && e.response.body) {
          // service error
          return res.status(400).send({
            message: "error from registration"
          });

        } else if (e.message) {
          // network error
          return res.status(500);
        }
      });
  },
  /*
    unregisterVapidKey
      req
        - publicKey: string
        - privateKey: string
      res
        - status: number
  */
  unregisterVapidKey: function (req, res) {
    if (req.body && !req.body.publicKey && !req.body.privateKey) {
      return res.status(400).send({
        message: "missing publicKey, or privateKey",
      })
    }

    request.post(url + "?action=unregister", {
      json: {
        publicKey: req.body.publicKey,
        privateKey: req.body.privateKey,
      },
      responseType: 'json'
    }).then(response => response.body)
      .then(response => {
        if (response.res.status.toLowerCase() !== "ok") {
          res.status(400).send({ status: 400 });
        } else {
          res.status(200).send({ status: 200 });
        }
      })
      .catch(e => {
        res.status(400).send({
          message: "failed to unregister key"
        });
      });
  },
  /*
    subscribeUser
      req
        - publicKey: string
        - subscription: url
      res
        - status: number
  */
  subscribeUser: function (req, res) {
    if (req.body && !req.body.publicKey && !req.body.subscription) {
      return res.status(400).send({
        message: "missing publicKey, or subscription url",
      })
    }

    request.post(url + "?action=subscribe", {
      json: {
        publicKey: req.body.publicKey,
        subscription: req.body.subscription,
      },
      responseType: 'json'
    }).then(response => response.body)
      .then(response => {
        if (response.res.status.toLowerCase() !== "ok") {
          res.status(400).send({ status: 400 });
        } else {
          res.status(200).send({ status: 200 });
        }
      })
      .catch(e => {
        res.status(400).send({
          message: "failed to unregister key"
        });
      });
  },
  /*
    unsubscribeUser
      req
        - publicKey: string
        - subscription: url
      res
        - status: number
  */
  unsubscribeUser: function (req, res) {
    if (req.body && !req.body.publicKey && !req.body.subscription) {
      return res.send({
        status: 400,
        message: "missing publicKey, or subscription url",
      })
    }

    request.post(url + "?action=unsubscribe", {
      json: {
        publicKey: req.body.publicKey,
        subscription: req.body.subscription,
      },
      responseType: 'json'
    }).then(response => response.body)
      .then(response => {
        if (response.res.status.toLowerCase() !== "ok") {
          res.status(400).send({ status: 400 });
        } else {
          res.status(200).send({ status: 200 });
        }
      }).catch(e => {
        res.status(400).send({
          message: "failed to unregister key"
        });
      });
  },
  /*
      sendPushNotification
      req
        - publicKey: string
        - privateKey: string
        - subject: url/email
        - notification: string
      res
        - status code
  */
  sendPushNotification: function (req, res) {
    if (req.body && !req.body.publicKey && !req.body.subject && !req.body.privateKey && !req.body.notification) {
      return res.status(400).send({
        message: "missing publicKey, privateKey, notification, or subscription url",
      })
    }

    request.post(url + "?action=sendnotification", {
      json: {
        publicKey: req.body.publicKey,
        privateKey: req.body.privateKey,
        subject: req.body.subject,
        notification: req.body.notification,
      },
      responseType: 'json'
    }).then(response => response.body)
      .then(response => {
        if (response.res.status.toLowerCase() !== "ok") {
          res.status(400).send({ status: 400 });
        } else {
          res.status(200).send({ status: 200 });
        }
      }).catch(e => {
        res.status(400).send({
          message: "failed to unregister key"
        });
      });
  }
}
<|endoftext|>


<commit_before>
/*
 Maps namespace

 gnt.maps
*/
gnt.maps = {};

gnt.maps.map = undefined;
gnt.maps.layer = undefined;
gnt.maps.layers = [];
gnt.maps.mapOptions = {};

/*
This function creates the map and layers.

Additional parameters and layers can be given to the
function.

map_div -- id of the element to create the map into
initial_extent -- initial extent where the map should open
callback_function -- callback function the to be called after creation
    The callback_function will get the map as a parameter
*/
gnt.maps.create_map = function (map_div, callback_function) {
    var map_options_created = false;
    {% for p in layer_data %}
        {% if p.protocol = 'ARCcache' %}
            var layer_info = {{ p.layer_info|safe }};
            layer = new OpenLayers.Layer.ArcGISCache(
                "{{ p.name }}",
                "{{ p.source }}",
                { layerInfo: layer_info}
            );
            gnt.maps.layers.push(layer);
            gnt.maps.mapOptions = {
                maxExtent: layer.maxExtent,
                units: layer.units,
                resolutions: layer.resolutions,
                numZoomLevels: layer.lods.length,
                tileSize: layer.tileSize,
                projection: layer.projection,
                restrictedExtent: layer.maxExtent
            };
            map_options_created = true;
        {% else %}
        {% if p.protocol = 'WMTS' %}
            var matrixIds = new Array(16);
            for (var i=0; i<16; ++i) {
                matrixIds[i] = "EPSG:{{ map_data.projection }}:" + i;
            }
            layer = new OpenLayers.Layer.WMTS({
                name: "{{ p.name }}",
                url: "{{ p.source }}",
                layer: "{{ p.layers }}",
                matrixSet: "EPSG:{{ map_data.projection }}",
                matrixIds: matrixIds,
                format: "image/png",
                style: "_null",
                opacity: 0.7,
                /*{% if p.layer_type = 'BL'%}
                    isBaseLayer: true,
                    {% else %}*/
                 //   isBaseLayer: false,
                //{% endif %}*/
               //wrapDateLine: false,
                //visibility: true
            });
            gnt.maps.layers.push(layer);
        {% else %}
        {% if p.protocol = 'ARCGIS' %}
            layer = new OpenLayers.Layer.ArcGIS93Rest(
                "{{ p.name }}",
                "{{ p.source }}",
                {layers: "show:{{ p.layers }}",
                format: "png24",
                transparent: true},
                {% if p.layer_type = 'BL'%}
                    {isBaseLayer: true}
                    {% else %}
                    {isBaseLayer: false}
                {% endif %}
                );
            gnt.maps.layers.push(layer);
        {% else %}
        {% if p.protocol = 'OSM' %}
            layer = new OpenLayers.Layer.OSM();
            gnt.maps.layers.push(layer);
        {% else %}
        {% if p.protocol = 'WMS' %}
            layer = new OpenLayers.Layer.WMS(
                "{{ p.name }}",
                "{{ p.source }}",
                {layers: "{{ p.layers }}"},
                {% if p.layer_type = 'BL'%}
                {isBaseLayer: true}
                {% else %}
                {isBaseLayer: false}
                {% endif %}
                );
            gnt.maps.layers.push(layer);
        {% else %}
        {% if p.protocol = 'WFS' %}
            layer = new OpenLayers.Layer.Vector(
                "{{ p.name }}",
                {strategies: [new OpenLayers.Strategy.BBOX()],
                protocol: new OpenLayers.Protocol.WFS({
                    url:  "{{ p.source }}",
                    version: "1.1.0",
                    featureType: "{{ p.layer }}",
                    featureNS: "http://localhost:8080/geoserver/BaseTest",
                    geometryName: "the_geom"
                    }),
                    visibility: false,
                    onFeatureInsert: function(event) {
                        count_order(event);
                    },
                    {% if p.layer_type = 'BL'%}
                    isBaseLayer: true
                    {% else %}
                    isBaseLayer: false
                    {% endif %}
                });
            gnt.maps.layers.push(layer);
        {% endif %}
        {% endif %}
        {% endif %}
        {% endif %}
        {% endif %}
        {% endif %}
        if(map_options_created === false) {
            gnt.maps.mapOptions = {
                projection: "EPSG:{{ map_data.projection }}",
                maxExtent: new OpenLayers.Bounds({{ map_data.max_extent }}),
                units: "m",
                maxResolution: {{ map_data.max_resolution }},
                zoom: {{ map_data.zoom_level }},
                tileSize: new OpenLayers.Size({{ map_data.tile_size }})
            };
        }
    {% endfor %}

    //make sure mapOptions controls are set correct
    //mapOptions.controls = [new OpenLayers.Control.ZoomPanel()];
    gnt.maps.mapOptions.theme = null;

    map = new OpenLayers.Map(map_div, gnt.maps.mapOptions);
     map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.addLayers(gnt.maps.layers);

    if(callback_function !== undefined) {
        callback_function(map);
    }
};
<commit_msg>fixed issue with IE and map variable that was not declared, this variable should also be under gnt.maps namespace but there are dependencies at the moment<commit_after>
/*
 Maps namespace

 gnt.maps
*/
gnt.maps = {};

var map = undefined;
gnt.maps.layer = undefined;
gnt.maps.layers = [];

/*
This function creates the map and layers.

Additional parameters and layers can be given to the
function.

map_div -- id of the element to create the map into
initial_extent -- initial extent where the map should open
callback_function -- callback function the to be called after creation
    The callback_function will get the map as a parameter
*/
gnt.maps.create_map = function (map_div, callback_function) {
    var mapOptions;
    var map_options_created = false;
    {% for p in layer_data %}
        {% if p.protocol = 'ARCcache' %}
            var layer_info = {{ p.layer_info|safe }};
            layer = new OpenLayers.Layer.ArcGISCache(
                "{{ p.name }}",
                "{{ p.source }}",
                { layerInfo: layer_info}
            );
            gnt.maps.layers.push(layer);
            mapOptions = {
                maxExtent: layer.maxExtent,
                units: layer.units,
                resolutions: layer.resolutions,
                numZoomLevels: layer.lods.length,
                tileSize: layer.tileSize,
                projection: layer.projection,
                restrictedExtent: layer.maxExtent
            };
            map_options_created = true;
        {% else %}
        {% if p.protocol = 'WMTS' %}
            var matrixIds = new Array(16);
            for (var i=0; i<16; ++i) {
                matrixIds[i] = "EPSG:{{ map_data.projection }}:" + i;
            }
            layer = new OpenLayers.Layer.WMTS({
                name: "{{ p.name }}",
                url: "{{ p.source }}",
                layer: "{{ p.layers }}",
                matrixSet: "EPSG:{{ map_data.projection }}",
                matrixIds: matrixIds,
                format: "image/png",
                style: "_null",
                opacity: 0.7,
                /*{% if p.layer_type = 'BL'%}
                    isBaseLayer: true,
                    {% else %}*/
                 //   isBaseLayer: false,
                //{% endif %}*/
               //wrapDateLine: false,
                //visibility: true
            });
            gnt.maps.layers.push(layer);
        {% else %}
        {% if p.protocol = 'ARCGIS' %}
            layer = new OpenLayers.Layer.ArcGIS93Rest(
                "{{ p.name }}",
                "{{ p.source }}",
                {layers: "show:{{ p.layers }}",
                format: "png24",
                transparent: true},
                {% if p.layer_type = 'BL'%}
                    {isBaseLayer: true}
                    {% else %}
                    {isBaseLayer: false}
                {% endif %}
                );
            gnt.maps.layers.push(layer);
        {% else %}
        {% if p.protocol = 'OSM' %}
            layer = new OpenLayers.Layer.OSM();
            gnt.maps.layers.push(layer);
        {% else %}
        {% if p.protocol = 'WMS' %}
            layer = new OpenLayers.Layer.WMS(
                "{{ p.name }}",
                "{{ p.source }}",
                {layers: "{{ p.layers }}"},
                {% if p.layer_type = 'BL'%}
                {isBaseLayer: true}
                {% else %}
                {isBaseLayer: false}
                {% endif %}
                );
            gnt.maps.layers.push(layer);
        {% else %}
        {% if p.protocol = 'WFS' %}
            layer = new OpenLayers.Layer.Vector(
                "{{ p.name }}",
                {strategies: [new OpenLayers.Strategy.BBOX()],
                protocol: new OpenLayers.Protocol.WFS({
                    url:  "{{ p.source }}",
                    version: "1.1.0",
                    featureType: "{{ p.layer }}",
                    featureNS: "http://localhost:8080/geoserver/BaseTest",
                    geometryName: "the_geom"
                    }),
                    visibility: false,
                    onFeatureInsert: function(event) {
                        count_order(event);
                    },
                    {% if p.layer_type = 'BL'%}
                    isBaseLayer: true
                    {% else %}
                    isBaseLayer: false
                    {% endif %}
                });
            gnt.maps.layers.push(layer);
        {% endif %}
        {% endif %}
        {% endif %}
        {% endif %}
        {% endif %}
        {% endif %}
        if(map_options_created === false) {
            mapOptions = {
                projection: "EPSG:{{ map_data.projection }}",
                maxExtent: new OpenLayers.Bounds({{ map_data.max_extent }}),
                units: "m",
                maxResolution: {{ map_data.max_resolution }},
                zoom: {{ map_data.zoom_level }},
                tileSize: new OpenLayers.Size({{ map_data.tile_size }})
            };
        }
    {% endfor %}

    //make sure mapOptions controls are set correct
    //mapOptions.controls = [new OpenLayers.Control.ZoomPanel()];
    mapOptions['theme'] = null;

    map = new OpenLayers.Map(map_div, mapOptions);
    map.addControl(new OpenLayers.Control.LayerSwitcher());
    map.addLayers(gnt.maps.layers);

    if(callback_function !== undefined) {
        callback_function(map);
    }
};
<|endoftext|>