<commit_before>(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["makeElement"] = factory();
	else
		root["makeElement"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__webpack_require__.i = function(value) { return value; };
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
// utility functions
function noop() { }
function consume(val) { }
function identity(val) {
    // nothing special here
    return val;
}
function makeElement(def = {}) {
    const props = def.props || {};
    const methods = def.methods || {};
    // whether the connectedCallback has been run
    let hasConnected = false;
    let readyFn = noop;
    if (typeof def.ready === 'function') {
        readyFn = def.ready;
    }
    // used to keep track of registered properties/attributes
    const registeredProps = {};
    const registeredAttrs = {};
    // we need to access the property name through Object.keys
    for (const propName of Object.keys(props)) {
        // populated registeredProps/Attrs objects
        const propDef = props[propName];
        let val = null;
        if (propDef.init !== undefined) {
            // initial value for the property
            val = propDef.init;
        }
        let hasAttr = typeof propDef.attr === 'string';
        let attrName = null;
        if (hasAttr) {
            attrName = propDef.attr;
            // register attribute internally
            registeredAttrs[attrName] = {
                // internal value
                val: null,
                // linked property name
                propName,
                // whether the attribute needs to be propagated to the
                // property
                needsPropagation: true,
            };
        }
        let toAttr = identity;
        if (typeof propDef.toAttr === 'function') {
            // this === element instance
            toAttr = propDef.toAttr;
        }
        let fromAttr = identity;
        if (typeof propDef.fromAttr === 'function') {
            fromAttr = propDef.fromAttr;
        }
        let get = identity;
        if (typeof propDef.get === 'function') {
            get = propDef.get;
        }
        let set = consume;
        if (typeof propDef.set === 'function') {
            set = propDef.set;
        }
        let coerce = identity;
        if (typeof propDef.coerce === 'function') {
            coerce = propDef.coerce;
        }
        registeredProps[propName] = {
            // internal value
            val,
            // linked attribute name
            attr: attrName,
            // function used to produce an attribute value from a
            // property value
            toAttr,
            // function used to produce a property value from an
            // attribute value
            fromAttr,
            // getter function
            get,
            // setter function
            set,
            // function to modify the value passed to the setter function
            coerce,
            // if the property has been set before
            hasSet: false,
        };
    }
    const observedAttrs = Object.keys(registeredAttrs);
    const DefinableCustomElement = class extends HTMLElement {
        constructor() {
            super();
            readyFn = readyFn.bind(this);
            for (const propName of Object.keys(registeredProps)) {
                // convenience aliases
                const internalProp = registeredProps[propName];
                const hasLinkedAttr = typeof internalProp.attr === 'string';
                const attrName = internalProp.attr;
                const internalAttr = registeredAttrs[attrName];
                // bind property methods to element context
                internalProp.toAttr = internalProp.toAttr.bind(this);
                internalProp.fromAttr = internalProp.fromAttr.bind(this);
                internalProp.get = internalProp.get.bind(this);
                internalProp.set = internalProp.set.bind(this);
                internalProp.coerce = internalProp.coerce.bind(this);
                Object.defineProperty(this, propName, {
                    set(val) {
                        let propVal = val;
                        propVal = internalProp.coerce(propVal);
                        if (internalProp.settingInitialValue) {
                            internalProp.settingInitialValue = false;
                        }
                        internalProp.val = propVal;
                        internalProp.set(propVal);
                        /*
                        We only propagate from the property to the attribute if:
                            - A linked attribute was defined
                            - The property setter is not being triggered by attributeChangedCallback
                        */
                        const beingInitialized = (this.hasAttribute(attrName)
                            && !internalProp.hasSet);
                        if (hasLinkedAttr && !beingInitialized) {
                            const attrVal = internalProp.toAttr(propVal);
                            // prevent the attribute from reflowing back to the
                            // property in attributeChangedCallback
                            internalAttr.needsPropagation = false;
                            // invoke attributeChangedCallback
                            this.setAttribute(attrName, attrVal);
                        }
                        internalProp.hasSet = true;
                    },
                    get() {
                        const propVal = internalProp.get(internalProp.val);
                        return propVal;
                    },
                });
            }
            // insert element template
            const hasLocalTemplate = typeof def.template === 'string';
            const hasRemoteTemplate = typeof def.templateUrl === 'string';
            if (def.shadowDom) {
                this.attachShadow({ mode: 'open' });
            }
            if (hasLocalTemplate) {
                if (def.shadowDom) {
                    this.shadowRoot.innerHTML = def.template;
                }
                else {
                    this.innerHTML = def.template;
                }
            }
            else if (hasRemoteTemplate) {
                fetch(def.templateUrl).then((resp) => {
                    if (resp.ok) {
                        // 200 OK
                        return resp.text();
                    }
                    else {
                        // 404 et al
                        throw new Error(`Couldn't fetch template at ${def.templateUrl}. ` +
                            `Got HTTP status code ${status}`);
                    }
                }).then((template) => {
                    if (def.shadowDom) {
                        this.shadowRoot.innerHTML = template;
                    }
                    else {
                        this.innerHTML = template;
                    }
                });
            }
            // id caching enabled by default
            if (def.cacheIds !== false) {
                this.$ = {};
                let elsWithIds;
                if (def.shadowDom) {
                    elsWithIds = this.shadowRoot.querySelectorAll('[id]');
                }
                else {
                    elsWithIds = this.querySelectorAll('[id]');
                }
                for (const el of elsWithIds) {
                    const castEl = el;
                    this.$[castEl.id] = castEl;
                }
            }
        }
        connectedCallback() {
            if (hasConnected) {
                return;
            }
            // only run once
            for (const propName of Object.keys(props)) {
                const internalProp = registeredProps[propName];
                // if there is a value but the setter has not run
                if (internalProp.val !== undefined
                    && internalProp.val !== null
                    && !internalProp.hasSet) {
                    internalProp.settingInitialValue = true;
                    // kick off property setter
                    this[propName] = internalProp.val;
                }
            }
            // invoke ready function with element context
            readyFn.call(this);
            hasConnected = true;
        }
        attributeChangedCallback(attrName, oldVal, val) {
            // only do work if the new value differs
            if (val !== oldVal) {
                // convenience aliases
                const internalAttr = registeredAttrs[attrName];
                internalAttr.val = val;
                if (internalAttr.needsPropagation) {
                    // propagation should only occur once
                    internalAttr.needsPropagation = false;
                    const propName = internalAttr.propName;
                    const internalProp = registeredProps[propName];
                    const propVal = internalProp.fromAttr(val);
                    this[propName] = propVal;
                }
            }
        }
        static get observedAttributes() {
            // required for attributeChangedCallback to be called
            return observedAttrs;
        }
    };
    for (const fnName of Object.keys(methods)) {
        const fn = methods[fnName];
        if (typeof fn !== 'function') {
            throw new TypeError(`${fnName} must be a function (got ${fn})`);
        }
        DefinableCustomElement.prototype[fnName] = fn;
    }
    return DefinableCustomElement;
}
/* harmony default export */ __webpack_exports__["default"] = (makeElement);

/***/ })
/******/ ]);
});<commit_msg>Release build<commit_after>(function webpackUniversalModuleDefinition(root, factory) {
	if(typeof exports === 'object' && typeof module === 'object')
		module.exports = factory();
	else if(typeof define === 'function' && define.amd)
		define([], factory);
	else if(typeof exports === 'object')
		exports["makeElement"] = factory();
	else
		root["makeElement"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// identity function for calling harmony imports with the correct context
/******/ 	__webpack_require__.i = function(value) { return value; };
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, {
/******/ 				configurable: false,
/******/ 				enumerable: true,
/******/ 				get: getter
/******/ 			});
/******/ 		}
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
// utility functions
function noop() { }
function consume(val) { }
function identity(val) {
    // nothing special here
    return val;
}
function convertToBoolAttr(val) {
    if (Boolean(val)) {
        return '';
    }
    else {
        return undefined;
    }
}
function makeElement(def = {}) {
    const props = def.props || {};
    const methods = def.methods || {};
    // whether the connectedCallback has been run
    let hasConnected = false;
    let readyFn = noop;
    if (typeof def.ready === 'function') {
        readyFn = def.ready;
    }
    // used to keep track of registered properties/attributes
    const registeredProps = {};
    const registeredAttrs = {};
    // we need to access the property name through Object.keys
    for (const propName of Object.keys(props)) {
        // populated registeredProps/Attrs objects
        const propDef = props[propName];
        let val = null;
        if (propDef.init !== undefined) {
            // initial value for the property
            val = propDef.init;
        }
        let hasAttr = typeof propDef.attr === 'string';
        let attrName = null;
        if (hasAttr) {
            attrName = propDef.attr;
            // register attribute internally
            registeredAttrs[attrName] = {
                // internal value
                val: null,
                // linked property name
                propName,
                // whether the attribute needs to be propagated to the
                // property
                needsPropagation: true,
            };
        }
        let boolAttr = false;
        if (typeof propDef.boolAttr === 'boolean') {
            boolAttr = propDef.boolAttr;
        }
        let toAttr = identity;
        if (boolAttr) {
            toAttr = convertToBoolAttr;
        }
        else if (typeof propDef.toAttr === 'function') {
            toAttr = propDef.toAttr;
        }
        let fromAttr = identity;
        if (typeof propDef.fromAttr === 'function') {
            fromAttr = propDef.fromAttr;
        }
        let get = identity;
        if (typeof propDef.get === 'function') {
            get = propDef.get;
        }
        let set = consume;
        if (typeof propDef.set === 'function') {
            set = propDef.set;
        }
        let coerce = identity;
        if (typeof propDef.coerce === 'function') {
            coerce = propDef.coerce;
        }
        registeredProps[propName] = {
            // internal value
            val,
            // linked attribute name
            attr: attrName,
            boolAttr,
            // function used to produce an attribute value from a
            // property value
            toAttr,
            // function used to produce a property value from an
            // attribute value
            fromAttr,
            // getter function
            get,
            // setter function
            set,
            // function to modify the value passed to the setter function
            coerce,
            // if the property has been set before
            hasSet: false,
        };
    }
    const observedAttrs = Object.keys(registeredAttrs);
    const DefinableCustomElement = class extends HTMLElement {
        constructor() {
            super();
            readyFn = readyFn.bind(this);
            for (const propName of Object.keys(registeredProps)) {
                // convenience aliases
                const internalProp = registeredProps[propName];
                const hasLinkedAttr = typeof internalProp.attr === 'string';
                const attrName = internalProp.attr;
                const internalAttr = registeredAttrs[attrName];
                // bind property methods to element context
                internalProp.toAttr = internalProp.toAttr.bind(this);
                internalProp.fromAttr = internalProp.fromAttr.bind(this);
                internalProp.get = internalProp.get.bind(this);
                internalProp.set = internalProp.set.bind(this);
                internalProp.coerce = internalProp.coerce.bind(this);
                Object.defineProperty(this, propName, {
                    set(val) {
                        let propVal = val;
                        propVal = internalProp.coerce(propVal);
                        if (internalProp.settingInitialValue) {
                            internalProp.settingInitialValue = false;
                        }
                        internalProp.val = propVal;
                        internalProp.set(propVal);
                        /*
                        We only propagate from the property to the attribute if:
                            - A linked attribute was defined
                            - The property setter is not being triggered by attributeChangedCallback
                        */
                        const beingInitialized = (this.hasAttribute(attrName)
                            && !internalProp.hasSet);
                        if (hasLinkedAttr && !beingInitialized) {
                            const attrVal = internalProp.toAttr(propVal);
                            // prevent the attribute from reflowing back to the
                            // property in attributeChangedCallback
                            internalAttr.needsPropagation = false;
                            if (attrVal !== undefined) {
                                // invoke attributeChangedCallback
                                this.setAttribute(attrName, attrVal);
                            }
                            else {
                                this.removeAttribute(attrName);
                            }
                        }
                        internalProp.hasSet = true;
                    },
                    get() {
                        const propVal = internalProp.get(internalProp.val);
                        return propVal;
                    },
                });
            }
            // insert element template
            const hasLocalTemplate = typeof def.template === 'string';
            const hasRemoteTemplate = typeof def.templateUrl === 'string';
            if (def.shadowDom) {
                this.attachShadow({ mode: 'open' });
            }
            if (hasLocalTemplate) {
                if (def.shadowDom) {
                    this.shadowRoot.innerHTML = def.template;
                }
                else {
                    this.innerHTML = def.template;
                }
            }
            else if (hasRemoteTemplate) {
                fetch(def.templateUrl).then((resp) => {
                    if (resp.ok) {
                        // 200 OK
                        return resp.text();
                    }
                    else {
                        // 404 et al
                        throw new Error(`Couldn't fetch template at ${def.templateUrl}. ` +
                            `Got HTTP status code ${status}`);
                    }
                }).then((template) => {
                    if (def.shadowDom) {
                        this.shadowRoot.innerHTML = template;
                    }
                    else {
                        this.innerHTML = template;
                    }
                });
            }
            // id caching enabled by default
            if (def.cacheIds !== false) {
                this.$ = {};
                let elsWithIds;
                if (def.shadowDom) {
                    elsWithIds = this.shadowRoot.querySelectorAll('[id]');
                }
                else {
                    elsWithIds = this.querySelectorAll('[id]');
                }
                for (const el of elsWithIds) {
                    const castEl = el;
                    this.$[castEl.id] = castEl;
                }
            }
        }
        connectedCallback() {
            if (hasConnected) {
                return;
            }
            // only run once
            for (const propName of Object.keys(props)) {
                const internalProp = registeredProps[propName];
                // if there is a value but the setter has not run
                if (internalProp.val !== undefined
                    && internalProp.val !== null
                    && !internalProp.hasSet) {
                    internalProp.settingInitialValue = true;
                    // kick off property setter
                    this[propName] = internalProp.val;
                }
            }
            // invoke ready function with element context
            readyFn.call(this);
            hasConnected = true;
        }
        attributeChangedCallback(attrName, oldVal, val) {
            // only do work if the new value differs
            if (val !== oldVal) {
                // convenience aliases
                const internalAttr = registeredAttrs[attrName];
                internalAttr.val = val;
                if (internalAttr.needsPropagation) {
                    // propagation should only occur once
                    internalAttr.needsPropagation = false;
                    const propName = internalAttr.propName;
                    const internalProp = registeredProps[propName];
                    const propVal = internalProp.fromAttr(val);
                    this[propName] = propVal;
                }
            }
        }
        static get observedAttributes() {
            // required for attributeChangedCallback to be called
            return observedAttrs;
        }
    };
    for (const fnName of Object.keys(methods)) {
        const fn = methods[fnName];
        if (typeof fn !== 'function') {
            throw new TypeError(`${fnName} must be a function (got ${fn})`);
        }
        DefinableCustomElement.prototype[fnName] = fn;
    }
    return DefinableCustomElement;
}
/* harmony default export */ __webpack_exports__["default"] = (makeElement);

/***/ })
/******/ ]);
});<|endoftext|>


<commit_before>import { dialog, app, shell, Menu } from 'electron';
import * as path from 'path';

import { launch, launchNewNotebook } from './launch';

const kernelspecs = require('kernelspecs');

function send(focusedWindow, eventName, obj) {
  if (!focusedWindow) {
    console.error('renderer window not in focus (are your devtools open?)');
    return;
  }
  focusedWindow.webContents.send(eventName, obj);
}

function createSender(eventName, obj) {
  return (item, focusedWindow) => {
    send(focusedWindow, eventName, obj);
  };
}

export const fileSubMenus = {
  new: {
    label: '&New',
    accelerator: 'CmdOrCtrl+N',
  },
  open: {
    label: '&Open',
    click: () => {
      const opts = {
        title: 'Open a notebook',
        filters: [
          { name: 'Notebooks', extensions: ['ipynb'] },
        ],
        properties: [
          'openFile',
        ],
        defaultPath: app.getPath('home'),
      };
      dialog.showOpenDialog(opts, (fname) => {
        if (fname) {
          launch(fname[0]);
        }
      });
    },
    accelerator: 'CmdOrCtrl+O',
  },
  save: {
    label: '&Save',
    click: createSender('menu:save'),
    accelerator: 'CmdOrCtrl+S',
  },
  saveAs: {
    label: 'Save &As',
    click: (item, focusedWindow) => {
      const opts = {
        title: 'Save Notebook As',
        filters: [{ name: 'Notebooks', extensions: ['ipynb'] }],
        defaultPath: app.getPath('home'),
      };
      dialog.showSaveDialog(opts, (filename) => {
        if (!filename) {
          return;
        }

        const ext = path.extname(filename) === '' ? '.ipynb' : '';
        send(focusedWindow, 'menu:save-as', `${filename}${ext}`);
      });
    },
    accelerator: 'CmdOrCtrl+Shift+S',
  },
  publish: {
    label: '&Publish',
    submenu: [
      {
        label: '&To Gist',
        click: createSender('menu:publish:gist'),
      },
    ],
  },
};

export const file = {
  label: '&File',
  submenu: [
    fileSubMenus.new,
    fileSubMenus.open,
    fileSubMenus.save,
    fileSubMenus.saveAs,
    fileSubMenus.publish,
  ],
};

export const edit = {
  label: 'Edit',
  submenu: [
    {
      label: 'Cut',
      accelerator: 'CmdOrCtrl+X',
      role: 'cut',
    },
    {
      label: 'Copy',
      accelerator: 'CmdOrCtrl+C',
      role: 'copy',
    },
    {
      label: 'Paste',
      accelerator: 'CmdOrCtrl+V',
      role: 'paste',
    },
    {
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
    },
    {
      type: 'separator',
    },
    {
      label: 'New Code Cell',
      accelerator: 'CmdOrCtrl+Shift+N',
      click: createSender('menu:new-code-cell'),
    },
    {
      label: 'Copy Cell',
      accelerator: 'CmdOrCtrl+Shift+C',
      click: createSender('menu:copy-cell'),
    },
    {
      label: 'Cut Cell',
      accelerator: 'CmdOrCtrl+Shift+X',
      click: createSender('menu:cut-cell'),
    },
    {
      label: 'Paste Cell',
      accelerator: 'CmdOrCtrl+Shift+V',
      click: createSender('menu:paste-cell'),
    },
  ],
};

export const cell = {
  label: 'Cell',
  submenu: [
    {
      label: 'Run All',
      click: createSender('menu:run-all'),
    },
    {
      label: 'Clear All',
      click: createSender('menu:clear-all'),
    },
  ],
};
const theme_menu = [
  {
    label: 'Light',
    click: createSender('menu:theme', 'light'),
  },
  {
    label: 'Dark',
    click: createSender('menu:theme', 'dark'),
  },
  {
    label: 'Classic',
    click: createSender('menu:theme', 'classic'),
  },
];

const today = new Date();
const day = today.getDate();
const month = today.getMonth() + 1;
if (month === 12) {
  theme_menu.push(
    {
      label: 'Hohoho',
      click: createSender('menu:theme', 'christmas'),
    });
} else if (month === 10 && day === 31) {
  theme_menu.push({
    label: 'Mwaaahahahhah',
    click: createSender('menu:theme', 'halloween'),
  });
}

export const view = {
  label: 'View',
  submenu: [
    {
      label: 'Reload',
      accelerator: 'CmdOrCtrl+R',
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.reload();
        }
      },
    },
    {
      label: 'Toggle Full Screen',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Ctrl+Command+F';
        }
        return 'F11';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
        }
      },
    },
    {
      label: 'Toggle Developer Tools',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Alt+Command+I';
        }
        return 'Ctrl+Shift+I';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.toggleDevTools();
        }
      },
    },
    {
      label: 'Zoom In',
      accelerator: 'CmdOrCtrl+=',
      click: createSender('menu:zoom-in'),
    },
    {
      label: 'Zoom Out',
      accelerator: 'CmdOrCtrl+-',
      click: createSender('menu:zoom-out'),
    },
    {
      label: 'Theme',
      submenu: theme_menu,
    },
  ],
};

const windowDraft = {
  label: 'Window',
  role: 'window',
  submenu: [
    {
      label: 'Minimize',
      accelerator: 'CmdOrCtrl+M',
      role: 'minimize',
    },
    {
      label: 'Close',
      accelerator: 'CmdOrCtrl+W',
      role: 'close',
    },
  ],
};

if (process.platform === 'darwin') {
  windowDraft.submenu.push(
    {
      type: 'separator',
    },
    {
      label: 'Bring All to Front',
      role: 'front',
    }
  );
}

export const window = windowDraft;

export const help = {
  label: 'Help',
  role: 'help',
  submenu: [
    {
      label: 'Learn More',
      click: () => { shell.openExternal('http://github.com/nteract/nteract'); },
    },
  ],
};

const name = 'nteract';
app.setName(name);

export const named = {
  label: name,
  submenu: [
    {
      label: `About ${name}`,
      role: 'about',
    },
    {
      type: 'separator',
    },
    {
      label: 'Services',
      role: 'services',
      submenu: [],
    },
    {
      type: 'separator',
    },
    {
      label: `Hide ${name}`,
      accelerator: 'Command+H',
      role: 'hide',
    },
    {
      label: 'Hide Others',
      accelerator: 'Command+Alt+H',
      role: 'hideothers',
    },
    {
      label: 'Show All',
      role: 'unhide',
    },
    {
      type: 'separator',
    },
    {
      label: 'Quit',
      accelerator: 'Command+Q',
      click: () => app.quit(),
    },
  ],
};

export function generateDefaultTemplate() {
  const template = [];

  if (process.platform === 'darwin') {
    template.push(named);
  }

  template.push(file);
  template.push(edit);
  template.push(view);
  template.push(window);
  template.push(help);

  return template;
}

export const defaultMenu = Menu.buildFromTemplate(generateDefaultTemplate());

export function loadFullMenu() {
  return kernelspecs.findAll().then((kernelSpecs) => {
    function generateSubMenu(kernelName) {
      return {
        label: kernelSpecs[kernelName].spec.display_name,
        click: createSender('menu:new-kernel', kernelName),
      };
    }

    const kernelMenuItems = Object.keys(kernelSpecs).map(generateSubMenu);

    const newNotebookItems = Object.keys(kernelSpecs)
      .map(kernelName => ({
        label: kernelSpecs[kernelName].spec.display_name,
        click: () => launchNewNotebook(kernelName),
      }));

    const languageMenu = {
      label: '&Language',
      submenu: [
        {
          label: '&Kill Running Kernel',
          click: createSender('menu:kill-kernel'),
        },
        {
          label: '&Interrupt Running Kernel',
          click: createSender('menu:interrupt-kernel'),
        },
        {
          label: 'Restart Running Kernel',
          click: createSender('menu:restart-kernel'),
        },
        {
          label: 'Restart and Clear All Cells',
          click: createSender('menu:restart-and-clear-all'),
        },
        {
          type: 'separator',
        },
        // All the available kernels
        ...kernelMenuItems,
      ],
    };

    const template = [];

    if (process.platform === 'darwin') {
      template.push(named);
    }

    const fileWithNew = {
      label: '&File',
      submenu: [
        {
          label: '&New',
          submenu: newNotebookItems,
        },
        fileSubMenus.open,
        fileSubMenus.save,
        fileSubMenus.saveAs,
        fileSubMenus.publish,
      ],
    };

    template.push(fileWithNew);
    template.push(edit);
    template.push(cell);
    template.push(view);

    // Application specific functionality should go before window and help
    template.push(languageMenu);
    template.push(window);
    template.push(help);

    const menu = Menu.buildFromTemplate(template);
    return menu;
  });
}
<commit_msg>feat(GithubAuth): Add initial function for github auth, change name to Github<commit_after>import { dialog, app, shell, Menu, ipcMain as ipc,
         BrowserWindow } from 'electron';
import * as path from 'path';

import { launch, launchNewNotebook } from './launch';

const kernelspecs = require('kernelspecs');

function send(focusedWindow, eventName, obj) {
  if (!focusedWindow) {
    console.error('renderer window not in focus (are your devtools open?)');
    return;
  }
  focusedWindow.webContents.send(eventName, obj);
}

function createSender(eventName, obj) {
  return (item, focusedWindow) => {
    send(focusedWindow, eventName, obj);
  };
}

export function githubAuth() {
  const win = new BrowserWindow({show: false, webPreferences: {zoomFactor: .75}});
  win.webContents.on('dom-ready', () => {
    if( win.getURL().match('authorize') ) {
      win.show();
      win.on('page-title-updated', () => {
        win.close()
        return githubAuth();
      });
    }
    else {
      win.webContents.executeJavaScript(`
        require('electron').ipcRenderer.send('auth', document.body.innerHTML);
        `);
      ipc.on('auth', (event, auth) => {
      // hacky parse of JSON
        auth = auth.match(/"\w+"/g)[1].match(/[^"]/g).join('')
        console.log(auth);
      });
    }
  });
  win.loadURL('http://localhost:3010/login');
}

export const fileSubMenus = {
  new: {
    label: '&New',
    accelerator: 'CmdOrCtrl+N',
  },
  open: {
    label: '&Open',
    click: () => {
      const opts = {
        title: 'Open a notebook',
        filters: [
          { name: 'Notebooks', extensions: ['ipynb'] },
        ],
        properties: [
          'openFile',
        ],
        defaultPath: app.getPath('home'),
      };
      dialog.showOpenDialog(opts, (fname) => {
        if (fname) {
          launch(fname[0]);
        }
      });
    },
    accelerator: 'CmdOrCtrl+O',
  },
  save: {
    label: '&Save',
    click: createSender('menu:save'),
    accelerator: 'CmdOrCtrl+S',
  },
  saveAs: {
    label: 'Save &As',
    click: (item, focusedWindow) => {
      const opts = {
        title: 'Save Notebook As',
        filters: [{ name: 'Notebooks', extensions: ['ipynb'] }],
        defaultPath: app.getPath('home'),
      };
      dialog.showSaveDialog(opts, (filename) => {
        if (!filename) {
          return;
        }

        const ext = path.extname(filename) === '' ? '.ipynb' : '';
        send(focusedWindow, 'menu:save-as', `${filename}${ext}`);
      });
    },
    accelerator: 'CmdOrCtrl+Shift+S',
  },
  publish: {
    label: '&Github',
    submenu: [
      {
        label: '&Authenticate',
        click: () => githubAuth(),
      },
      {
        label: '&Publish To Gist',
        click: createSender('menu:publish:gist'),
      },
    ],
  },
};

export const file = {
  label: '&File',
  submenu: [
    fileSubMenus.new,
    fileSubMenus.open,
    fileSubMenus.save,
    fileSubMenus.saveAs,
    fileSubMenus.publish,
  ],
};

export const edit = {
  label: 'Edit',
  submenu: [
    {
      label: 'Cut',
      accelerator: 'CmdOrCtrl+X',
      role: 'cut',
    },
    {
      label: 'Copy',
      accelerator: 'CmdOrCtrl+C',
      role: 'copy',
    },
    {
      label: 'Paste',
      accelerator: 'CmdOrCtrl+V',
      role: 'paste',
    },
    {
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
    },
    {
      type: 'separator',
    },
    {
      label: 'New Code Cell',
      accelerator: 'CmdOrCtrl+Shift+N',
      click: createSender('menu:new-code-cell'),
    },
    {
      label: 'Copy Cell',
      accelerator: 'CmdOrCtrl+Shift+C',
      click: createSender('menu:copy-cell'),
    },
    {
      label: 'Cut Cell',
      accelerator: 'CmdOrCtrl+Shift+X',
      click: createSender('menu:cut-cell'),
    },
    {
      label: 'Paste Cell',
      accelerator: 'CmdOrCtrl+Shift+V',
      click: createSender('menu:paste-cell'),
    },
  ],
};

export const cell = {
  label: 'Cell',
  submenu: [
    {
      label: 'Run All',
      click: createSender('menu:run-all'),
    },
    {
      label: 'Clear All',
      click: createSender('menu:clear-all'),
    },
  ],
};
const theme_menu = [
  {
    label: 'Light',
    click: createSender('menu:theme', 'light'),
  },
  {
    label: 'Dark',
    click: createSender('menu:theme', 'dark'),
  },
  {
    label: 'Classic',
    click: createSender('menu:theme', 'classic'),
  },
];

const today = new Date();
const day = today.getDate();
const month = today.getMonth() + 1;
if (month === 12) {
  theme_menu.push(
    {
      label: 'Hohoho',
      click: createSender('menu:theme', 'christmas'),
    });
} else if (month === 10 && day === 31) {
  theme_menu.push({
    label: 'Mwaaahahahhah',
    click: createSender('menu:theme', 'halloween'),
  });
}

export const view = {
  label: 'View',
  submenu: [
    {
      label: 'Reload',
      accelerator: 'CmdOrCtrl+R',
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.reload();
        }
      },
    },
    {
      label: 'Toggle Full Screen',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Ctrl+Command+F';
        }
        return 'F11';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
        }
      },
    },
    {
      label: 'Toggle Developer Tools',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Alt+Command+I';
        }
        return 'Ctrl+Shift+I';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.toggleDevTools();
        }
      },
    },
    {
      label: 'Zoom In',
      accelerator: 'CmdOrCtrl+=',
      click: createSender('menu:zoom-in'),
    },
    {
      label: 'Zoom Out',
      accelerator: 'CmdOrCtrl+-',
      click: createSender('menu:zoom-out'),
    },
    {
      label: 'Theme',
      submenu: theme_menu,
    },
  ],
};

const windowDraft = {
  label: 'Window',
  role: 'window',
  submenu: [
    {
      label: 'Minimize',
      accelerator: 'CmdOrCtrl+M',
      role: 'minimize',
    },
    {
      label: 'Close',
      accelerator: 'CmdOrCtrl+W',
      role: 'close',
    },
  ],
};

if (process.platform === 'darwin') {
  windowDraft.submenu.push(
    {
      type: 'separator',
    },
    {
      label: 'Bring All to Front',
      role: 'front',
    }
  );
}

export const window = windowDraft;

export const help = {
  label: 'Help',
  role: 'help',
  submenu: [
    {
      label: 'Learn More',
      click: () => { shell.openExternal('http://github.com/nteract/nteract'); },
    },
  ],
};

const name = 'nteract';
app.setName(name);

export const named = {
  label: name,
  submenu: [
    {
      label: `About ${name}`,
      role: 'about',
    },
    {
      type: 'separator',
    },
    {
      label: 'Services',
      role: 'services',
      submenu: [],
    },
    {
      type: 'separator',
    },
    {
      label: `Hide ${name}`,
      accelerator: 'Command+H',
      role: 'hide',
    },
    {
      label: 'Hide Others',
      accelerator: 'Command+Alt+H',
      role: 'hideothers',
    },
    {
      label: 'Show All',
      role: 'unhide',
    },
    {
      type: 'separator',
    },
    {
      label: 'Quit',
      accelerator: 'Command+Q',
      click: () => app.quit(),
    },
  ],
};

export function generateDefaultTemplate() {
  const template = [];

  if (process.platform === 'darwin') {
    template.push(named);
  }

  template.push(file);
  template.push(edit);
  template.push(view);
  template.push(window);
  template.push(help);

  return template;
}

export const defaultMenu = Menu.buildFromTemplate(generateDefaultTemplate());

export function loadFullMenu() {
  return kernelspecs.findAll().then((kernelSpecs) => {
    function generateSubMenu(kernelName) {
      return {
        label: kernelSpecs[kernelName].spec.display_name,
        click: createSender('menu:new-kernel', kernelName),
      };
    }

    const kernelMenuItems = Object.keys(kernelSpecs).map(generateSubMenu);

    const newNotebookItems = Object.keys(kernelSpecs)
      .map(kernelName => ({
        label: kernelSpecs[kernelName].spec.display_name,
        click: () => launchNewNotebook(kernelName),
      }));

    const languageMenu = {
      label: '&Language',
      submenu: [
        {
          label: '&Kill Running Kernel',
          click: createSender('menu:kill-kernel'),
        },
        {
          label: '&Interrupt Running Kernel',
          click: createSender('menu:interrupt-kernel'),
        },
        {
          label: 'Restart Running Kernel',
          click: createSender('menu:restart-kernel'),
        },
        {
          label: 'Restart and Clear All Cells',
          click: createSender('menu:restart-and-clear-all'),
        },
        {
          type: 'separator',
        },
        // All the available kernels
        ...kernelMenuItems,
      ],
    };

    const template = [];

    if (process.platform === 'darwin') {
      template.push(named);
    }

    const fileWithNew = {
      label: '&File',
      submenu: [
        {
          label: '&New',
          submenu: newNotebookItems,
        },
        fileSubMenus.open,
        fileSubMenus.save,
        fileSubMenus.saveAs,
        fileSubMenus.publish,
      ],
    };

    template.push(fileWithNew);
    template.push(edit);
    template.push(cell);
    template.push(view);

    // Application specific functionality should go before window and help
    template.push(languageMenu);
    template.push(window);
    template.push(help);

    const menu = Menu.buildFromTemplate(template);
    return menu;
  });
}
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2009-2013, rultor.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met: 1) Redistributions of source code must retain the above
 * copyright notice, this list of conditions and the following
 * disclaimer. 2) Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided
 * with the distribution. 3) Neither the name of the rultor.com nor
 * the names of its contributors may be used to endorse or promote
 * products derived from this software without specific prior written
 * permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

function fetch($div) {
    var entry = $div.attr('data-fetch-url');
    if (!entry) {
        console.log('fetch URL is absent!');
        return;
    }
    $div.find('.heart').addClass('text-warning');
    $div.find('.body').load(
        entry,
        function(text, status, xhr) {
            if (status == "error") {
                $div.find('.heart').addClass('text-danger');
                $div.find('.heart').attr('title', text);
            } else {
                $div.find('.heart').removeClass('text-warning');
                RULTOR.format($div);
                setTimeout(function() { fetch($div); }, 5000);
            }
        }
    );
}

$(document).ready(
    function() {
        $('div:has(.body)').each(
            function () {
                fetch($(this));
            }
        );
        $('.heart').each(
            function () {
                $(this).click(
                    function() {
                        var $div = $(this).parent().parent().parent();
                        if ($div.attr('data-fetch-stop')) {
                        } else {
                            $div.attr('data-fetch-stop', 'yes');
                            $(this).addClass('text-danger');
                        }
                    }
                );
            }
        );
    }
);
<commit_msg>click to stop fetching<commit_after>/**
 * Copyright (c) 2009-2013, rultor.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met: 1) Redistributions of source code must retain the above
 * copyright notice, this list of conditions and the following
 * disclaimer. 2) Redistributions in binary form must reproduce the above
 * copyright notice, this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided
 * with the distribution. 3) Neither the name of the rultor.com nor
 * the names of its contributors may be used to endorse or promote
 * products derived from this software without specific prior written
 * permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
 * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
 * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

function fetch($div) {
    var entry = $div.attr('data-fetch-url');
    if (!entry) {
        console.log('fetch URL is absent!');
        return;
    }
    if ($div.attr('data-fetch-stop')) {
        return;
    }
    $div.find('.heart').addClass('text-warning');
    $div.find('.body').load(
        entry,
        function(text, status, xhr) {
            if (status == "error") {
                $div.find('.heart').addClass('text-danger');
                $div.find('.heart').attr('title', text);
            } else {
                $div.find('.heart').removeClass('text-warning');
                RULTOR.format($div);
                setTimeout(function() { fetch($div); }, 5000);
            }
        }
    );
}

$(document).ready(
    function() {
        $('div:has(.body)').each(
            function () {
                fetch($(this));
            }
        );
        $('.heart').each(
            function () {
                $(this).click(
                    function() {
                        var $div = $(this).parent().parent().parent();
                        if ($div.attr('data-fetch-stop')) {
                            $div.removeAttr('data-fetch-stop');
                            $(this).removeClass('text-danger');
                            fetch($div);
                        } else {
                            $div.attr('data-fetch-stop', 'yes');
                            $(this).addClass('text-danger');
                        }
                    }
                );
            }
        );
    }
);
<|endoftext|>


<commit_before>// sharedflow.js
// ------------------------------------------------------------------
//
// Tests for Sharedflow operations.
//
// 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
//
//     https://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.
//
// created: Sat Apr 29 09:17:48 2017
// last saved: <2018-December-03 09:25:35>

/* global describe, faker, it, path, before */

const common = require('./common'),
      fs = require('fs');

describe('Sharedflow', function() {
  const resourceDir = "./test/resources",
        dateVal = new Date().valueOf(),
        contrivedNamePrefix = 'apigee-edge-js-test-' + dateVal;

  this.timeout(common.testTimeout);
  common.connectEdge(function(edgeOrg){

    describe('sf-import-from-zip-and-get', function() {
      var sharedFlowList;
      var zipFileList;
      var envList;

      before(function(done){
        var actualPath = path.resolve(resourceDir);
        fs.readdir(actualPath, function(e, items) {
          assert.isNull(e, "error getting zips: " + JSON.stringify(e));
          var re = new RegExp('^sharedflow-.+\.zip$');
          items = items.filter(function(item){ return item.match(re);});
          zipFileList = items.map(function(item){ return path.resolve( path.join(resourceDir, item));});
          edgeOrg.environments.get(function(e, result) {
            assert.isNull(e, "error listing: " + JSON.stringify(e));
            envList = result;
            done();
          });
        });
      });

      it('should import sharedflow zips into an org', function(done) {
        this.timeout(15000);
        var numDone = 0;
        zipFileList.forEach(function(zip){
          var contrivedName = contrivedNamePrefix + '-fromzip-' + faker.random.alphaNumeric(12);
          edgeOrg.sharedflows.importFromZip({name:contrivedName, zipArchive:zip}, function(e, result){
            assert.isNull(e, "error importing zip: " + JSON.stringify(e));
            numDone++;
            if (numDone == zipFileList.length) { done(); }
          });
        });
      });

      it('should import sharedflow zips via the simple method', function(done) {
        this.timeout(15000);
        var numDone = 0;
        zipFileList.forEach(function(zip){
          var contrivedName = contrivedNamePrefix + '-fromzip-simple-' + faker.random.alphaNumeric(12);
          edgeOrg.sharedflows.import({name:contrivedName, source:zip}, function(e, result){
            assert.isNull(e, "error importing zip: " + JSON.stringify(e));
            numDone++;
            if (numDone == zipFileList.length) { done(); }
          });
        });
      });

      it('should list all sharedflows for an org', function(done) {
        edgeOrg.sharedflows.get({}, function(e, result){
          assert.isNull(e, "error getting sharedflows: " + JSON.stringify(e));
          assert.isDefined(result.length, "sharedflow list");
          assert.isAbove(result.length, 1, "length of sharedflow list");
          sharedFlowList = result;
          done();
        });
      });

      it('should get one sharedFlow', function(done) {
        assert.isTrue(sharedFlowList && sharedFlowList.length>0);
        var ix = Math.floor(Math.random() * sharedFlowList.length);
        edgeOrg.sharedflows.get({name:sharedFlowList[ix]}, function(e, result){
          assert.isNull(e, "error getting sharedflow: " + JSON.stringify(e));
          //utility.logWrite(JSON.stringify(result, null, 2));
          assert.equal(sharedFlowList[ix], result.name, "sharedflow name");
          done();
        });
      });

      it('should export a few sharedflows', function(done) {
        var numWanted = 4;
        var numDone = 0;
        var cb = function(e, result) {
              assert.isNull(e, "error exporting sharedflow: " + JSON.stringify(e));
              //utility.logWrite(JSON.stringify(result, null, 2));
              assert.isTrue(result.filename.startsWith('sharedflow-'), "file name");
              if (++numDone >= numWanted) { done(); }
            };
        assert.isTrue(sharedFlowList && sharedFlowList.length>0);
        for(var i = 0; i<numWanted; i++) {
          var ix = Math.floor(Math.random() * sharedFlowList.length);
          edgeOrg.sharedflows.export({name:sharedFlowList[ix]}, cb);
        }
      });

      it('should fail to get a non-existent sharedflow', function(done) {
        var fakeName = 'sharedflow-' + faker.random.alphaNumeric(23);
        edgeOrg.sharedflows.get({name:fakeName}, function(e, result){
          assert.isNotNull(e, "the expected error did not occur");
          done();
        });
      });

      it('should delete test sharedflows previously imported into this org', function(done) {
        var numDone = 0, L = 0;
        var tick = function() { if (++numDone >= L) { done(); } };
        edgeOrg.sharedflows.get({}, function(e, sharedflows){
          assert.isNull(e, "error getting sharedflows: " + JSON.stringify(e));
          assert.isAbove(sharedflows.length, 1, "length of SF list");
          L = sharedflows.length;
          sharedflows.forEach(function(sf) {
            if (sf.startsWith(contrivedNamePrefix + '-fromzip-')) {
              edgeOrg.sharedflows.del({name:sf}, function(e, proxies){
                assert.isNull(e, "error deleting sharedflow: " + JSON.stringify(e));
                tick();
              });
            }
            else { tick(); }
          });
        });
      });
    });

    // describe('get', function() {
    //
    //   before(function(done){
    //     edgeOrg.sharedflows.get({}, function(e, result){
    //       assert.isNull(e, "error getting sharedflows: " + JSON.stringify(e));
    //       assert.isDefined(result.length, "sharedflow list");
    //       assert.isAbove(result.length, 1, "length of sharedflow list");
    //       sharedFlowList = result;
    //       done();
    //     });
    //   });
    //
    //
    // });

  });

});
<commit_msg>minor change to code comments<commit_after>// sharedflow.js
// ------------------------------------------------------------------
//
// Tests for Sharedflow operations.
//
// 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
//
//     https://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.
//
// created: Sat Apr 29 09:17:48 2017
// last saved: <2018-December-04 11:26:03>

/* global describe, faker, it, path, before */

const common = require('./common'),
      fs = require('fs');

describe('Sharedflow', function() {
  const resourceDir = "./test/resources",
        dateVal = new Date().valueOf(),
        contrivedNamePrefix = 'apigee-edge-js-test-' + dateVal;

  this.timeout(common.testTimeout);
  common.connectEdge(function(edgeOrg){

    describe('sf-import-from-zip-and-get', function() {
      var sharedFlowList;
      var zipFileList;
      var envList;

      before(function(done){
        var actualPath = path.resolve(resourceDir);
        fs.readdir(actualPath, function(e, items) {
          assert.isNull(e, "error getting zips: " + JSON.stringify(e));
          var re = new RegExp('^sharedflow-.+\.zip$');
          items = items.filter(function(item){ return item.match(re);});
          zipFileList = items.map(function(item){ return path.resolve( path.join(resourceDir, item));});
          edgeOrg.environments.get(function(e, result) {
            assert.isNull(e, "error listing: " + JSON.stringify(e));
            envList = result;
            done();
          });
        });
      });

      it('should import sharedflow zips into an org', function(done) {
        this.timeout(15000);
        var numDone = 0;
        zipFileList.forEach(function(zip){
          var contrivedName = contrivedNamePrefix + '-fromzip-' + faker.random.alphaNumeric(12);
          edgeOrg.sharedflows.importFromZip({name:contrivedName, zipArchive:zip}, function(e, result){
            assert.isNull(e, "error importing zip: " + JSON.stringify(e));
            numDone++;
            if (numDone == zipFileList.length) { done(); }
          });
        });
      });

      it('should import sharedflow zips via the simple method', function(done) {
        this.timeout(15000);
        var numDone = 0;
        zipFileList.forEach(function(zip){
          var contrivedName = contrivedNamePrefix + '-fromzip-simple-' + faker.random.alphaNumeric(12);
          edgeOrg.sharedflows.import({name:contrivedName, source:zip}, function(e, result){
            assert.isNull(e, "error importing zip: " + JSON.stringify(e));
            numDone++;
            if (numDone == zipFileList.length) { done(); }
          });
        });
      });

      it('should list all sharedflows for an org', function(done) {
        edgeOrg.sharedflows.get({}, function(e, result){
          assert.isNull(e, "error getting sharedflows: " + JSON.stringify(e));
          assert.isDefined(result.length, "sharedflow list");
          assert.isAbove(result.length, 1, "length of sharedflow list");
          sharedFlowList = result;
          done();
        });
      });

      it('should get one randomly-selected sharedFlow', function(done) {
        assert.isTrue(sharedFlowList && sharedFlowList.length>0);
        var ix = Math.floor(Math.random() * sharedFlowList.length);
        edgeOrg.sharedflows.get({name:sharedFlowList[ix]}, function(e, result){
          assert.isNull(e, "error getting sharedflow: " + JSON.stringify(e));
          //utility.logWrite(JSON.stringify(result, null, 2));
          assert.equal(sharedFlowList[ix], result.name, "sharedflow name");
          done();
        });
      });

      it('should export a few sharedflows', function(done) {
        var numWanted = 4;
        var numDone = 0;
        var cb = function(e, result) {
              assert.isNull(e, "error exporting sharedflow: " + JSON.stringify(e));
              //utility.logWrite(JSON.stringify(result, null, 2));
              assert.isTrue(result.filename.startsWith('sharedflow-'), "file name");
              if (++numDone >= numWanted) { done(); }
            };
        assert.isTrue(sharedFlowList && sharedFlowList.length>0);
        for(var i = 0; i<numWanted; i++) {
          // the selected item may be repeated
          var ix = Math.floor(Math.random() * sharedFlowList.length);
          edgeOrg.sharedflows.export({name:sharedFlowList[ix]}, cb);
        }
      });

      it('should fail to get a non-existent sharedflow', function(done) {
        var fakeName = 'sharedflow-' + faker.random.alphaNumeric(23);
        edgeOrg.sharedflows.get({name:fakeName}, function(e, result){
          assert.isNotNull(e, "the expected error did not occur");
          done();
        });
      });

      it('should delete test sharedflows previously imported into this org', function(done) {
        var numDone = 0, L = 0;
        var tick = function() { if (++numDone >= L) { done(); } };
        edgeOrg.sharedflows.get({}, function(e, sharedflows){
          assert.isNull(e, "error getting sharedflows: " + JSON.stringify(e));
          assert.isAbove(sharedflows.length, 1, "length of SF list");
          L = sharedflows.length;
          sharedflows.forEach(function(sf) {
            if (sf.startsWith(contrivedNamePrefix + '-fromzip-')) {
              edgeOrg.sharedflows.del({name:sf}, function(e, proxies){
                assert.isNull(e, "error deleting sharedflow: " + JSON.stringify(e));
                tick();
              });
            }
            else { tick(); }
          });
        });
      });
    });

    // describe('get', function() {
    //
    //   before(function(done){
    //     edgeOrg.sharedflows.get({}, function(e, result){
    //       assert.isNull(e, "error getting sharedflows: " + JSON.stringify(e));
    //       assert.isDefined(result.length, "sharedflow list");
    //       assert.isAbove(result.length, 1, "length of sharedflow list");
    //       sharedFlowList = result;
    //       done();
    //     });
    //   });
    //
    //
    // });

  });

});
<|endoftext|>


<commit_before>var assert = require('assert');
var StyleStats = require('../lib/stylestats.js');

describe('CSS Statistics', function() {
    var stats = new StyleStats('test/fixture/test.css');
    var statsResult;
    before(function(done) {
        stats.parse(function(error, result) {
            if (error) {
                throw error;
            }
            statsResult = result;
            done();
        });
    });
    it('should return stylesheets', function() {
        assert.equal(statsResult.stylesheets, 1);
    });
    it('should return file size', function() {
        assert.equal(statsResult.size, 753);
    });
    it('should return data URI size', function() {
        assert.equal(statsResult.dataUriSize, 82);
    });
    it('should return ratio of data URI size', function() {
        assert.equal(statsResult.ratioOfDataUriSize, 0.10889774236387782);
    });
    it('should return css rules', function() {
        assert.equal(statsResult.rules, 10);
    });
    it('should return css selectors', function() {
        assert.equal(statsResult.selectors, 15);
    });
    it('should return simplicity', function() {
        assert.equal(statsResult.simplicity, 0.6666666666666666);
    });
    it('should return most identifier', function() {
        assert.equal(statsResult.mostIdentifier, 5);
    });
    it('should return most identifier selector', function() {
        assert.equal(statsResult.mostIdentifierSelector, '.foo  .bar > .baz + .qux ~ .quux:before');
    });
    it('should return lowest cohesion', function() {
        assert.equal(statsResult.lowestCohesion, 8);
    });
    it('should return lowest cohesion selector', function() {
        assert.equal(statsResult.lowestCohesionSelector, 'hr');
    });
    it('should return total unique font sizes', function() {
        assert.equal(statsResult.totalUniqueFontSizes, 5);
    });
    it('should return total unique colors', function() {
        assert.equal(statsResult.totalUniqueColors, 2);
    });
    it('should return id selectors', function() {
        assert.equal(statsResult.idSelectors, 1);
    });
    it('should return universal selectors', function() {
        assert.equal(statsResult.universalSelectors, 1);
    });
    it('should return unqualified attribute selectors', function() {
        assert.equal(statsResult.unqualifiedAttributeSelectors, 1);
    });
    it('should return JavaScript specific selectors', function() {
        assert.equal(statsResult.javascriptSpecificSelectors, 1);
    });
    it('should return important keywords', function() {
        assert.equal(statsResult.importantKeywords, 1);
    });
    it('should return float properties', function() {
        assert.equal(statsResult.floatProperties, 1);
    });
    it('should return media queries"', function() {
        assert.equal(statsResult.mediaQueries, 1);
    });
});

describe('Customize with configuration file', function() {
    it('should return gzipped size', function(done) {
        var customStats = new StyleStats('test/fixture/test.css', 'test/fixture/.stylestatsrc');
        customStats.parse(function(error, customResult) {
            if (error) {
                throw error;
            }
            assert.equal(customResult.gzippedSize, 217);
            done();
        });
    });
});

describe('Invalid argument', function() {
    it('should throw error', function(done) {
        assert.throws(
            function() {
                new StyleStats('xxxxxxxxxxxxxxxx');
            },
            Error
        );
        done();
    });
});

describe('Customize with option', function() {
    it('should return gzipped size', function(done) {
        var customObjectStats = new StyleStats('test/fixture/test.css', {
            gzippedSize: true
        });
        customObjectStats.parse(function(error, customObjectResult) {
            if (error) {
                throw error;
            }
            assert.equal(customObjectResult.gzippedSize, 217);
            done();
        });
    });
});

describe('Analyze remote css file', function() {
    it('should return file size', function(done) {
        var requestStats = new StyleStats('http://t32k.me/static/blog/skelton.css?query');
        requestStats.parse(function(error, requestResult) {
            if (error) {
                throw error;
            }
            assert.equal(requestResult.size, 15419);
            done();
        });
    });
});

describe('Analyze HTML pages', function() {
    it('should return the number of stylesheets', function(done) {
        var htmlStats = new StyleStats('http://t32k.me/');
        htmlStats.parse(function(error, htmlResult) {
            if (error) {
                throw error;
            }
            assert.equal(htmlResult.size, 15419);
            done();
        });
    });
});

describe('Analyze files of specified directory', function() {
    it('should return file size', function(done) {
        var dirStats = new StyleStats('test/fixture/');
        dirStats.parse(function(error, dirResult) {
            if (error) {
                throw error;
            }
            assert.equal(dirResult.size, 20462);
            done();
        });
    });
});

describe('Analyze files which match specified glob', function() {
    it('should return file size', function(done) {
        var globStats = new StyleStats('test/**/*.css');
        globStats.parse(function(error, globResult) {
            if (error) {
                throw error;
            }
            assert.equal(globResult.size, 39931);
            done();
        });
    });
});

describe('Analyze multiple files', function() {
    it('should return the number of stylesheets', function(done) {
        var multipleStats = new StyleStats(['test/fixture/test.css', 'test/fixture/app.css']);
        multipleStats.parse(function(error, multipleResult) {
            if (error) {
                throw error;
            }
            assert.equal(multipleResult.stylesheets, 2);
            done();
        });
    });
});

describe('Analyze raw contents files', function() {
    it('should return the number of stylesheets', function(done) {
        var rawStats = new StyleStats('body{color:green}');
        rawStats.parse(function(error, rawResult) {
            if (error) {
                throw error;
            }
            assert.equal(rawResult.stylesheets, 0);
            done();
        });
    });
    it('should return file size', function(done) {
        var rawStats = new StyleStats('body{color:green}');
        rawStats.parse(function(error, rawResult) {
            if (error) {
                throw error;
            }
            assert.equal(rawResult.size, 17);
            done();
        });
    });
});

describe('Analyze LESS files', function() {
    it('should return file size', function(done) {
        var lessStats = new StyleStats('test/fixture/prepros/foo.less');
        lessStats.parse(function(error, lessResult) {
            if (error) {
                throw error;
            }
            assert.equal(lessResult.size, 499);
            done();
        });
    });
});

describe('Analyze Stylus files', function() {
    it('should return file size', function(done) {
        var stylStats = new StyleStats('test/fixture/prepros/foo.styl');
        stylStats.parse(function(error, stylResult) {
            if (error) {
                throw error;
            }
            assert.equal(stylResult.size, 259);
            done();
        });
    });
});<commit_msg>Add tests<commit_after>var assert = require('assert');
var StyleStats = require('../lib/stylestats.js');

describe('CSS Statistics', function() {
    var stats = new StyleStats('test/fixture/test.css');
    var statsResult;
    before(function(done) {
        stats.parse(function(error, result) {
            if (error) {
                throw error;
            }
            statsResult = result;
            done();
        });
    });
    it('should return stylesheets', function() {
        assert.equal(statsResult.stylesheets, 1);
    });
    it('should return file size', function() {
        assert.equal(statsResult.size, 753);
    });
    it('should return data URI size', function() {
        assert.equal(statsResult.dataUriSize, 82);
    });
    it('should return ratio of data URI size', function() {
        assert.equal(statsResult.ratioOfDataUriSize, 0.10889774236387782);
    });
    it('should return css rules', function() {
        assert.equal(statsResult.rules, 10);
    });
    it('should return css selectors', function() {
        assert.equal(statsResult.selectors, 15);
    });
    it('should return simplicity', function() {
        assert.equal(statsResult.simplicity, 0.6666666666666666);
    });
    it('should return most identifier', function() {
        assert.equal(statsResult.mostIdentifier, 5);
    });
    it('should return most identifier selector', function() {
        assert.equal(statsResult.mostIdentifierSelector, '.foo  .bar > .baz + .qux ~ .quux:before');
    });
    it('should return lowest cohesion', function() {
        assert.equal(statsResult.lowestCohesion, 8);
    });
    it('should return lowest cohesion selector', function() {
        assert.equal(statsResult.lowestCohesionSelector, 'hr');
    });
    it('should return total unique font sizes', function() {
        assert.equal(statsResult.totalUniqueFontSizes, 5);
    });
    it('should return total unique colors', function() {
        assert.equal(statsResult.totalUniqueColors, 2);
    });
    it('should return id selectors', function() {
        assert.equal(statsResult.idSelectors, 1);
    });
    it('should return universal selectors', function() {
        assert.equal(statsResult.universalSelectors, 1);
    });
    it('should return unqualified attribute selectors', function() {
        assert.equal(statsResult.unqualifiedAttributeSelectors, 1);
    });
    it('should return JavaScript specific selectors', function() {
        assert.equal(statsResult.javascriptSpecificSelectors, 1);
    });
    it('should return important keywords', function() {
        assert.equal(statsResult.importantKeywords, 1);
    });
    it('should return float properties', function() {
        assert.equal(statsResult.floatProperties, 1);
    });
    it('should return media queries"', function() {
        assert.equal(statsResult.mediaQueries, 1);
    });
});

describe('Customize with configuration file', function() {
    it('should return gzipped size', function(done) {
        var customStats = new StyleStats('test/fixture/test.css', 'test/fixture/.stylestatsrc');
        customStats.parse(function(error, customResult) {
            if (error) {
                throw error;
            }
            assert.equal(customResult.gzippedSize, 217);
            done();
        });
    });
});

describe('Invalid argument', function() {
    it('should throw error', function(done) {
        assert.throws(
            function() {
                new StyleStats('xxxxxxxxxxxxxxxx');
            },
            Error
        );
        done();
    });
});

describe('Invalid CSS', function() {
    it('should throw error', function(done) {
        var invalidCSS = new StyleStats('http://t32k.me/static/assets/css/invalid.css');
        assert.throws(
            invalidCSS.parse(function(error, invalidCSSResult) {
                if (error) {
                    throw error;
                }
                console.log(invalidCSSResult);
            }),
            Error
        );
        done();
    });
});

describe('Invalid JSON', function() {
    it('should throw error', function(done) {
        var invalidJSON = new StyleStats('http://t32k.me/static/assets/json/foo.json');
        assert.throws(
            invalidJSON.parse(function(error, invalidJSONResult) {
                if (error) {
                    throw error;
                }
                console.log(invalidJSONResult);
            }),
            Error
        );
        done();
    });
});

describe('Customize with option', function() {
    it('should return gzipped size', function(done) {
        var customObjectStats = new StyleStats('test/fixture/test.css', {
            gzippedSize: true
        });
        customObjectStats.parse(function(error, customObjectResult) {
            if (error) {
                throw error;
            }
            assert.equal(customObjectResult.gzippedSize, 217);
            done();
        });
    });
});

describe('Analyze remote css file', function() {
    it('should return file size', function(done) {
        var requestStats = new StyleStats('http://t32k.me/static/blog/skelton.css?query');
        requestStats.parse(function(error, requestResult) {
            if (error) {
                throw error;
            }
            assert.equal(requestResult.size, 15419);
            done();
        });
    });
});

describe('Analyze HTML pages', function() {
    it('should return the number of stylesheets', function(done) {
        var htmlStats = new StyleStats('http://t32k.me/');
        htmlStats.parse(function(error, htmlResult) {
            if (error) {
                throw error;
            }
            assert.equal(htmlResult.size, 15419);
            done();
        });
    });
});

describe('Analyze files of specified directory', function() {
    it('should return file size', function(done) {
        var dirStats = new StyleStats('test/fixture/');
        dirStats.parse(function(error, dirResult) {
            if (error) {
                throw error;
            }
            assert.equal(dirResult.size, 20462);
            done();
        });
    });
});

describe('Analyze files which match specified glob', function() {
    it('should return file size', function(done) {
        var globStats = new StyleStats('test/**/*.css');
        globStats.parse(function(error, globResult) {
            if (error) {
                throw error;
            }
            assert.equal(globResult.size, 39931);
            done();
        });
    });
});

describe('Analyze multiple files', function() {
    it('should return the number of stylesheets', function(done) {
        var multipleStats = new StyleStats(['test/fixture/test.css', 'test/fixture/app.css']);
        multipleStats.parse(function(error, multipleResult) {
            if (error) {
                throw error;
            }
            assert.equal(multipleResult.stylesheets, 2);
            done();
        });
    });
});

describe('Analyze raw contents files', function() {
    it('should return the number of stylesheets', function(done) {
        var rawStats = new StyleStats('body{color:green}');
        rawStats.parse(function(error, rawResult) {
            if (error) {
                throw error;
            }
            assert.equal(rawResult.stylesheets, 0);
            done();
        });
    });
    it('should return file size', function(done) {
        var rawStats = new StyleStats('body{color:green}');
        rawStats.parse(function(error, rawResult) {
            if (error) {
                throw error;
            }
            assert.equal(rawResult.size, 17);
            done();
        });
    });
});

describe('Analyze LESS files', function() {
    it('should return file size', function(done) {
        var lessStats = new StyleStats('test/fixture/prepros/foo.less');
        lessStats.parse(function(error, lessResult) {
            if (error) {
                throw error;
            }
            assert.equal(lessResult.size, 499);
            done();
        });
    });
});

describe('Analyze Stylus files', function() {
    it('should return file size', function(done) {
        var stylStats = new StyleStats('test/fixture/prepros/foo.styl');
        stylStats.parse(function(error, stylResult) {
            if (error) {
                throw error;
            }
            assert.equal(stylResult.size, 259);
            done();
        });
    });
});<|endoftext|>


<commit_before>var debug = require('debug')('supervisor:test');
var spawn = require('child_process').spawn;
var path = require('path');

var slr = path.resolve('bin/slr');
var cwd = process.cwd();

function once(fn) {
  return function() {
    if(fn) {
      fn.apply(null, arguments);
      fn = null;
    }
  }
}

describe('supervisor', function(done) {
  var child;

  this.timeout(4000); // CI machines are slow for process creation

  this.afterEach(function(done) {
    process.chdir(cwd);
    if(!child || child.exitCode != null || child.signalCode) {
      return done();
    }
    child.on('exit', function() {
      done();
    }).kill('SIGKILL');
  });

  function run(dir, args, expectations) {
    it('should run ['+args.join(',')+'] from '+dir, function(done) {
      done = once(done);
      process.chdir(dir);
      child = spawn(slr, args).on('error', done);

      child.stdout.on('data', data);
      child.stderr.on('data', data);

      function data(data) {
        debug('> ' + data)
        expectations = expectations.filter(function(expect) {
          return !expect.test(data);
        });
        if(expectations.length == 0) {
          return done();
        }
      }
    });
  }

  describe('loopback', function() {
    var EXPECT = [
      /LoopBack server listening/,
      /profiling/
    ];

    run('.', ['test/lb-app'], EXPECT);
    run('.', ['test/lb-app/.'], EXPECT);
    run('.', ['test/lb-app/app.js'], EXPECT);
    run('test/lb-app', [], EXPECT);
    run('test/lb-app', ['.'], EXPECT);
    run('test/lb-app', ['app.js'], EXPECT);
  });

  describe('express', function() {
    var EXPECT = [
      /express-app listening/
    ];

    run('.', ['test/express-app'], EXPECT);
    run('.', ['test/express-app/.'], EXPECT);
    run('.', ['test/express-app/server.js'], EXPECT);
    run('test/express-app', [], EXPECT);
    run('test/express-app', ['.'], EXPECT);
    run('test/express-app', ['server.js'], EXPECT);
  });

  describe('module', function() {
    var EXPECT = [
      /module-app listening/
    ];

    run('.', ['test/module-app'], EXPECT);
    run('.', ['test/module-app/.'], EXPECT);
    run('.', ['test/module-app/index.js'], EXPECT);
    run('test/module-app', [], EXPECT);
    run('test/module-app', ['.'], EXPECT);
    run('test/module-app', ['index.js'], EXPECT);
  });

  describe('argument processing', function() {
    var EXPECT = [
      /module-app listening/,
      /argv:.*index.js.*size=10/
    ];

    run('.', ['--size', '0', 'test/module-app/index.js', '--size=10'], EXPECT);
    run('.', ['--size', '1', 'test/module-app/index.js', '--size=10'], EXPECT);

    run('.', ['--help', 'help-option'], [/usage: slr/]);
    run('.', ['-h', 'h-option'], [/usage: slr/]);

    var VERSION = RegExp('v'+require('../package.json').version);

    run('.', ['--version', 'version-option'], [VERSION]);
    run('.', ['-v', 'v-option'], [VERSION]);
  });
});
<commit_msg>Use a --size of 'off' to get no clustering<commit_after>var debug = require('debug')('supervisor:test');
var spawn = require('child_process').spawn;
var path = require('path');

var slr = path.resolve('bin/slr');
var cwd = process.cwd();

function once(fn) {
  return function() {
    if(fn) {
      fn.apply(null, arguments);
      fn = null;
    }
  }
}

describe('supervisor', function(done) {
  var child;

  this.timeout(4000); // CI machines are slow for process creation

  this.afterEach(function(done) {
    process.chdir(cwd);
    if(!child || child.exitCode != null || child.signalCode) {
      return done();
    }
    child.on('exit', function() {
      done();
    }).kill('SIGKILL');
  });

  function run(dir, args, expectations) {
    it('should run ['+args.join(',')+'] from '+dir, function(done) {
      done = once(done);
      process.chdir(dir);
      child = spawn(slr, args).on('error', done);

      child.stdout.on('data', data);
      child.stderr.on('data', data);

      function data(data) {
        debug('> ' + data)
        expectations = expectations.filter(function(expect) {
          return !expect.test(data);
        });
        if(expectations.length == 0) {
          return done();
        }
      }
    });
  }

  describe('loopback', function() {
    var EXPECT = [
      /LoopBack server listening/,
      /profiling/
    ];

    run('.', ['test/lb-app'], EXPECT);
    run('.', ['test/lb-app/.'], EXPECT);
    run('.', ['test/lb-app/app.js'], EXPECT);
    run('test/lb-app', [], EXPECT);
    run('test/lb-app', ['.'], EXPECT);
    run('test/lb-app', ['app.js'], EXPECT);
  });

  describe('express', function() {
    var EXPECT = [
      /express-app listening/
    ];

    run('.', ['test/express-app'], EXPECT);
    run('.', ['test/express-app/.'], EXPECT);
    run('.', ['test/express-app/server.js'], EXPECT);
    run('test/express-app', [], EXPECT);
    run('test/express-app', ['.'], EXPECT);
    run('test/express-app', ['server.js'], EXPECT);
  });

  describe('module', function() {
    var EXPECT = [
      /module-app listening/
    ];

    run('.', ['test/module-app'], EXPECT);
    run('.', ['test/module-app/.'], EXPECT);
    run('.', ['test/module-app/index.js'], EXPECT);
    run('test/module-app', [], EXPECT);
    run('test/module-app', ['.'], EXPECT);
    run('test/module-app', ['index.js'], EXPECT);
  });

  describe('argument processing', function() {
    var EXPECT = [
      /module-app listening/,
      /argv:.*index.js.*size=10/
    ];

    run('.', ['--size', 'off', 'test/module-app/index.js', '--size=10'], EXPECT);
    run('.', ['--size', '1', 'test/module-app/index.js', '--size=10'], EXPECT);

    run('.', ['--help', 'help-option'], [/usage: slr/]);
    run('.', ['-h', 'h-option'], [/usage: slr/]);

    var VERSION = RegExp('v'+require('../package.json').version);

    run('.', ['--version', 'version-option'], [VERSION]);
    run('.', ['-v', 'v-option'], [VERSION]);
  });
});
<|endoftext|>


<commit_before>import test from 'ava';
import {readFileSync, writeFileSync} from 'fs';
import {resolve} from 'path';
import {convert, convertAll} from '../lib/svg-symbol';

test('logo.2-symbol.svg', t => {
  const original = readFileSync(resolve(__dirname, 'fixtures', 'logo.original.svg'), 'utf8');
  const expected = readFileSync(resolve(__dirname, 'fixtures', t.title), 'utf8');
  return convert(original, {codeIndent: '    '})
    .then(actual =>  t.is(actual, expected));
})
test('logo.4-symbol.svg', t => {
  const original = readFileSync(resolve(__dirname, 'fixtures', 'logo.original.svg'), 'utf8');
  const expected = readFileSync(resolve(__dirname, 'fixtures', t.title), 'utf8');
  return convert(original, {codeIndent: '    '})
    .then(actual =>  t.is(actual, expected));
})
test('coin.2-symbol.svg', t => {
  const original = readFileSync(resolve(__dirname, 'fixtures', 'coin.original.svg'), 'utf8');
  const expected = readFileSync(resolve(__dirname, 'fixtures', t.title), 'utf8');
  return convert(original, {codeIndent: '    '})
    .then(actual =>  t.is(actual, expected));
})
test('coin.4-symbol.svg', t => {
  const original = readFileSync(resolve(__dirname, 'fixtures', 'coin.original.svg'), 'utf8');
  const expected = readFileSync(resolve(__dirname, 'fixtures', t.title), 'utf8');
  return convert(original, {codeIndent: '    '})
    .then(actual =>  t.is(actual, expected));
})
test('all.4-symbol.svg', t => {
  const original = [{
    name: 'logo.4-symbol',
    svg: readFileSync(resolve(__dirname, 'fixtures', 'logo.original.svg'), 'utf8')
  },{
    name: 'coin.4-symbol',
    svg: readFileSync(resolve(__dirname, 'fixtures', 'coin.original.svg'), 'utf8')
  }];
  const expected = readFileSync(resolve(__dirname, 'fixtures', t.title), 'utf8');
  return convertAll(original, {codeIndent: '    '})
    .then(actual =>  t.is(actual[0].code, expected));
})
test(t => {
  t.throws(() => convert(''), /codeIndent must be a string/);
  t.throws(() => convert('', {codeIndent : '😱'}), /codeIndent must be whitespace only/);
  t.throws(() => convert('', {codeIndent : '', name : 1}), /name must be a string/);
  t.throws(() => convert('', {codeIndent : '', stripStyle : 1}), /stripStyle must be a boolean/);
  t.throws(() => convert('', {codeIndent : '', compressed : 'compressed'}), /compressed must be a boolean/);
})
<commit_msg>removed unused ref<commit_after>import test from 'ava';
import {readFileSync} from 'fs';
import {resolve} from 'path';
import {convert, convertAll} from '../lib/svg-symbol';

test('logo.2-symbol.svg', t => {
  const original = readFileSync(resolve(__dirname, 'fixtures', 'logo.original.svg'), 'utf8');
  const expected = readFileSync(resolve(__dirname, 'fixtures', t.title), 'utf8');
  return convert(original, {codeIndent: '    '})
    .then(actual =>  t.is(actual, expected));
})
test('logo.4-symbol.svg', t => {
  const original = readFileSync(resolve(__dirname, 'fixtures', 'logo.original.svg'), 'utf8');
  const expected = readFileSync(resolve(__dirname, 'fixtures', t.title), 'utf8');
  return convert(original, {codeIndent: '    '})
    .then(actual =>  t.is(actual, expected));
})
test('coin.2-symbol.svg', t => {
  const original = readFileSync(resolve(__dirname, 'fixtures', 'coin.original.svg'), 'utf8');
  const expected = readFileSync(resolve(__dirname, 'fixtures', t.title), 'utf8');
  return convert(original, {codeIndent: '    '})
    .then(actual =>  t.is(actual, expected));
})
test('coin.4-symbol.svg', t => {
  const original = readFileSync(resolve(__dirname, 'fixtures', 'coin.original.svg'), 'utf8');
  const expected = readFileSync(resolve(__dirname, 'fixtures', t.title), 'utf8');
  return convert(original, {codeIndent: '    '})
    .then(actual =>  t.is(actual, expected));
})
test('all.4-symbol.svg', t => {
  const original = [{
    name: 'logo.4-symbol',
    svg: readFileSync(resolve(__dirname, 'fixtures', 'logo.original.svg'), 'utf8')
  },{
    name: 'coin.4-symbol',
    svg: readFileSync(resolve(__dirname, 'fixtures', 'coin.original.svg'), 'utf8')
  }];
  const expected = readFileSync(resolve(__dirname, 'fixtures', t.title), 'utf8');
  return convertAll(original, {codeIndent: '    '})
    .then(actual =>  t.is(actual[0].code, expected));
})
test(t => {
  t.throws(() => convert(''), /codeIndent must be a string/);
  t.throws(() => convert('', {codeIndent : '😱'}), /codeIndent must be whitespace only/);
  t.throws(() => convert('', {codeIndent : '', name : 1}), /name must be a string/);
  t.throws(() => convert('', {codeIndent : '', stripStyle : 1}), /stripStyle must be a boolean/);
  t.throws(() => convert('', {codeIndent : '', compressed : 'compressed'}), /compressed must be a boolean/);
})
<|endoftext|>


<commit_before>var dataManipulationFunction = (arg) => {}
var defineCommandToServer = () => {return "default message"}

module.exports.launch = () => {
var uuid = require('node-uuid');
var id = uuid.v4()

var data = []
var host = window.location.hostname
var frames = 0
var fps = 0

var ws
var wsPort = new WebSocket('ws://' + host + ':9000'+"/?id="+id)
console.log("Searching port at 9000")
wsPort.onmessage = function (event) {
    data = event.data
    console.log("Connection to : "+'ws://' + host +':'+data +"/?id="+id)
    ws = new WebSocket('ws://' + host +':'+data +"/?id="+id )
    ws.onmessage = function (event) {
        frames++
        dataManipulationFunction(event.data)
    }
}

var countFpsFunction = () =>
{
    setTimeout(countFpsFunction,1000)
    fps = frames
    frames = 0
}
setTimeout(countFpsFunction,1000)

var sendCommand = () =>
{
    setTimeout(sendCommand,16.667)
    ws.send( defineCommandToServer() )
}
setTimeout(sendCommand,1000)
}

var target = 'http://localhost:5000'

// using net-ping
/*var pingTest1 = () =>
{
    var ping = require ("net-ping")

    session.pingHost (target, function (error, target, sent, received) {
        var ms = received - sent
        if (error)
            console.log (target + ": " + error.toString ())
        else
            console.log (target + ": Alive (ms=" + ms + ")")
    })
}*/
// using ping-wrapper
/*var pingTest2 = () =>
{
    var Ping = require('ping-wrapper')
    Ping.configure()

    var ping = new Ping(target)

    ping.on('ping', function(data){
        console.log('Ping %s: time: %d ms', data.host, data.time)
    })

    ping.on('fail', function(data){
        console.log('Fail', data)
    })

    //ping.stop()
}*/
// using tcp-ping
var pingTest3 = () =>
{
    var port = 5000 //TODO
    var tcpp = require('tcp-ping')

    tcpp.probe(target, port, function(err, available) {
        console.log(available)
    })

    tcpp.ping({ address: target }, function(err, data) {
        console.log(data)
    })
}
// using jjg-ping
var pingTest4 = () =>
{
    var ping = require('jjg-ping')

    ping.system.ping(target, function(latency, status) {
        if (status) {
            console.log('The target is reachable (' + latency + ' ms ping).')
        }
        else {
            console.log('The target is unreachable.')
        }
    })
}
//TODO use ping ? hard to code

module.exports.dataManipulation = (f) => { dataManipulationFunction = f }
module.exports.commandToServer = (f) => { defineCommandToServer = f }
module.exports.countFps = () => { return fps }
module.exports.pingMeasurement = () => { return pingTest3() }<commit_msg>added a 5th test (still not one working though)<commit_after>var dataManipulationFunction = (arg) => {}
var defineCommandToServer = () => {return "default message"}

module.exports.launch = () => {
var uuid = require('node-uuid');
var id = uuid.v4()

var data = []
var host = window.location.hostname
var frames = 0
var fps = 0

var ws
var wsPort = new WebSocket('ws://' + host + ':9000'+"/?id="+id)
console.log("Searching port at 9000")
wsPort.onmessage = function (event) {
    data = event.data
    console.log("Connection to : "+'ws://' + host +':'+data +"/?id="+id)
    ws = new WebSocket('ws://' + host +':'+data +"/?id="+id )
    ws.onmessage = function (event) {
        frames++
        dataManipulationFunction(event.data)
    }
}

var countFpsFunction = () =>
{
    setTimeout(countFpsFunction,1000)
    fps = frames
    frames = 0
}
setTimeout(countFpsFunction,1000)

var sendCommand = () =>
{
    setTimeout(sendCommand,16.667)
    ws.send( defineCommandToServer() )
}
setTimeout(sendCommand,1000)
}

var target = 'http://localhost:5000'

// using net-ping
/*var pingTest1 = () =>
{
    var ping = require ("net-ping")

    session.pingHost (target, function (error, target, sent, received) {
        var ms = received - sent
        if (error)
            console.log (target + ": " + error.toString ())
        else
            console.log (target + ": Alive (ms=" + ms + ")")
    })
}*/
// using ping-wrapper
/*var pingTest2 = () =>
{
    var Ping = require('ping-wrapper')
    Ping.configure()

    var ping = new Ping(target)

    ping.on('ping', function(data){
        console.log('Ping %s: time: %d ms', data.host, data.time)
    })

    ping.on('fail', function(data){
        console.log('Fail', data)
    })

    //ping.stop()
}*/
// using tcp-ping : net.Socket is not a constructor...
var pingTest3 = () =>
{
    var port = 5000 //TODO
    var tcpp = require('tcp-ping')

    tcpp.probe(target, port, function(err, available) {
        console.log(available)
    })

    tcpp.ping({ address: target }, function(err, data) {
        console.log(data)
    })
}
// using jjg-ping : cannot identify operating system...
var pingTest4 = () =>
{
    var ping = require('jjg-ping')

    ping.system.ping(target, function(latency, status) {
        if (status) {
            console.log('The target is reachable (' + latency + ' ms ping).')
        }
        else {
            console.log('The target is unreachable.')
        }
    })
}
// using ping : seems to be an OS problem as well...
var pingTest5 = () =>
{
    var ping = require('ping');

    var hosts = [target];

    hosts.forEach(function (host) {
        ping.promise.probe(host)
            .then(function (res) {
                console.log(res);
            });
    });
}

module.exports.dataManipulation = (f) => { dataManipulationFunction = f }
module.exports.commandToServer = (f) => { defineCommandToServer = f }
module.exports.countFps = () => { return fps }
module.exports.pingMeasurement = () => { return pingTest5() }<|endoftext|>


<commit_before>'use strict';

function _random(max) {
    return Math.round(Math.random()*1000)%max;
}

export class Store {
    constructor() {
        this.data = [];
        this.selected = undefined;
        this.id = 1;
	}
    buildData(count = 1000) {
        const adjectives = ["pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy"];
        const colours = ["red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange"];
        const nouns = ["table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard"];
        let data = [];
        for (let i = 0; i < count; i++)
            data.push({id: this.id++, label: adjectives[_random(adjectives.length)] + " " + colours[_random(colours.length)] + " " + nouns[_random(nouns.length)] });
        return data;
    }
    updateData(mod = 10) {
        for (let i=0;i<this.data.length;i+=10) {
            this.data[i] = Object.assign({}, this.data[i], {label: this.data[i].label + ' !!!'});
        }
    }
    delete(id) {
        const idx = this.data.findIndex(d => d.id==id);
        this.data.splice(idx, 1);
    }
    run() {
        this.data = this.buildData();
        this.selected = undefined;
    }
    add() {
        this.data = this.data.concat(this.buildData(1000));
    }
    update() {
        this.updateData();
    }
    select(id) {
        this.selected = id;
    }
    runLots() {
        this.data = this.buildData(10000);
        this.selected = undefined;
    }
    clear() {
        this.data = [];
        this.selected = undefined;
    }
    swapRows() {
    	if(this.data.length > 998) {
    		var a = this.data[1];
    		this.data[1] = this.data[998];
    		this.data[998] = a;
    	}
    }
}<commit_msg>use const for a in swap rows<commit_after>'use strict';

function _random(max) {
    return Math.round(Math.random()*1000)%max;
}

export class Store {
    constructor() {
        this.data = [];
        this.selected = undefined;
        this.id = 1;
	}
    buildData(count = 1000) {
        const adjectives = ["pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy"];
        const colours = ["red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange"];
        const nouns = ["table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard"];
        let data = [];
        for (let i = 0; i < count; i++)
            data.push({id: this.id++, label: adjectives[_random(adjectives.length)] + " " + colours[_random(colours.length)] + " " + nouns[_random(nouns.length)] });
        return data;
    }
    updateData(mod = 10) {
        for (let i=0;i<this.data.length;i+=10) {
            this.data[i] = Object.assign({}, this.data[i], {label: this.data[i].label + ' !!!'});
        }
    }
    delete(id) {
        const idx = this.data.findIndex(d => d.id==id);
        this.data.splice(idx, 1);
    }
    run() {
        this.data = this.buildData();
        this.selected = undefined;
    }
    add() {
        this.data = this.data.concat(this.buildData(1000));
    }
    update() {
        this.updateData();
    }
    select(id) {
        this.selected = id;
    }
    runLots() {
        this.data = this.buildData(10000);
        this.selected = undefined;
    }
    clear() {
        this.data = [];
        this.selected = undefined;
    }
    swapRows() {
    	if(this.data.length > 998) {
    		const a = this.data[1];
    		this.data[1] = this.data[998];
    		this.data[998] = a;
    	}
    }
}<|endoftext|>