<commit_before>/* module make possible connectoin thru socket.io on a server */

(function() {
    'use strict';

    var main            = global.cloudcmd.main,
        DIR             = main.DIR,
        SRVDIR          = main.SRVDIR,

        io              = main.require('socket.io'),
        update          = main.srvrequire('update'),
        exec            = main.child_process.exec,
        Util            = main.util,
        path            = main.path,
        mainpackage     = main.mainpackage,
        equalPart       = Util.isContainStrAtBegin,
        CLOUDCMD        = mainpackage.name,
        ClientFuncs     = [],
        ClientDirs      = [],
        Clients         = [],
        INFO_LOG_LEVEL  = 2,
        ENV             = process.env,
        WIN32           = main.WIN32,
        HELP            = {
            stdout  : CLOUDCMD + ' exit     \n' +
                      CLOUDCMD + ' update   \n',
        },

        /* windows commands thet require
         * unicode charset on locales
         * different then English
         */
        Win32Commands   = ['ASSOC', 'AT', 'ATTRIB', 'BREAK', 'CACLS', 'CALL',
                            'CD', 'CHCP', 'CHDIR', 'CHKDSK', 'CHKNTFS', 'CLS',
                            'CMD', 'COLOR', 'COMP', 'COMPACT', 'CONVERT', 'COPY',
                            'DATE', 'DEL', 'DIR', 'DISKCOMP', 'DISKCOPY', 'DOSKEY',
                            'ECHO', 'ENDLOCAL', 'ERASE', 'EXIT', 'FC', 'FIND',
                            'FINDSTR', 'FOR', 'FORMAT', 'FTYPE', 'GOTO', 'GRAFTABL',
                            'HELP', 'IF', 'LABEL', 'MD', 'MKDIR', 'MODE', 'MORE',
                            'MOVE', 'PATH', 'PAUSE', 'POPD', 'PRINT', 'PROMPT',
                            'PUSHD', 'RD', 'RECOVER', 'REM', 'REN', 'RENAME',
                            'REPLACE', 'RMDIR', 'SET', 'SETLOCAL', 'SHIFT', 'SORT',
                            'START', 'SUBST', 'TIME', 'TITLE', 'TREE', 'TYPE',
                            'VER', 'VERIFY', 'VOL', 'XCOPY'];

    /**
     * function listen on servers port
     * @pServer {Object} started server object
     */
    exports.listen = function(pServer) {
        var lRet, lConnNum, lMsg, lConn_func;

        if (io) {
            io          = io.listen(pServer);
            lConnNum    = 0;

            io.set('log level', INFO_LOG_LEVEL);

            /*
             * on Win7 application is crashing,
             * when options below is used.
             *
             * https://github.com/LearnBoost/socket.io/issues/1314
             *
             */
            if (!WIN32) {
                io.enable('browser client minification');
                io.enable('browser client gzip');
                io.enable('browser client etag');
            }

            io.set('transports', [
              'websocket',
              'htmlfile',
              'xhr-polling',
              'jsonp-polling'
            ]);

            lRet = io.sockets.on('connection', function (socket) {
                var onDisconect, onConnect;

                ++lConnNum;

                if (!Clients[lConnNum]) {
                    lMsg    = log(lConnNum, 'connected\n');

                    jsonSend(socket, {
                        stdout : lMsg
                    });

                    Clients[lConnNum]   = true;
                    onConnect           = onMessage(lConnNum, socket);
                    onDisconect         = Util.retFunc(disconnect, lConnNum);

                    socket.on('message', onConnect);
                    socket.on('disconnect', function() {
                        socket.removeListener('message', onConnect);
                        socket.removeListener('disconnect', onDisconect);

                        socket = null;
                    });
                } else {
                    lMsg = log(lConnNum, ' in use. Reconnecting...');

                    jsonSend(socket, {
                        stdout: lMsg
                    });

                    socket.disconnect();
                }

            });
        }

        return lRet;
    };

    function disconnect(connNum) {
        OnMessageFuncs  [connNum]  =
        ClientFuncs     [connNum]  = null;

        log(connNum, 'disconnected');
    }

    /**
     * function gets onMessage function
     * that execute needed command
     *
     * @param pConnNum, pSocket
     */
    function onMessage(pConnNum, pSocket) {
        return function(pCommand) {
            var lMsg, lWinCommand, lExec_func, firstChar,
                connName,
                lError, lRet, lExecSymbols, isContain,
                dir, options = {};

            dir = ClientDirs[pConnNum];

            if (!dir)
                dir = ClientDirs[pConnNum] = DIR;

            connName = '#' + pConnNum + ': ';
            Util.log(connName + pCommand);

            if (equalPart(pCommand, CLOUDCMD))
                lRet = onCloudCmd(pCommand, function(json) {
                     jsonSend(pSocket, json);
                });
            else if (equalPart(pCommand, 'cd '))  {
                lRet = true;

                onCD(pCommand, dir, function(json) {
                    var error   = json.stderr,
                        stdout  = json.stdout;

                    if (error)
                        jsonSend(pSocket, json);
                    else
                        ClientDirs[pConnNum] = stdout;
                });
            }

            if (!lRet) {
                /* if we on windows and command is build in
                 * change code page to unicode becouse
                 * windows use unicode on non English versions
                 */
                if (WIN32) {
                    lWinCommand     = pCommand.toUpperCase();

                    if (Win32Commands.indexOf(lWinCommand) >= 0)
                        pCommand    = 'chcp 65001 |' + pCommand;
                }

                if (!ClientFuncs[pConnNum])
                    ClientFuncs[pConnNum] = getExec(function(json, pError, pStderr) {
                        log(pConnNum, pError, 'error');
                        log(pConnNum, pStderr, 'stderror');

                        jsonSend(pSocket, json);
                    });

                lExec_func      = ClientFuncs[pConnNum];
                lExecSymbols    = ['*', '&', '{', '}', '|', '\'', '"'];
                isContain       = Util.isContainStr(pCommand, lExecSymbols);
                firstChar       = pCommand[0];
                options.cwd     = dir;

                if (firstChar === '#') {
                    pCommand    = pCommand.slice(1);
                    pCommand    = connName + pCommand;
                    pCommand    = Util.addNewLine(pCommand);

                    lMsg    = Util.stringifyJSON({
                        stdout: pCommand
                    });

                    io.sockets.emit('message', lMsg);
                } else if (WIN32 || firstChar === ' ' || isContain)
                    exec(pCommand, options, lExec_func);
                else
                    getSpawn(pCommand, options, function(json) {
                        jsonSend(pSocket, json);
                    });
            }
        };
    }

    /**
     * function send result of command to client
     * @param pSocket
     */
    function getExec(callback) {
        return function(pError, pStdout, pStderr) {
            var lErrorStr, lExecStr, lExec,
                lError          = pStderr || pError;

            if (lError) {
                if (Util.isString(lError))
                    lErrorStr   = lError;
                else
                    lErrorStr   = lError.toString();

                lErrorStr = Util.addNewLine(lErrorStr);
            }

            lExec               = {
                stdout : pStdout,
                stderr : lErrorStr || lError
            };

            Util.exec(callback, lExec, pError, pStderr);
        };
    }

    function getSpawn(pCommand, options, callback) {
        var send, cmd, spawn,
            args    = pCommand.split(' ');

        pCommand    = args.shift();

        spawn       = main.child_process.spawn;
        Util.tryCatchLog(function() {
            cmd         = spawn(pCommand, args, options);
        });

        if (cmd) {
            send        = function(data, isError) {
                var lExec               = {},
                    msg                 = data.toString();

                if (isError)
                    lExec.stderr    = msg;
                else
                    lExec.stdout    = msg;

                Util.exec(callback, lExec);
            };

            cmd.stdout.on('data', send);

            cmd.stderr.on('data', function(data) {
                send(data, true);
            });

            cmd.on('error', Util.retFalse);
            cmd.on('close', function (code) {
                cmd = null;
            });
        }
    }

    function onCloudCmd(pCommand, callback) {
        var lRet;

        pCommand = Util.removeStr(pCommand, CLOUDCMD);

        if (!equalPart(pCommand, ' ')) {
            lRet = true;
            Util.exec(callback, HELP);
        }
        else {
            pCommand = Util.removeStr(pCommand, ' ');

            if (equalPart(pCommand, 'update') && update) {
                lRet = true;
                update.get();

                Util.exec(callback, {
                    stdout: Util.addNewLine('update: ok')
                });
            }

            if (Util.strCmp(pCommand, 'exit'))
                process.exit();
        }

        return lRet;
    }

    function onCD(pCommand, currDir, callback) {
        var dir,
            getDir      = WIN32 ? 'chdir' : 'pwd',
            paramDir    = Util.removeStr(pCommand, 'cd ');

        if (equalPart(paramDir, ['/', '~']))
            dir = paramDir;
        else
            dir = path.join(currDir, paramDir);

        exec('cd ' + dir + ' && ' + getDir, function (error, stdout, stderr) {
            var lRet,
                lMsg    = '',
                lError = error || stderr;

            if (lError) {
                lError  = Util.stringifyJSON(lError);
                lMsg    = lError;
            }

            Util.exec(callback, {
                stderr  : lMsg,
                stdout  : Util.rmNewLine(stdout)
            });
        });
    }

    function log(pConnNum, pStr, pType) {
        var lRet,
            lType       = ' ';

        if (pStr) {

            if (pType)
                lType  += pType + ':';

            lRet        = 'client #' + pConnNum + lType + pStr;

            Util.log(lRet);
        }

        return lRet;
    }

    function jsonSend(socket, json) {
        var msg = Util.stringifyJSON(json);
        socket.send(msg);
    }
})();
<commit_msg>chore(socket) rm lConn_func<commit_after>/* module make possible connectoin thru socket.io on a server */

(function() {
    'use strict';

    var main            = global.cloudcmd.main,
        DIR             = main.DIR,
        SRVDIR          = main.SRVDIR,

        io              = main.require('socket.io'),
        update          = main.srvrequire('update'),
        exec            = main.child_process.exec,
        Util            = main.util,
        path            = main.path,
        mainpackage     = main.mainpackage,
        equalPart       = Util.isContainStrAtBegin,
        CLOUDCMD        = mainpackage.name,
        ClientFuncs     = [],
        ClientDirs      = [],
        Clients         = [],
        INFO_LOG_LEVEL  = 2,
        ENV             = process.env,
        WIN32           = main.WIN32,
        HELP            = {
            stdout  : CLOUDCMD + ' exit     \n' +
                      CLOUDCMD + ' update   \n',
        },

        /* windows commands thet require
         * unicode charset on locales
         * different then English
         */
        Win32Commands   = ['ASSOC', 'AT', 'ATTRIB', 'BREAK', 'CACLS', 'CALL',
                            'CD', 'CHCP', 'CHDIR', 'CHKDSK', 'CHKNTFS', 'CLS',
                            'CMD', 'COLOR', 'COMP', 'COMPACT', 'CONVERT', 'COPY',
                            'DATE', 'DEL', 'DIR', 'DISKCOMP', 'DISKCOPY', 'DOSKEY',
                            'ECHO', 'ENDLOCAL', 'ERASE', 'EXIT', 'FC', 'FIND',
                            'FINDSTR', 'FOR', 'FORMAT', 'FTYPE', 'GOTO', 'GRAFTABL',
                            'HELP', 'IF', 'LABEL', 'MD', 'MKDIR', 'MODE', 'MORE',
                            'MOVE', 'PATH', 'PAUSE', 'POPD', 'PRINT', 'PROMPT',
                            'PUSHD', 'RD', 'RECOVER', 'REM', 'REN', 'RENAME',
                            'REPLACE', 'RMDIR', 'SET', 'SETLOCAL', 'SHIFT', 'SORT',
                            'START', 'SUBST', 'TIME', 'TITLE', 'TREE', 'TYPE',
                            'VER', 'VERIFY', 'VOL', 'XCOPY'];

    /**
     * function listen on servers port
     * @pServer {Object} started server object
     */
    exports.listen = function(pServer) {
        var lRet, lConnNum, lMsg;

        if (io) {
            io          = io.listen(pServer);
            lConnNum    = 0;

            io.set('log level', INFO_LOG_LEVEL);

            /*
             * on Win7 application is crashing,
             * when options below is used.
             *
             * https://github.com/LearnBoost/socket.io/issues/1314
             *
             */
            if (!WIN32) {
                io.enable('browser client minification');
                io.enable('browser client gzip');
                io.enable('browser client etag');
            }

            io.set('transports', [
              'websocket',
              'htmlfile',
              'xhr-polling',
              'jsonp-polling'
            ]);

            lRet = io.sockets.on('connection', function (socket) {
                var onDisconect, onConnect;

                ++lConnNum;

                if (!Clients[lConnNum]) {
                    lMsg    = log(lConnNum, 'connected\n');

                    jsonSend(socket, {
                        stdout : lMsg
                    });

                    Clients[lConnNum]   = true;
                    onConnect           = onMessage(lConnNum, socket);
                    onDisconect         = Util.retFunc(disconnect, lConnNum);

                    socket.on('message', onConnect);
                    socket.on('disconnect', function() {
                        socket.removeListener('message', onConnect);
                        socket.removeListener('disconnect', onDisconect);

                        socket = null;
                    });
                } else {
                    lMsg = log(lConnNum, ' in use. Reconnecting...');

                    jsonSend(socket, {
                        stdout: lMsg
                    });

                    socket.disconnect();
                }

            });
        }

        return lRet;
    };

    function disconnect(connNum) {
        OnMessageFuncs  [connNum]  =
        ClientFuncs     [connNum]  = null;

        log(connNum, 'disconnected');
    }

    /**
     * function gets onMessage function
     * that execute needed command
     *
     * @param pConnNum, pSocket
     */
    function onMessage(pConnNum, pSocket) {
        return function(pCommand) {
            var lMsg, lWinCommand, lExec_func, firstChar,
                connName,
                lError, lRet, lExecSymbols, isContain,
                dir, options = {};

            dir = ClientDirs[pConnNum];

            if (!dir)
                dir = ClientDirs[pConnNum] = DIR;

            connName = '#' + pConnNum + ': ';
            Util.log(connName + pCommand);

            if (equalPart(pCommand, CLOUDCMD))
                lRet = onCloudCmd(pCommand, function(json) {
                     jsonSend(pSocket, json);
                });
            else if (equalPart(pCommand, 'cd '))  {
                lRet = true;

                onCD(pCommand, dir, function(json) {
                    var error   = json.stderr,
                        stdout  = json.stdout;

                    if (error)
                        jsonSend(pSocket, json);
                    else
                        ClientDirs[pConnNum] = stdout;
                });
            }

            if (!lRet) {
                /* if we on windows and command is build in
                 * change code page to unicode becouse
                 * windows use unicode on non English versions
                 */
                if (WIN32) {
                    lWinCommand     = pCommand.toUpperCase();

                    if (Win32Commands.indexOf(lWinCommand) >= 0)
                        pCommand    = 'chcp 65001 |' + pCommand;
                }

                if (!ClientFuncs[pConnNum])
                    ClientFuncs[pConnNum] = getExec(function(json, pError, pStderr) {
                        log(pConnNum, pError, 'error');
                        log(pConnNum, pStderr, 'stderror');

                        jsonSend(pSocket, json);
                    });

                lExec_func      = ClientFuncs[pConnNum];
                lExecSymbols    = ['*', '&', '{', '}', '|', '\'', '"'];
                isContain       = Util.isContainStr(pCommand, lExecSymbols);
                firstChar       = pCommand[0];
                options.cwd     = dir;

                if (firstChar === '#') {
                    pCommand    = pCommand.slice(1);
                    pCommand    = connName + pCommand;
                    pCommand    = Util.addNewLine(pCommand);

                    lMsg    = Util.stringifyJSON({
                        stdout: pCommand
                    });

                    io.sockets.emit('message', lMsg);
                } else if (WIN32 || firstChar === ' ' || isContain)
                    exec(pCommand, options, lExec_func);
                else
                    getSpawn(pCommand, options, function(json) {
                        jsonSend(pSocket, json);
                    });
            }
        };
    }

    /**
     * function send result of command to client
     * @param pSocket
     */
    function getExec(callback) {
        return function(pError, pStdout, pStderr) {
            var lErrorStr, lExecStr, lExec,
                lError          = pStderr || pError;

            if (lError) {
                if (Util.isString(lError))
                    lErrorStr   = lError;
                else
                    lErrorStr   = lError.toString();

                lErrorStr = Util.addNewLine(lErrorStr);
            }

            lExec               = {
                stdout : pStdout,
                stderr : lErrorStr || lError
            };

            Util.exec(callback, lExec, pError, pStderr);
        };
    }

    function getSpawn(pCommand, options, callback) {
        var send, cmd, spawn,
            args    = pCommand.split(' ');

        pCommand    = args.shift();

        spawn       = main.child_process.spawn;
        Util.tryCatchLog(function() {
            cmd         = spawn(pCommand, args, options);
        });

        if (cmd) {
            send        = function(data, isError) {
                var lExec               = {},
                    msg                 = data.toString();

                if (isError)
                    lExec.stderr    = msg;
                else
                    lExec.stdout    = msg;

                Util.exec(callback, lExec);
            };

            cmd.stdout.on('data', send);

            cmd.stderr.on('data', function(data) {
                send(data, true);
            });

            cmd.on('error', Util.retFalse);
            cmd.on('close', function (code) {
                cmd = null;
            });
        }
    }

    function onCloudCmd(pCommand, callback) {
        var lRet;

        pCommand = Util.removeStr(pCommand, CLOUDCMD);

        if (!equalPart(pCommand, ' ')) {
            lRet = true;
            Util.exec(callback, HELP);
        }
        else {
            pCommand = Util.removeStr(pCommand, ' ');

            if (equalPart(pCommand, 'update') && update) {
                lRet = true;
                update.get();

                Util.exec(callback, {
                    stdout: Util.addNewLine('update: ok')
                });
            }

            if (Util.strCmp(pCommand, 'exit'))
                process.exit();
        }

        return lRet;
    }

    function onCD(pCommand, currDir, callback) {
        var dir,
            getDir      = WIN32 ? 'chdir' : 'pwd',
            paramDir    = Util.removeStr(pCommand, 'cd ');

        if (equalPart(paramDir, ['/', '~']))
            dir = paramDir;
        else
            dir = path.join(currDir, paramDir);

        exec('cd ' + dir + ' && ' + getDir, function (error, stdout, stderr) {
            var lRet,
                lMsg    = '',
                lError = error || stderr;

            if (lError) {
                lError  = Util.stringifyJSON(lError);
                lMsg    = lError;
            }

            Util.exec(callback, {
                stderr  : lMsg,
                stdout  : Util.rmNewLine(stdout)
            });
        });
    }

    function log(pConnNum, pStr, pType) {
        var lRet,
            lType       = ' ';

        if (pStr) {

            if (pType)
                lType  += pType + ':';

            lRet        = 'client #' + pConnNum + lType + pStr;

            Util.log(lRet);
        }

        return lRet;
    }

    function jsonSend(socket, json) {
        var msg = Util.stringifyJSON(json);
        socket.send(msg);
    }
})();
<|endoftext|>


<commit_before>import {React, Component, PropTypes} from '../imports';

/**
 * This component renders a tab menu and provides the selected tab via a value property.
 * @property {Array} items List of menu items {value: any & required, label: string, className: string, badge: string}
 * @property {*} value Matching a value of an item
 * @property {Function} onChange Callback function for React/Preact applications
 */
export class WSTabMenu extends Component {

  static propTypes = {
    items: PropTypes.array,
    value: PropTypes.any,
    onChange: PropTypes.func
  };

  static defaultProps = {
    items: [],
    value: null,
    onChange: null
  };

  /**
   * @param {Object} props React component properties
   */
  constructor(props) {
    super(props);

    this.state = this.createState(props);
    this.menuItems = [];
  }

  componentDidMount() {
    this.configureMenuItems();
  }

  componentDidUpdate() {
    this.configureMenuItems();
  }

  /**
   * Bind listeners and move dash below active item
   * @returns {void}
   */
  configureMenuItems() {
    this.menuItems.forEach((element, index) => {
      const item = this.props.items[index];
      // Move dash below selected item
      if (item.value === this.state.value) {
        this.animateDash(element);
      }
      element.addEventListener('click', this.onClick);
    });
  }

  /**
   * Update state from property change
   * @param {Object} props React properties
   * @returns {void}
   */
  componentWillReceiveProps(props) {
    this.setState(this.createState(props));
    // If the value changed we have to move the dash
    const index = this.props.items.findIndex(item => item.value === this.state.value) || 0;
    this.animateDash(this.menuItems[index]);
  }

  /**
   * Unbind event listeners
   * @returns {void}
   */
  componentWillUnmount() {
    this.menuItems.forEach(element =>
      element.removeEventListener('click', this.onClick)
    );
  }

  /**
   * Handles clicks on menu items
   * @param {Event} event JavaScript event object
   * @returns {void}
   */
  onClick = event => {
    event.stopPropagation();
    const selectedIndex = this.menuItems.indexOf(event.currentTarget);
    const selectedItem = this.props.items[selectedIndex];

    if (selectedItem.disabled) {
      return;
    }
    if (selectedItem.value === this.state.value) {
      return;
    }

    this.setState({value: selectedItem.value});
    // Animate dash to sit below active item
    this.animateDash(event.currentTarget);
    // Propagate change
    this.dispatchEvent('change', selectedItem.value);
    if (typeof this.props.onChange === 'function') {
      this.props.onChange(selectedItem.value);
    }
  };

  /**
   * Animate the dash below the new active item
   * @param {Element} newMenuItem HTMLElement of new active menu item
   * @returns {void}
   */
  animateDash(newMenuItem) {
    this.dash.style.left = `${newMenuItem.offsetLeft}px`;
    this.dash.style.right = `${newMenuItem.parentNode.offsetWidth - newMenuItem.offsetLeft - newMenuItem.offsetWidth}px`;
  }

  /**
   * Create a state object from the properties
   * @param {Object} props React properties
   * @returns {Object}
   * @throws Error when no items are passed
   */
  createState(props) {
    if (!props.items.length) {
      throw new Error(`WSTabMenu has no items specified: ${JSON.stringify(props)}`);
    }
    if (props.value) {
      return {value: props.value};
    }
    return {value: props.items[0].value};
  }

  /**
   * Render a single menu item
   * @param {Object} item Menu item object
   * @param {number} index Index of item in item list
   * @returns {XML}
   */
  renderMenuItem(item, index) {
    let className = `tab-item ${item.className || ''}`;
    if (item.value === this.state.value) {
      className += ' is-active';
    } else if (item.disabled) {
      className += ' is-disabled';
    }

    return (

 { this.menuItems[index] = element; }} key={`item-${index}`}>
        {item.label || item.value}
        {item.badge !== undefined &&
          {item.badge}
        }

    );
  }

  /**
   * Render the component markup
   * @returns {XML}
   */
  render() {
    return (

 { this.element = element; }}>

          {this.props.items.map((item, index) =>
            this.renderMenuItem(item, index)
          )}

 { this.dash = element; }} />

    );
  }
}
<commit_msg>fix JSDoc<commit_after>import {React, Component, PropTypes} from '../imports';

/**
 * This component renders a tab menu and provides the selected tab via a value property.
 * @property {Array} items List of menu items {value: any & required, label: string, className: string, badge: string}
 * @property {*} value Matching a value of an item
 * @property {Function} onChange Callback function for React/Preact applications
 */
export class WSTabMenu extends Component {

  static propTypes = {
    items: PropTypes.array,
    value: PropTypes.any,
    onChange: PropTypes.func
  };

  static defaultProps = {
    items: [],
    value: null,
    onChange: null
  };

  /**
   * @param {Object} props React component properties
   */
  constructor(props) {
    super(props);

    this.state = this.createState(props);
    this.menuItems = [];
  }

  /**
   * Bind listeners after mount
   */
  componentDidMount() {
    this.configureMenuItems();
  }

  /**
   * Bind listeners after update
   */
  componentDidUpdate() {
    this.configureMenuItems();
  }

  /**
   * Bind listeners and move dash below active item
   * @returns {void}
   */
  configureMenuItems() {
    this.menuItems.forEach((element, index) => {
      const item = this.props.items[index];
      // Move dash below selected item
      if (item.value === this.state.value) {
        this.animateDash(element);
      }
      element.addEventListener('click', this.onClick);
    });
  }

  /**
   * Update state from property change
   * @param {Object} props React properties
   * @returns {void}
   */
  componentWillReceiveProps(props) {
    this.setState(this.createState(props));
    // If the value changed we have to move the dash
    const index = this.props.items.findIndex(item => item.value === this.state.value) || 0;
    this.animateDash(this.menuItems[index]);
  }

  /**
   * Unbind event listeners
   * @returns {void}
   */
  componentWillUnmount() {
    this.menuItems.forEach(element =>
      element.removeEventListener('click', this.onClick)
    );
  }

  /**
   * Handles clicks on menu items
   * @param {Event} event JavaScript event object
   * @returns {void}
   */
  onClick = event => {
    event.stopPropagation();
    const selectedIndex = this.menuItems.indexOf(event.currentTarget);
    const selectedItem = this.props.items[selectedIndex];

    if (selectedItem.disabled) {
      return;
    }
    if (selectedItem.value === this.state.value) {
      return;
    }

    this.setState({value: selectedItem.value});
    // Animate dash to sit below active item
    this.animateDash(event.currentTarget);
    // Propagate change
    this.dispatchEvent('change', selectedItem.value);
    if (typeof this.props.onChange === 'function') {
      this.props.onChange(selectedItem.value);
    }
  };

  /**
   * Animate the dash below the new active item
   * @param {Element} newMenuItem HTMLElement of new active menu item
   * @returns {void}
   */
  animateDash(newMenuItem) {
    this.dash.style.left = `${newMenuItem.offsetLeft}px`;
    this.dash.style.right = `${newMenuItem.parentNode.offsetWidth - newMenuItem.offsetLeft - newMenuItem.offsetWidth}px`;
  }

  /**
   * Create a state object from the properties
   * @param {Object} props React properties
   * @returns {Object}
   * @throws Error when no items are passed
   */
  createState(props) {
    if (!props.items.length) {
      throw new Error(`WSTabMenu has no items specified: ${JSON.stringify(props)}`);
    }
    if (props.value) {
      return {value: props.value};
    }
    return {value: props.items[0].value};
  }

  /**
   * Render a single menu item
   * @param {Object} item Menu item object
   * @param {number} index Index of item in item list
   * @returns {XML}
   */
  renderMenuItem(item, index) {
    let className = `tab-item ${item.className || ''}`;
    if (item.value === this.state.value) {
      className += ' is-active';
    } else if (item.disabled) {
      className += ' is-disabled';
    }

    return (

 { this.menuItems[index] = element; }} key={`item-${index}`}>
        {item.label || item.value}
        {item.badge !== undefined &&
          {item.badge}
        }

    );
  }

  /**
   * Render the component markup
   * @returns {XML}
   */
  render() {
    return (

 { this.element = element; }}>

          {this.props.items.map((item, index) =>
            this.renderMenuItem(item, index)
          )}

 { this.dash = element; }} />

    );
  }
}
<|endoftext|>


<commit_before>var passport        = require('passport');
var WindowsStrategy = require('passport-windowsauth');
var SslCertStrategy = require('passport-ssl-certificate');
var nconf           = require('nconf');
var profileMapper   = require('./profileMapper');

if (nconf.get('LDAP_URL')) {

  var Users           = require('./users');
  var users           = new Users();

  function finish(preprofile, done) {
    if (!preprofile) return done();

    var profile = profileMapper(preprofile._json);

    users.getAllGroups(preprofile._json, function (err, groups) {
      if (err) {
        return done(null, profile);
      }

      profile.groups = groups.map(function (g) {
        return g.cn;
      });

      return done(null, profile);
    });
  }

  passport.use('IISIntegrated', new WindowsStrategy({
    ldap: {
      url:             nconf.get("LDAP_URL"),
      base:            nconf.get("LDAP_BASE"),
      bindDN:          nconf.get("LDAP_BIND_USER"),
      bindCredentials: nconf.get("LDAP_BIND_PASSWORD")
    }
  }, finish));

  passport.use('ApacheKerberos', new WindowsStrategy({
    ldap: {
      url:             nconf.get("LDAP_URL"),
      base:            nconf.get("LDAP_BASE"),
      bindDN:          nconf.get("LDAP_BIND_USER"),
      bindCredentials: nconf.get("LDAP_BIND_PASSWORD")
    },
    getUserNameFromHeader: function (req) {
      var forwarded_user = req.headers['x-forwarded-user'];

      if (!forwarded_user || forwarded_user === '(null)'){
        return null;
      }

      if (~forwarded_user.indexOf('@')) {
        return forwarded_user.split('@')[0];
      } else if (~forwarded_user.indexOf('\\')) {
        return forwarded_user.split('\\')[1];
      }

      return forwarded_user;
    }
  }, finish));

  passport.use('WindowsAuthentication', new WindowsStrategy({
    ldap: {
      url:             nconf.get("LDAP_URL"),
      base:            nconf.get("LDAP_BASE"),
      bindDN:          nconf.get("LDAP_BIND_USER"),
      bindCredentials: nconf.get("LDAP_BIND_PASSWORD")
    },
    integrated:      false
  }, finish));

  passport.use('ClientCertAuthentication', new SslCertStrategy({passReqToCallback: true}, function (req, cert, done) {
    req.session.cert = cert;

    if (!cert.subject) {
      return done(new Error('Specified certificate does not contain subject attribute'));
    }

    // get user by certificate subject
    users.getByUserName(cert.subject.CN, function (err, rawProfile) {
      if (err) { return done(err); }
      finish({_json: rawProfile}, done);
    });
  }));

} else {
  //LDAP connectivity is not yet setup, use a fake user.
  var LocalStrategy = require('passport-local').Strategy;
  passport.use('WindowsAuthentication', new LocalStrategy(function (username, password, done) {
    if (username === 'test' && password === '123') {
      return done(null, {
                          id:           123,
                          username:     'test',
                          displayName:  'test user',
                          name: {
                            familyName: 'user',
                            givenName:  'test'
                          },
                          emails:   [ { value: 'foo@bar.com'} ]
                        });
    }
    done(null, false);
  }));

}

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});
<commit_msg>log for cert.subject.CN<commit_after>var passport        = require('passport');
var WindowsStrategy = require('passport-windowsauth');
var SslCertStrategy = require('passport-ssl-certificate');
var nconf           = require('nconf');
var profileMapper   = require('./profileMapper');

if (nconf.get('LDAP_URL')) {

  var Users           = require('./users');
  var users           = new Users();

  function finish(preprofile, done) {
    if (!preprofile) return done();

    var profile = profileMapper(preprofile._json);

    users.getAllGroups(preprofile._json, function (err, groups) {
      if (err) {
        return done(null, profile);
      }

      profile.groups = groups.map(function (g) {
        return g.cn;
      });

      return done(null, profile);
    });
  }

  passport.use('IISIntegrated', new WindowsStrategy({
    ldap: {
      url:             nconf.get("LDAP_URL"),
      base:            nconf.get("LDAP_BASE"),
      bindDN:          nconf.get("LDAP_BIND_USER"),
      bindCredentials: nconf.get("LDAP_BIND_PASSWORD")
    }
  }, finish));

  passport.use('ApacheKerberos', new WindowsStrategy({
    ldap: {
      url:             nconf.get("LDAP_URL"),
      base:            nconf.get("LDAP_BASE"),
      bindDN:          nconf.get("LDAP_BIND_USER"),
      bindCredentials: nconf.get("LDAP_BIND_PASSWORD")
    },
    getUserNameFromHeader: function (req) {
      var forwarded_user = req.headers['x-forwarded-user'];

      if (!forwarded_user || forwarded_user === '(null)'){
        return null;
      }

      if (~forwarded_user.indexOf('@')) {
        return forwarded_user.split('@')[0];
      } else if (~forwarded_user.indexOf('\\')) {
        return forwarded_user.split('\\')[1];
      }

      return forwarded_user;
    }
  }, finish));

  passport.use('WindowsAuthentication', new WindowsStrategy({
    ldap: {
      url:             nconf.get("LDAP_URL"),
      base:            nconf.get("LDAP_BASE"),
      bindDN:          nconf.get("LDAP_BIND_USER"),
      bindCredentials: nconf.get("LDAP_BIND_PASSWORD")
    },
    integrated:      false
  }, finish));

  passport.use('ClientCertAuthentication', new SslCertStrategy({passReqToCallback: true}, function (req, cert, done) {
    req.session.cert = cert;

    if (!cert.subject) {
      return done(new Error('Specified certificate does not contain subject attribute'));
    }

    console.log('Authenticating user from certificate with subject.CN: ' + cert.subject.CN);

    // get user by certificate subject
    users.getByUserName(cert.subject.CN, function (err, rawProfile) {
      if (err) { return done(err); }
      finish({_json: rawProfile}, done);
    });
  }));

} else {
  //LDAP connectivity is not yet setup, use a fake user.
  var LocalStrategy = require('passport-local').Strategy;
  passport.use('WindowsAuthentication', new LocalStrategy(function (username, password, done) {
    if (username === 'test' && password === '123') {
      return done(null, {
                          id:           123,
                          username:     'test',
                          displayName:  'test user',
                          name: {
                            familyName: 'user',
                            givenName:  'test'
                          },
                          emails:   [ { value: 'foo@bar.com'} ]
                        });
    }
    done(null, false);
  }));

}

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});
<|endoftext|>


<commit_before>function Shortener(backendId, useAcct, login, apiKey, serviceUrl) {
  if(!backendId) {
    backendId = 'bitly';
  }
  this.useAcct = useAcct;
  if(useAcct || backendId == 'yourls') {
    this.login = login;
    this.apiKey = apiKey;
  }
  this.serviceUrl = serviceUrl;
  this.shortenerInfo = SHORTENERS_BACKEND[backendId];
}
Shortener.prototype = {
  shorten: function(longUrl, callback) {
    var _this = this;
      this.shortenerInfo.backend.shorten(longUrl, this.useAcct, this.login, this.apiKey, this.serviceUrl,
        function(errorCode, msg) {
      var cbMsg = null;
      var success = true;
      if(errorCode == 0 && msg) {
        cbMsg = _this.shortenerInfo.baseUrl + msg;
      } else if(errorCode != 0 && msg) {
        cbMsg = 'Error ' + errorCode + ': ' + msg;
        success = false;
      } else {
        cbMsg = 'Unknown Error';
        success = false;
      }
      callback(success, cbMsg);
    });
  }
}

BitLyShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://api.bit.ly/shorten";
    var params = {
      version: '2.0.1',
      format: 'json',
      longUrl: longUrl
    }
    if(useAcct) {
      params['login'] = login;
      params['apiKey'] = apiKey;
      params['history'] = 1;
    } else {
      params['login'] = 'chromedbird';
      params['apiKey'] = 'R_aa77c64a8258cf704e7fa361555a4d81';
    }

    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'json',
      success: function(data, status) {
        var ecAPI = data.errorCode;
        if(ecAPI == 0) {
          var ecURL = data.results[longUrl].errorCode;
          if(!ecURL || ecURL==0) {
            callback(0, data.results[longUrl].userHash);
          } else {
            callback(ecURL, data.results[longUrl].errorMessage);
          }
        } else {
          callback(ecAPI, data.errorMessage);
        }
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

TrimShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://api.tr.im/v1/trim_url.json";
    var params = {
      url: longUrl
    }
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'json',
      success: function(data, status) {
        if(data.status.result != 'OK') {
          callback(data.status.code, data.status.message);
          return;
        }
        callback(0, data.trimpath);
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

MigremeShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://migre.me/api.xml";
    var params = {
      url: longUrl
    }
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'xml',
      success: function(data, status) {
        var errorId = $('error', data).text();
        if(errorId != 0) {
          callback(errorId, $('errormessage', data).text());
          return;
        }
        callback(0, $('id', data).text());
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

IsGdShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://is.gd/api.php";
    var params = {
      longurl: longUrl
    }
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'text',
      success: function(data, status) {
        if(data.match(/^ERROR/i)) {
          callback(-1, data);
          return;
        }
        callback(0, data);
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

MiudinShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://miud.in/api-create.php";
    var params = {
      url: longUrl
    }
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'text',
      success: function(data, status) {
        callback(0, data);
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

UdanaxShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://udanax.org/shorturl.jsp";
    var params = {
      mode: 'api',
      longurl: longUrl
    };
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      jsonp: 'jsoncallback',
      dataType: 'jsonp',
      success: function(data, status) {
        callback(0, data.shorturl);
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

URLinlShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://urli.nl/api.php";
    var params = {
      format: 'json',
      action: 'shorturl',
      url: longUrl
    };
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'json',
      success: function(data, status) {
        if(data && data.status && data.status == 'success') {
          callback(0, data.url.keyword);
        } else {
          callback(data.statusCode, data.message);
        }
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

URLcortaShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://urlcorta.es/api/text/";
    var params = {
      url: longUrl
    }
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'text',
      success: function(data, status) {
        callback(0, data);
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

GooglShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var authFunc = function(f){function k(){for(var c=0,b=0;b<arguments.length;b++)c=c+arguments[b]&4294967295;return c}function m(c){c=c=String(c>0?c:c+4294967296);var b;b=c;for(var d=0,i=false,j=b.length-1;j>=0;--j){var g=Number(b.charAt(j));if(i){g*=2;d+=Math.floor(g/10)+g%10}else d+=g;i=!i}b=b=d%10;d=0;if(b!=0){d=10-b;if(c.length%2==1){if(d%2==1)d+=9;d/=2}}b=String(d);b+=c;return b}function n(c){for(var b=5381,d=0;d<c.length;d++)b=k(b<<5,b,c.charCodeAt(d));return b}function o(c){for(var b=0,d=0;d<c.length;d++)b=k(c.charCodeAt(d),b<<6,b<<16,-b);return b}f={byteArray_:f,charCodeAt:function(c){return this.byteArray_[c]}};f.length=f.byteArray_.length;var e=n(f.byteArray_);e=e>>2&1073741823;e=e>>4&67108800|e&63;e=e>>4&4193280|e&1023;e=e>>4&245760|e&16383;var l="7";f=o(f.byteArray_);var h=(e>>2&15)<<4|f&15;h|=(e>>6&15)<<12|(f>>8&15)<<8;h|=(e>>10&15)<<20|(f>>16&15)<<16;h|=(e>>14&15)<<28|(f>>24&15)<<24;l+=m(h);return l};
    var url = 'http://goo.gl/api/url';
    var params = {
      user: 'toolbar@google.com',
      url: longUrl,
      auth_token: authFunc(longUrl)
    };
    $.ajax({
      url: url,
      type: 'post',
      data: params,
      dataType: 'json',
      success: function(data, status) {
        callback(0, data.short_url);
      },
      error: function (request, status, error) {
        var errMsg;
        try {
          var rspObj = JSON.parse(request.responseText);
          errMsg = rspObj.error_message;
        } catch(e) {
          errMsg = chrome.i18n.getMessage("ajaxFailed");
        }
        callback(-1, errMsg);
      }
    });
  }
}

KCYShortener = {
  shorten : function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = 'http://kcy.me/api/';
    var params = {
      url: longUrl,
      u: login,
      key: apiKey
    };
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'text',
      success: function(data, status) {
        var errorCode = -1;
        if(data.match(/^http/i)) {
          errorCode = 0;
        }
        callback(errorCode, data);
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

YourlsShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var params = {
      signature: apiKey,
      action:  'shorturl',
      format: 'json',
      url: longUrl,
    };

    $.ajax({
      type: 'GET',
      url: serviceUrl,
      data: params,
      dataType: 'json',
      success: function(data, status) {
        if(data && data.status && data.shorturl) {
          callback(0, data.shorturl);
        } else {
          callback(-1, data.message);
        }
      },
      error: function (request, status, error) {
        callback(-1,'AJAX request failed (bad connection?)');
      }
    });
  }
}

SHORTENERS_BACKEND = {
  bitly: {
    desc: 'bit.ly',
    baseUrl: 'http://bit.ly/',
    backend: BitLyShortener
  },
  jmp: {
    desc: 'j.mp',
    baseUrl: 'http://j.mp/',
    backend: BitLyShortener
  },
  trim: {
    desc: 'tr.im',
    baseUrl: 'http://tr.im/',
    backend: TrimShortener
  },
  isgd: {
    desc: 'is.gd',
    baseUrl: '',
    backend: IsGdShortener
  },
  migreme: {
    desc: 'migre.me',
    baseUrl: 'http://migre.me/',
    backend: MigremeShortener
  },
  miudin: {
    desc: 'miud.in',
    baseUrl: '',
    backend: MiudinShortener
  },
  udanax: {
    desc: 'udanax.org',
    baseUrl: 'http://udanax.org/',
    backend: UdanaxShortener
  },
  urlinl: {
    desc: 'URLi.nl',
    baseUrl: 'http://urli.nl/',
    backend: URLinlShortener
  },
  urlcorta: {
    desc: 'URLcorta.es',
    baseUrl: '',
    backend: URLcortaShortener
  },
  googl: {
    desc: 'goo.gl',
    baseUrl: '',
    backend: GooglShortener
  },
  karmacracy: {
    desc: 'karmacracy.com',
    baseUrl: '',
    backend: KCYShortener
  },
  yourls: {
    desc: 'yourls',
    baseUrl: '',
    backend: YourlsShortener
  }
}
<commit_msg>Adding mcaf.ee shortener.<commit_after>function Shortener(backendId, useAcct, login, apiKey, serviceUrl) {
  if(!backendId) {
    backendId = 'bitly';
  }
  this.useAcct = useAcct;
  if(useAcct || backendId == 'yourls') {
    this.login = login;
    this.apiKey = apiKey;
  }
  this.serviceUrl = serviceUrl;
  this.shortenerInfo = SHORTENERS_BACKEND[backendId];
}
Shortener.prototype = {
  shorten: function(longUrl, callback) {
    var _this = this;
      this.shortenerInfo.backend.shorten(longUrl, this.useAcct, this.login, this.apiKey, this.serviceUrl,
        function(errorCode, msg) {
      var cbMsg = null;
      var success = true;
      if(errorCode == 0 && msg) {
        cbMsg = _this.shortenerInfo.baseUrl + msg;
      } else if(errorCode != 0 && msg) {
        cbMsg = 'Error ' + errorCode + ': ' + msg;
        success = false;
      } else {
        cbMsg = 'Unknown Error';
        success = false;
      }
      callback(success, cbMsg);
    });
  }
}

BitLyShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://api.bit.ly/shorten";
    var params = {
      version: '2.0.1',
      format: 'json',
      longUrl: longUrl
    }
    if(useAcct) {
      params['login'] = login;
      params['apiKey'] = apiKey;
      params['history'] = 1;
    } else {
      params['login'] = 'chromedbird';
      params['apiKey'] = 'R_aa77c64a8258cf704e7fa361555a4d81';
    }

    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'json',
      success: function(data, status) {
        var ecAPI = data.errorCode;
        if(ecAPI == 0) {
          var ecURL = data.results[longUrl].errorCode;
          if(!ecURL || ecURL==0) {
            callback(0, data.results[longUrl].userHash);
          } else {
            callback(ecURL, data.results[longUrl].errorMessage);
          }
        } else {
          callback(ecAPI, data.errorMessage);
        }
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

TrimShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://api.tr.im/v1/trim_url.json";
    var params = {
      url: longUrl
    }
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'json',
      success: function(data, status) {
        if(data.status.result != 'OK') {
          callback(data.status.code, data.status.message);
          return;
        }
        callback(0, data.trimpath);
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

MigremeShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://migre.me/api.xml";
    var params = {
      url: longUrl
    }
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'xml',
      success: function(data, status) {
        var errorId = $('error', data).text();
        if(errorId != 0) {
          callback(errorId, $('errormessage', data).text());
          return;
        }
        callback(0, $('id', data).text());
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

IsGdShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://is.gd/api.php";
    var params = {
      longurl: longUrl
    }
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'text',
      success: function(data, status) {
        if(data.match(/^ERROR/i)) {
          callback(-1, data);
          return;
        }
        callback(0, data);
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

MiudinShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://miud.in/api-create.php";
    var params = {
      url: longUrl
    }
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'text',
      success: function(data, status) {
        callback(0, data);
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

UdanaxShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://udanax.org/shorturl.jsp";
    var params = {
      mode: 'api',
      longurl: longUrl
    };
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      jsonp: 'jsoncallback',
      dataType: 'jsonp',
      success: function(data, status) {
        callback(0, data.shorturl);
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

URLinlShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://urli.nl/api.php";
    var params = {
      format: 'json',
      action: 'shorturl',
      url: longUrl
    };
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'json',
      success: function(data, status) {
        if(data && data.status && data.status == 'success') {
          callback(0, data.url.keyword);
        } else {
          callback(data.statusCode, data.message);
        }
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

URLcortaShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://urlcorta.es/api/text/";
    var params = {
      url: longUrl
    }
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'text',
      success: function(data, status) {
        callback(0, data);
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

GooglShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var authFunc = function(f){function k(){for(var c=0,b=0;b<arguments.length;b++)c=c+arguments[b]&4294967295;return c}function m(c){c=c=String(c>0?c:c+4294967296);var b;b=c;for(var d=0,i=false,j=b.length-1;j>=0;--j){var g=Number(b.charAt(j));if(i){g*=2;d+=Math.floor(g/10)+g%10}else d+=g;i=!i}b=b=d%10;d=0;if(b!=0){d=10-b;if(c.length%2==1){if(d%2==1)d+=9;d/=2}}b=String(d);b+=c;return b}function n(c){for(var b=5381,d=0;d<c.length;d++)b=k(b<<5,b,c.charCodeAt(d));return b}function o(c){for(var b=0,d=0;d<c.length;d++)b=k(c.charCodeAt(d),b<<6,b<<16,-b);return b}f={byteArray_:f,charCodeAt:function(c){return this.byteArray_[c]}};f.length=f.byteArray_.length;var e=n(f.byteArray_);e=e>>2&1073741823;e=e>>4&67108800|e&63;e=e>>4&4193280|e&1023;e=e>>4&245760|e&16383;var l="7";f=o(f.byteArray_);var h=(e>>2&15)<<4|f&15;h|=(e>>6&15)<<12|(f>>8&15)<<8;h|=(e>>10&15)<<20|(f>>16&15)<<16;h|=(e>>14&15)<<28|(f>>24&15)<<24;l+=m(h);return l};
    var url = 'http://goo.gl/api/url';
    var params = {
      user: 'toolbar@google.com',
      url: longUrl,
      auth_token: authFunc(longUrl)
    };
    $.ajax({
      url: url,
      type: 'post',
      data: params,
      dataType: 'json',
      success: function(data, status) {
        callback(0, data.short_url);
      },
      error: function (request, status, error) {
        var errMsg;
        try {
          var rspObj = JSON.parse(request.responseText);
          errMsg = rspObj.error_message;
        } catch(e) {
          errMsg = chrome.i18n.getMessage("ajaxFailed");
        }
        callback(-1, errMsg);
      }
    });
  }
}

KCYShortener = {
  shorten : function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = 'http://kcy.me/api/';
    var params = {
      url: longUrl,
      u: login,
      key: apiKey
    };
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'text',
      success: function(data, status) {
        var errorCode = -1;
        if(data.match(/^http/i)) {
          errorCode = 0;
        }
        callback(errorCode, data);
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

YourlsShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var params = {
      signature: apiKey,
      action:  'shorturl',
      format: 'json',
      url: longUrl,
    };

    $.ajax({
      type: 'GET',
      url: serviceUrl,
      data: params,
      dataType: 'json',
      success: function(data, status) {
        if(data && data.status && data.shorturl) {
          callback(0, data.shorturl);
        } else {
          callback(-1, data.message);
        }
      },
      error: function (request, status, error) {
        callback(-1,'AJAX request failed (bad connection?)');
      }
    });
  }
}

McafeeShortener = {
  shorten: function(longUrl, useAcct, login, apiKey, serviceUrl, callback) {
    var url = "http://mcaf.ee/api/shorten";
    var params = {
      input_url: longUrl,
      format: 'json'
    }
    $.ajax({
      type: 'GET',
      url: url,
      data: params,
      dataType: 'json',
      success: function(data, status) {
        if(!data) {
          callback(-1, chrome.i18n.getMessage("ajaxFailed"));
        }
        if(data.status_code == 200 && data.data) {
          callback(0, data.data.url);
        } else {
          callback(data.status_code, data.status_txt);
        }
      },
      error: function (request, status, error) {
        callback(-1, chrome.i18n.getMessage("ajaxFailed"));
      }
    });
  }
}

SHORTENERS_BACKEND = {
  bitly: {
    desc: 'bit.ly',
    baseUrl: 'http://bit.ly/',
    backend: BitLyShortener
  },
  jmp: {
    desc: 'j.mp',
    baseUrl: 'http://j.mp/',
    backend: BitLyShortener
  },
  trim: {
    desc: 'tr.im',
    baseUrl: 'http://tr.im/',
    backend: TrimShortener
  },
  isgd: {
    desc: 'is.gd',
    baseUrl: '',
    backend: IsGdShortener
  },
  migreme: {
    desc: 'migre.me',
    baseUrl: 'http://migre.me/',
    backend: MigremeShortener
  },
  miudin: {
    desc: 'miud.in',
    baseUrl: '',
    backend: MiudinShortener
  },
  udanax: {
    desc: 'udanax.org',
    baseUrl: 'http://udanax.org/',
    backend: UdanaxShortener
  },
  urlinl: {
    desc: 'URLi.nl',
    baseUrl: 'http://urli.nl/',
    backend: URLinlShortener
  },
  urlcorta: {
    desc: 'URLcorta.es',
    baseUrl: '',
    backend: URLcortaShortener
  },
  googl: {
    desc: 'goo.gl',
    baseUrl: '',
    backend: GooglShortener
  },
  karmacracy: {
    desc: 'karmacracy.com',
    baseUrl: '',
    backend: KCYShortener
  },
  yourls: {
    desc: 'yourls',
    baseUrl: '',
    backend: YourlsShortener
  },
  mcafee: {
    desc: 'mcaf.ee',
    baseUrl: '',
    backend: McafeeShortener
  }
}
<|endoftext|>


<commit_before>Xflow.registerOperator("lerpSeq", {
    outputs: [  {type: 'float3', name: 'result'}],
    params:  [  {type: 'float3', source: 'sequence'},
                {type: 'float', source: 'key'}],
    mapping: [  {source: 'sequence', sequence: Xflow.SEQUENCE.PREV_BUFFER, keySource: 'key'},
                {source: 'sequence', sequence: Xflow.SEQUENCE.NEXT_BUFFER, keySource: 'key'},
                {source: 'sequence', sequence: Xflow.SEQUENCE.LINEAR_WEIGHT, keySource: 'key'}],
    evaluate: function(result, value1, value2, weight) {
        var me = this;
        this.result.result = sequence.interpolate(weight[0], function(v1,v2,t) {
            if (!me.tmp || me.tmp.length != v1.length)
                me.tmp = new Float32Array(v1.length);
            var result = me.tmp;
            var it = 1.0 - t;
            for(var i = 0; i < v1.length; i++) {
                result[i] = v1[i] * it + v2[i] * t;
            };
            return result;
        });
        return true;
    },
    evaluate_core: function(result, value1, value2, weight){
        var invWeight = 1 - weight[0];
        result[0] = invWeight*value1[0] + weight[0]*value2[0];
        result[1] = invWeight*value1[1] + weight[0]*value2[1];
        result[2] = invWeight*value1[2] + weight[0]*value2[2];
    },
    evaluate_parallel: function(sequence, weight) {
        var me = this;
        this.result.result = sequence.interpolate(weight[0], function(v1,v2,t) {
            if (!me.tmp || me.tmp.length != v1.length)
                me.tmp = new Float32Array(v1.length);
            var result = me.tmp;
            var it = 1.0 - t;

            for(var i = 0; i < v1.length; i++) {
                result[i] = v1[i] * it + v2[i] * t;
            };
            return result;
        });
        return true;
    }
});<commit_msg>Fix to avoid error with closure compilation<commit_after>Xflow.registerOperator("lerpSeq", {
    outputs: [  {type: 'float3', name: 'result'}],
    params:  [  {type: 'float3', source: 'sequence'},
                {type: 'float', source: 'key'}],
    mapping: [  {source: 'sequence', sequence: Xflow.SEQUENCE.PREV_BUFFER, keySource: 'key'},
                {source: 'sequence', sequence: Xflow.SEQUENCE.NEXT_BUFFER, keySource: 'key'},
                {source: 'sequence', sequence: Xflow.SEQUENCE.LINEAR_WEIGHT, keySource: 'key'}],
    evaluate_core: function(result, value1, value2, weight){
        var invWeight = 1 - weight[0];
        result[0] = invWeight*value1[0] + weight[0]*value2[0];
        result[1] = invWeight*value1[1] + weight[0]*value2[1];
        result[2] = invWeight*value1[2] + weight[0]*value2[2];
    },
    evaluate_parallel: function(sequence, weight) {
        var me = this;
        this.result.result = sequence.interpolate(weight[0], function(v1,v2,t) {
            if (!me.tmp || me.tmp.length != v1.length)
                me.tmp = new Float32Array(v1.length);
            var result = me.tmp;
            var it = 1.0 - t;

            for(var i = 0; i < v1.length; i++) {
                result[i] = v1[i] * it + v2[i] * t;
            };
            return result;
        });
        return true;
    }
});<|endoftext|>


<commit_before>import coroutine from './coroutine'

describe('coroutine', () => {

  function neverResolve() {
    return new Promise((resolve, reject) => {})
  }

  function asyncResolveTo(value) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(value);
      }, 50);
    });
  }

  function asyncRejectTo(error) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(error);
      }, 50);
    });
  }

  it('should be defined', () => {
    expect(coroutine).toBeDefined();
  });

  describe('function argument', () => {

    it('executes function', () => {
      var executedFunction = false;

      coroutine(() =>
        executedFunction = true
      );
      expect(executedFunction).toBe(true);
    });

    it('passes arguments to function', () => {
      coroutine((x, y, z) =>
        expect([x, y, z]).toEqual([1, 2, 3])
      , 1, 2, 3);
    });

    it('immediately executes function in the correct context', () => {
      var context = {
        value: 'valueInContext'
      };

      //() => {} would ignore the context, using 'function'
      coroutine.call(context, function() {
        expect(this.value).toBe('valueInContext');
      });
    });

    it('returns promise that immediately resolves to function\'s return value', (done) => {
      coroutine(() => 'returnValue').then(value => {
        expect(value).toBe('returnValue');
        done();
      });
    });

    it('returns promise that rejects if the function throws an exception', (done) => {
      coroutine(() => {
        throw 'someError'
      }).catch(error => {
        expect(error).toBe('someError');
        done();
      });
    });

    it('returns a promise chained to the promise returned by the function if it returns a promise', (done) => {
      coroutine(() =>
        Promise.resolve('someValue')
      ).then(value => {
        expect(value).toBe('someValue');
        done();
      });
    });
  });

  describe('non-function argument', () => {

    it('resolves to the argument', () => {
      coroutine(1).then(value =>
        expect(value).toBe(1)
      );
    });
  });

  describe('generator argument', () => {

    it('passes arguments to the generator', (done) => {
      coroutine(function*(x, y, z) {
        return x + y + z;
      }, 'a', 'b', 'c').then(value => {
        expect(value).toBe('abc');
        done();
      });
    });

    describe('yields simple values', () => {

      describe('no yields', () => {

        it('executes the generator until it stops', (done) => {
          coroutine(function*() {
            return 'returnValue';
          }).then(value => {
            expect(value).toBe('returnValue');
            done();
          });
        });
      });

      describe('has yields', function() {

        it('executes the generator until it stops', (done) => {
          var iterationsCount = 0;

          coroutine(function*() {
            iterationsCount++;
            yield 'a';
            iterationsCount++;
            yield 'b';
            iterationsCount++;
            return 'c';
          }).then(value => {
            expect(value).toBe('c');
            expect(iterationsCount).toBe(3);
            done();
          });
        });

        it('rejects if the generator throws an exception', (done) => {
          coroutine(function*() {
            yield 'a';
            throw 'someError';
          }).catch(error => {
            expect(error).toBe('someError');
            done();
          });
        });

        it('executes generator with single yield', (done) => {
          coroutine(function*() {
            yield 'a';
          }).then(value => {
            expect(value).not.toBeDefined();
            done();
          });
        });
      });
    });

    describe('yields promises', () => {

      it('awaits the promises that are yielded', (done) => {
        var iterationsCount = 0;

        coroutine(function*() {
          iterationsCount++;
          yield asyncResolveTo('a');
          iterationsCount++;
          yield asyncResolveTo('b');
          iterationsCount++;
          return asyncResolveTo('c');
        }).then(value => {
          expect(value).toBe('c');
          expect(iterationsCount).toBe(3);
          done();
        });
      });

      it('returns previous promise return value from yield', (done) => {
        coroutine(function*() {
          var x = yield asyncResolveTo('a');
          var y = yield asyncResolveTo('b');
          var z = yield asyncResolveTo('c');
          return x + y + z;
        }).then(value => {
          expect(value).toBe('abc');
          done();
        });
      });

      it('rejects if one of the promises rejects', (done) => {
        var iterationsCount = 0;

        coroutine(function*() {
          iterationsCount++;
          yield asyncResolveTo('a');
          iterationsCount++;
          yield asyncRejectTo('someError');
          iterationsCount++;
          return asyncResolveTo('c');
        }).catch(error => {
          expect(error).toBe('someError');
          expect(iterationsCount).toBe(2);
          done();
        });
      });

      it('returns promise return value for single yield in return', (done) => {
        var iterationsCount = 0;

        coroutine(function*() {
          return asyncResolveTo('a');
        }).then(value => {
          expect(value).toBe('a');
          done();
        });
      });

      it('is never settled if one of yielded promises is never settled', (done) => {
        var timeoutMs = 100;
        var hasResolved = false;
        var hasRejected = false;

        coroutine(function*() {
          yield neverResolve();
        }).then(value => {
          hasResolved = true;
        }).catch(error => {
          hasRejected = true;
        });
        setTimeout(() => {
          expect(hasResolved || hasRejected).toBe(false);
          done();
        }, timeoutMs);
      });
    });

    describe('yields to another generator', () => {

      it('executes the inner generator until it stops', (done) => {

        function* innerGenerator() {
          yield 'a';
          yield 'b';
          return 'c';
        }

        coroutine(function*() {
          var value = yield* innerGenerator();
          return value;
        }).then(value => {
          expect(value).toBe('c');
          done();
        });
      });

      it('executes all inner generators', (done) => {

        var counter = 0;

        function* innerGenerator() {
          counter++;
          return counter;
        }

        coroutine(function*() {
          yield* innerGenerator();
          yield* innerGenerator();
          return yield* innerGenerator();
        }).then(value => {
          expect(value).toBe(3);
          done();
        });
      });

      it('executes several nested generators', (done) => {

        function* f1() {
          return yield* f2();
        }

        function* f2() {
          return yield* f3();
        }

        function* f3() {
          return 'returnValue';
        }

        coroutine(function*() {
          return yield* f1();
        }).then(value => {
          expect(value).toBe('returnValue');
          done();
        });
      });

      it('executes nested generator that yields promises', (done) => {

        function* inner() {
          var b = yield asyncResolveTo('b');
          var c = yield asyncResolveTo('c');

          return asyncResolveTo(b + c + 'd');
        }

        coroutine(function*() {
          var a = yield asyncResolveTo('a');
          var bcd = yield yield* inner();

          return asyncResolveTo(a + bcd + 'e');
        }).then(value => {
          expect(value).toBe('abcde');
          done();
        });
      });

      //TODO: Error happens in an inner generator
      //TODO: Returning an inner generator from the enclosing one
    });
  });
});<commit_msg>Adds more unit tests.<commit_after>import coroutine from './coroutine'

describe('coroutine', () => {

  function neverResolve() {
    return new Promise((resolve, reject) => {})
  }

  function asyncResolveTo(value) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve(value);
      }, 50);
    });
  }

  function asyncRejectTo(error) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(error);
      }, 50);
    });
  }

  it('should be defined', () => {
    expect(coroutine).toBeDefined();
  });

  describe('function argument', () => {

    it('executes function', () => {
      var executedFunction = false;

      coroutine(() =>
        executedFunction = true
      );
      expect(executedFunction).toBe(true);
    });

    it('passes arguments to function', () => {
      coroutine((x, y, z) =>
        expect([x, y, z]).toEqual([1, 2, 3])
      , 1, 2, 3);
    });

    it('immediately executes function in the correct context', () => {
      var context = {
        value: 'valueInContext'
      };

      //() => {} would ignore the context, using 'function'
      coroutine.call(context, function() {
        expect(this.value).toBe('valueInContext');
      });
    });

    it('returns promise that immediately resolves to function\'s return value', (done) => {
      coroutine(() => 'returnValue').then(value => {
        expect(value).toBe('returnValue');
        done();
      });
    });

    it('returns promise that rejects if the function throws an exception', (done) => {
      coroutine(() => {
        throw 'someError'
      }).catch(error => {
        expect(error).toBe('someError');
        done();
      });
    });

    it('returns a promise chained to the promise returned by the function if it returns a promise', (done) => {
      coroutine(() =>
        Promise.resolve('someValue')
      ).then(value => {
        expect(value).toBe('someValue');
        done();
      });
    });
  });

  describe('non-function argument', () => {

    it('resolves to the argument', () => {
      coroutine(1).then(value =>
        expect(value).toBe(1)
      );
    });
  });

  describe('generator argument', () => {

    it('passes arguments to the generator', (done) => {
      coroutine(function*(x, y, z) {
        return x + y + z;
      }, 'a', 'b', 'c').then(value => {
        expect(value).toBe('abc');
        done();
      });
    });

    describe('yields simple values', () => {

      describe('no yields', () => {

        it('executes the generator until it stops', (done) => {
          coroutine(function*() {
            return 'returnValue';
          }).then(value => {
            expect(value).toBe('returnValue');
            done();
          });
        });
      });

      describe('has yields', function() {

        it('executes the generator until it stops', (done) => {
          var iterationsCount = 0;

          coroutine(function*() {
            iterationsCount++;
            yield 'a';
            iterationsCount++;
            yield 'b';
            iterationsCount++;
            return 'c';
          }).then(value => {
            expect(value).toBe('c');
            expect(iterationsCount).toBe(3);
            done();
          });
        });

        it('rejects if the generator throws an exception', (done) => {
          coroutine(function*() {
            yield 'a';
            throw 'someError';
          }).catch(error => {
            expect(error).toBe('someError');
            done();
          });
        });

        it('executes generator with single yield', (done) => {
          coroutine(function*() {
            yield 'a';
          }).then(value => {
            expect(value).not.toBeDefined();
            done();
          });
        });
      });
    });

    describe('yields promises', () => {

      it('awaits the promises that are yielded', (done) => {
        var iterationsCount = 0;

        coroutine(function*() {
          iterationsCount++;
          yield asyncResolveTo('a');
          iterationsCount++;
          yield asyncResolveTo('b');
          iterationsCount++;
          return asyncResolveTo('c');
        }).then(value => {
          expect(value).toBe('c');
          expect(iterationsCount).toBe(3);
          done();
        });
      });

      it('returns previous promise return value from yield', (done) => {
        coroutine(function*() {
          var x = yield asyncResolveTo('a');
          var y = yield asyncResolveTo('b');
          var z = yield asyncResolveTo('c');
          return x + y + z;
        }).then(value => {
          expect(value).toBe('abc');
          done();
        });
      });

      it('rejects if one of the promises rejects', (done) => {
        var iterationsCount = 0;

        coroutine(function*() {
          iterationsCount++;
          yield asyncResolveTo('a');
          iterationsCount++;
          yield asyncRejectTo('someError');
          iterationsCount++;
          return asyncResolveTo('c');
        }).catch(error => {
          expect(error).toBe('someError');
          expect(iterationsCount).toBe(2);
          done();
        });
      });

      it('returns promise return value for single yield in return', (done) => {
        var iterationsCount = 0;

        coroutine(function*() {
          return asyncResolveTo('a');
        }).then(value => {
          expect(value).toBe('a');
          done();
        });
      });

      it('is never settled if one of yielded promises is never settled', (done) => {
        var timeoutMs = 100;
        var hasResolved = false;
        var hasRejected = false;

        coroutine(function*() {
          yield neverResolve();
        }).then(value => {
          hasResolved = true;
        }).catch(error => {
          hasRejected = true;
        });
        setTimeout(() => {
          expect(hasResolved || hasRejected).toBe(false);
          done();
        }, timeoutMs);
      });
    });

    describe('yields to another generator', () => {

      it('executes the inner generator until it stops', (done) => {

        function* innerGenerator() {
          yield 'a';
          yield 'b';
          return 'c';
        }

        coroutine(function*() {
          var value = yield* innerGenerator();
          return value;
        }).then(value => {
          expect(value).toBe('c');
          done();
        });
      });

      it('executes all inner generators', (done) => {

        var counter = 0;

        function* innerGenerator() {
          counter++;
          return counter;
        }

        coroutine(function*() {
          yield* innerGenerator();
          yield* innerGenerator();
          return yield* innerGenerator();
        }).then(value => {
          expect(value).toBe(3);
          done();
        });
      });

      it('executes several nested generators', (done) => {

        function* f1() {
          return yield* f2();
        }

        function* f2() {
          return yield* f3();
        }

        function* f3() {
          return 'returnValue';
        }

        coroutine(function*() {
          return yield* f1();
        }).then(value => {
          expect(value).toBe('returnValue');
          done();
        });
      });

      it('executes nested generator that yields promises', (done) => {

        function* inner() {
          var b = yield asyncResolveTo('b');
          var c = yield asyncResolveTo('c');

          return asyncResolveTo(b + c + 'd');
        }

        coroutine(function*() {
          var a = yield asyncResolveTo('a');
          var bcd = yield yield* inner();

          return asyncResolveTo(a + bcd + 'e');
        }).then(value => {
          expect(value).toBe('abcde');
          done();
        });
      });

      it('executes nested generator that yields promises', (done) => {

        function* inner() {
          yield asyncRejectTo('innerError');
          return 'innerValue';
        }

        coroutine(function*() {
          yield* inner();

          return 'externalValue';
        }).catch(error => {
          expect(error).toBe('innerError');
          done();
        });
      });

      it('does not execute inner generator when it is just being returned', (done) => {

        function* inner() {
          yield asyncRejectTo('innerError');
        }

        coroutine(function*() {
          return inner;
        }).then(value => {
          expect(value).toEqual(inner);
          done();
        });
      });
    });
  });
});<|endoftext|>


<commit_before>import _ from 'intl'
import ActionRowButton from 'action-row-button'
import isEmpty from 'lodash/isEmpty'
import Link from 'link'
import React from 'react'
import SortedTable from 'sorted-table'
import Tooltip from 'tooltip'
import { ButtonGroup } from 'react-bootstrap-4/lib'
import { Container, Row, Col } from 'grid'
import { editSr, isSrShared, setDefaultSr } from 'xo'
import { formatSize } from 'utils'
import { Text } from 'editable'

const SR_COLUMNS = [
  {
    name: _('srName'),
    itemRenderer: (sr, pool) => (

        <Link to={`/srs/${sr.id}`}>
          <Text value={sr.name_label} onChange={value => editSr(sr, { name_label: value })} useLongClick />
        </Link>
        {pool.default_SR === sr.id && {_('defaultSr')}}

    ),
    sortCriteria: 'name_label'
  },
  {
    name: _('srFormat'),
    itemRenderer: sr => sr.SR_type,
    sortCriteria: 'SR_type'
  },
  {
    name: _('srSize'),
    itemRenderer: sr => formatSize(sr.size),
    sortCriteria: 'size'
  },
  {
    default: true,
    name: _('srUsage'),
    itemRenderer: sr => sr.size > 1 &&
      <Tooltip content={_('spaceLeftTooltip', {used: Math.round((sr.physical_usage / sr.size) * 100), free: formatSize(sr.size - sr.physical_usage)})}>
        <meter value={(sr.physical_usage / sr.size) * 100} min='0' max='100' optimum='40' low='80' high='90' />
      </Tooltip>,
    sortCriteria: sr => sr.physical_usage / sr.size,
    sortOrder: 'desc'
  },
  {
    name: _('srType'),
    itemRenderer: (sr, pool) =>

      {isSrShared(sr) ? _('srShared') : _('srNotShared')}
      <ButtonGroup className='pull-xs-right'>
        {(pool.default_SR !== sr.id && sr.size > 1) && <Tooltip key={sr.id} content={_('setAsDefaultSr')}>
          <ActionRowButton
            handler={setDefaultSr}
            handlerParam={sr}
            icon='disk'
          />
        </Tooltip>}
      </ButtonGroup>

,
    sortCriteria: isSrShared
  }
]

export default ({
  pool,
  hosts,
  srs
}) => <Container>
  <Row>
    <Col>
      {!isEmpty(srs)
       ? <SortedTable collection={srs} columns={SR_COLUMNS} userData={pool} />
       :
{_('srNoSr')}

      }
    </Col>
  </Row>
</Container>
<commit_msg>fix(pool/storage): fix sort by usage<commit_after>import _ from 'intl'
import ActionRowButton from 'action-row-button'
import isEmpty from 'lodash/isEmpty'
import Link from 'link'
import React from 'react'
import SortedTable from 'sorted-table'
import Tooltip from 'tooltip'
import { ButtonGroup } from 'react-bootstrap-4/lib'
import { Container, Row, Col } from 'grid'
import { editSr, isSrShared, setDefaultSr } from 'xo'
import { formatSize } from 'utils'
import { Text } from 'editable'

const SR_COLUMNS = [
  {
    name: _('srName'),
    itemRenderer: (sr, pool) => (

        <Link to={`/srs/${sr.id}`}>
          <Text value={sr.name_label} onChange={value => editSr(sr, { name_label: value })} useLongClick />
        </Link>
        {pool.default_SR === sr.id && {_('defaultSr')}}

    ),
    sortCriteria: 'name_label'
  },
  {
    name: _('srFormat'),
    itemRenderer: sr => sr.SR_type,
    sortCriteria: 'SR_type'
  },
  {
    name: _('srSize'),
    itemRenderer: sr => formatSize(sr.size),
    sortCriteria: 'size'
  },
  {
    default: true,
    name: _('srUsage'),
    itemRenderer: sr => sr.size > 0 &&
      <Tooltip content={_('spaceLeftTooltip', {used: Math.round((sr.physical_usage / sr.size) * 100), free: formatSize(sr.size - sr.physical_usage)})}>
        <meter value={(sr.physical_usage / sr.size) * 100} min='0' max='100' optimum='40' low='80' high='90' />
      </Tooltip>,
    sortCriteria: ({ physical_usage: usage, size }) => size > 0 ? usage / size : 0,
    sortOrder: 'desc'
  },
  {
    name: _('srType'),
    itemRenderer: (sr, pool) =>

      {isSrShared(sr) ? _('srShared') : _('srNotShared')}
      <ButtonGroup className='pull-xs-right'>
        {(pool.default_SR !== sr.id && sr.size > 1) && <Tooltip key={sr.id} content={_('setAsDefaultSr')}>
          <ActionRowButton
            handler={setDefaultSr}
            handlerParam={sr}
            icon='disk'
          />
        </Tooltip>}
      </ButtonGroup>

,
    sortCriteria: isSrShared
  }
]

export default ({
  pool,
  hosts,
  srs
}) => <Container>
  <Row>
    <Col>
      {!isEmpty(srs)
       ? <SortedTable collection={srs} columns={SR_COLUMNS} userData={pool} />
       :
{_('srNoSr')}

      }
    </Col>
  </Row>
</Container>
<|endoftext|>


<commit_before>/*
 * This file is picked up by the build system only
 * when building for PRODUCTION
 */

import { register } from 'register-service-worker'

register(process.env.SERVICE_WORKER_FILE, {
  ready () {
    console.log('App is being served from cache by a service worker.')
  },
  registered (registration) { // registration -> a ServiceWorkerRegistration instance
    console.log('Service worker has been registered.')
  },
  cached (registration) { // registration -> a ServiceWorkerRegistration instance
    console.log('Content has been cached for offline use.')
  },
  updated (registration) { // registration -> a ServiceWorkerRegistration instance
    console.log('New content is available; please refresh.')
  },
  offline () {
    console.log('No internet connection found. App is running in offline mode.')
  },
  error (err) {
    console.error('Error during service worker registration:', err)
  }
})

// ServiceWorkerRegistration: https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
<commit_msg>feat: Update to latest register-service-worker specs<commit_after>/*
 * This file is picked up by the build system only
 * when building for PRODUCTION
 */

import { register } from 'register-service-worker'

register(process.env.SERVICE_WORKER_FILE, {
  ready () {
    console.log('App is being served from cache by a service worker.')
  },
  registered (registration) { // registration -> a ServiceWorkerRegistration instance
    console.log('Service worker has been registered.')
  },
  cached (registration) { // registration -> a ServiceWorkerRegistration instance
    console.log('Content has been cached for offline use.')
  },
  updatefound (registration) { // registration -> a ServiceWorkerRegistration instance
    console.log('New content is downloading.')
  },
  updated (registration) { // registration -> a ServiceWorkerRegistration instance
    console.log('New content is available; please refresh.')
  },
  offline () {
    console.log('No internet connection found. App is running in offline mode.')
  },
  error (err) {
    console.error('Error during service worker registration:', err)
  }
})

// ServiceWorkerRegistration: https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
<|endoftext|>


<commit_before>"use strict";

const retry = require('retry');
const unix_socket = require('./unix_socket');

exports.connect = function(server, socket_file){

  const io = require('socket.io')(server);

  let player_id = null;

  io.on("connection", function(client){
    console.log("browser connected");
    let serverConnection = null;

    client.on("join", function(id, token){
      console.log(id + " : " + token + " joined");
      player_id = id;

      connect_unix_socket(socket_file, (socket) => {
        serverConnection = socket;
        serverConnection.browserConnection = client;
        client.emit("net-status", {message: "connected to sim server", key: "server_connected", error: null});
      });
    });

    client.on("action", function(data){
      console.log("message received ", data);
      if(serverConnection) {
        data.player_id = player_id;
        serverConnection.write(JSON.stringify(data)+"\r\n");
      } else {
        console.log("action dropped as we don't have any server connection");
      }
    });

    client.on("disconnect", function(data){
      console.log("client disconnected");
      if(serverConnection) {
        serverConnection.end();
      }
    });
  });

};

connect_to_unix_socket(socket_file, callback){
  let operation = retry.operation();
  operation.attempt(function(currentAttempt){
    unix_socket.connect(socket_file, (err, socket) => {
      if(operation.retry(err)){
        client.emit("net-status", {message: "sim server is not available", key: "server_away", error: err});
        return;
      } else {
        callback(socket);
      }
    });

  });
}
<commit_msg>! fix websocket<commit_after>"use strict";

const retry = require('retry');
const unix_socket = require('./unix_socket');

const connect_to_unix_socket = function(socket_file, callback){
  let operation = retry.operation();
  operation.attempt(function(currentAttempt){
    unix_socket.connect(socket_file, (err, socket) => {
      if(operation.retry(err)){
        client.emit("net-status", {message: "sim server is not available", key: "server_away", error: err});
        return;
      } else {
        callback(socket);
      }
    });

  });
};

exports.connect = function(server, socket_file){

  const io = require('socket.io')(server);

  let player_id = null;

  io.on("connection", function(client){
    console.log("browser connected");
    let serverConnection = null;

    client.on("join", function(id, token){
      console.log(id + " : " + token + " joined");
      player_id = id;

      connect_to_unix_socket(socket_file, (socket) => {
        serverConnection = socket;
        serverConnection.browserConnection = client;
        client.emit("net-status", {message: "connected to sim server", key: "server_connected", error: null});
      });
    });

    client.on("action", function(data){
      console.log("message received ", data);
      if(serverConnection) {
        data.player_id = player_id;
        serverConnection.write(JSON.stringify(data)+"\r\n");
      } else {
        console.log("action dropped as we don't have any server connection");
      }
    });

    client.on("disconnect", function(data){
      console.log("client disconnected");
      if(serverConnection) {
        serverConnection.end();
      }
    });
  });

};
<|endoftext|>


<commit_before>var socket = io.connect('http://' + window.location.host);

function getState(id) {
    var obj = $('#value-' + id);
    $.get('/state/' + id, function(res) {
        obj.text(res.data);
    });
}

function addLoadListener(id) {
    $('#load-' + id).on('click', function() {
        $.post('/load', {projectId: projectId, stateId: id});
    });
}

function drawTree(states) {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Node');
    data.addColumn('string', 'Parent');
    for (var i = 0; i < states.length; i++) {
        var state = states[i];
        var html = '
';
        html += '
';
        if (state.icon) {
            html += '
';
        }
        if (state.name) {
            html += '
' + state.name.substring(0, 16);
        }
        html += '
';
        html += '
';
        html += state.id + ': ';
        if (state.name) {
            html += state.name + '
';
        }
        html += '' + state.path + '';
        html += '
(' + new Date(state.timestamp).toLocaleTimeString() + ')';
        html += '
';
        html += '
';
        var parentId = state.parentId ? state.parentId.toString() : '';
        data.addRow([{v: state.id.toString(), f: html}, state.parentId]);
    }
    var chart = new google.visualization.OrgChart(document.getElementById('canvas'));
    chart.draw(data, {allowHtml:true, nodeClass:'treenode', size:'small'});
    for (var i = 0; i < states.length; i++) {
        var state = states[i];
        getState(state.id);
        addLoadListener(state.id);
    }
}

function addMoveListeners() {
    var startX = 0, startY = 0, prevX = 0, prevY = 0;
    $('#canvas-container').on('mousedown', function(event) {
        startX = parseInt($('#canvas').css('left'));
        startY = parseInt($('#canvas').css('top'));
        prevX = event.clientX;
        prevY = event.clientY;
        $(window).on('mousemove', function(event) {
            $('#canvas').css({
                left: startX + event.clientX - prevX,
                top: startY + event.clientY - prevY
            });
        });
    });
    $(window).on('mouseup', function(event) {
        $(window).off('mousemove');
    });
}

function addMaximizeListener() {
    $('#toggle-maximize').on('click', function() {
        if ($('#canvas-wrapper').hasClass('overlay')) {
            var element = $('#canvas-wrapper').detach();
            $('#canvas-parent').append(element);
            $('#canvas-container').css('max-height', '600px');
            $('#canvas-wrapper').removeClass('overlay');
            $('#toggle-maximize').text('+');
        } else {
            var element = $('#canvas-wrapper').detach();
            $('body').append(element);
            $('#canvas-container').css('max-height', '100%');
            $('#canvas-wrapper').addClass('overlay');
            $('#toggle-maximize').text('-');
        }
    });
}

function addListeners() {
    $('#nav-save').on('click', function() {
        $.post('/requestSave', {projectId: projectId});
    });
    addMoveListeners();
    addMaximizeListener();
    socket.emit('projectId', projectId);
    socket.on('tree', function(data) {
        drawTree(data);
    });
}

<commit_msg>Placeholder for empty tree nodes.<commit_after>var socket = io.connect('http://' + window.location.host);

function getState(id) {
    var obj = $('#value-' + id);
    $.get('/state/' + id, function(res) {
        obj.text(res.data);
    });
}

function addLoadListener(id) {
    $('#load-' + id).on('click', function() {
        $.post('/load', {projectId: projectId, stateId: id});
    });
}

function drawTree(states) {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Node');
    data.addColumn('string', 'Parent');
    for (var i = 0; i < states.length; i++) {
        var state = states[i];
        var html = '
';
        html += '
';
        if (state.icon) {
            html += '
';
        }
        if (state.name) {
            html += '
' + state.name.substring(0, 16);
        }
        if (!state.icon && !state.name) {
            html += new Date(state.timestamp).toLocaleTimeString();
        }
        html += '
';
        html += '
';
        html += state.id + ': ';
        if (state.name) {
            html += state.name + '
';
        }
        html += '' + state.path + '';
        html += '
(' + new Date(state.timestamp).toLocaleTimeString() + ')';
        html += '
';
        html += '
';
        var parentId = state.parentId ? state.parentId.toString() : '';
        data.addRow([{v: state.id.toString(), f: html}, state.parentId]);
    }
    var chart = new google.visualization.OrgChart(document.getElementById('canvas'));
    chart.draw(data, {allowHtml:true, nodeClass:'treenode', size:'small'});
    for (var i = 0; i < states.length; i++) {
        var state = states[i];
        getState(state.id);
        addLoadListener(state.id);
    }
}

function addMoveListeners() {
    var startX = 0, startY = 0, prevX = 0, prevY = 0;
    $('#canvas-container').on('mousedown', function(event) {
        startX = parseInt($('#canvas').css('left'));
        startY = parseInt($('#canvas').css('top'));
        prevX = event.clientX;
        prevY = event.clientY;
        $(window).on('mousemove', function(event) {
            $('#canvas').css({
                left: startX + event.clientX - prevX,
                top: startY + event.clientY - prevY
            });
        });
    });
    $(window).on('mouseup', function(event) {
        $(window).off('mousemove');
    });
}

function addMaximizeListener() {
    $('#toggle-maximize').on('click', function() {
        if ($('#canvas-wrapper').hasClass('overlay')) {
            var element = $('#canvas-wrapper').detach();
            $('#canvas-parent').append(element);
            $('#canvas-container').css('max-height', '600px');
            $('#canvas-wrapper').removeClass('overlay');
            $('#toggle-maximize').text('+');
        } else {
            var element = $('#canvas-wrapper').detach();
            $('body').append(element);
            $('#canvas-container').css('max-height', '100%');
            $('#canvas-wrapper').addClass('overlay');
            $('#toggle-maximize').text('-');
        }
    });
}

function addListeners() {
    $('#nav-save').on('click', function() {
        $.post('/requestSave', {projectId: projectId});
    });
    addMoveListeners();
    addMaximizeListener();
    socket.emit('projectId', projectId);
    socket.on('tree', function(data) {
        drawTree(data);
    });
}

<|endoftext|>


<commit_before>(function() {
    var guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
    var verbs = [];
    var room = (function() {
        var _room = localStorage.getItem("room.1")
        return (_room==undefined) ? "Lobby" : _room;
    })();
    var remoteIO = {
      setVerbs:function(_verbs) { verbs = _verbs; },
      // to be overridden by the app
      onFocus:function(focus) {},
      onVerb:function(verb) {},
    };

    var socket = io({});
    socket.on('connect', function() {
        console.log("connect", guid, room);
        socket.emit('/room/join', {name: room});
    });
    socket.on('/room/join/success', function(data) {
        console.log("/room/join/success");
    });
    socket.on('/room/message', function(data) {
        console.log("/room/message", data);
        switch(data.cmd) {
        case 'scan':
            socket.emit('/room/message', {cmd:"advertise", guid:guid, verbs:verbs});
            break;
        case 'focus':
            if (data.guid == guid) {
                remoteIO.onFocus(data.focus);
            }
            break;
        case 'switch':
            if (data.guid == guid) {
                localStorage.setItem("room", data.room);
                socket.emit('/room/join', {name: data.room});
            }
            break;
        case 'custom':
            remoteIO.onVerb(data.verb);
            break;
        case 'scene':
            console.log("scene =", data.name, data.path);
            window.location.href = data.path;
            break;
        }
    });
    window.remoteIO = remoteIO;
})()

<commit_msg>onScene<commit_after>(function() {
    var guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
        return v.toString(16);
    });
    var verbs = [];
    var room = (function() {
        var _room = localStorage.getItem("room.1")
        return (_room==undefined) ? "Lobby" : _room;
    })();
    var remoteIO = {
      setVerbs:function(_verbs) { verbs = _verbs; },
      // to be overridden by the app
      onFocus:function(focus) {},
      onVerb:function(verb) {},
      onScene:function(scene) {
        console.log("scene =", scene.name, scene.path);
        window.location.href = scene.path;
      }
    };

    var socket = io({});
    socket.on('connect', function() {
        console.log("connect", guid, room);
        socket.emit('/room/join', {name: room});
    });
    socket.on('/room/join/success', function(data) {
        console.log("/room/join/success");
        socket.emit('/room/message', {cmd:"advertise", guid:guid, verbs:verbs});
    });
    socket.on('/room/message', function(data) {
        console.log("/room/message", data);
        switch(data.cmd) {
        case 'scan':
            socket.emit('/room/message', {cmd:"advertise", guid:guid, verbs:verbs});
            break;
        case 'focus':
            if (data.guid == guid) {
                remoteIO.onFocus(data.focus);
            }
            break;
        case 'switch':
            if (data.guid == guid) {
                localStorage.setItem("room", data.room);
                socket.emit('/room/join', {name: data.room});
            }
            break;
        case 'custom':
            remoteIO.onVerb(data.verb);
            break;
        case 'scene':
            remoteIO.onScene(data);
            break;
        }
    });
    window.remoteIO = remoteIO;
})()

<|endoftext|>