<commit_before>define(['co', 'md5', 'app/utils/storage'], function(co, md5, storage) {
    function FileController(options) {
        var self = this;
        this.fsInitPromise = co(function*() {
            yield self._init();
            self.rootEntry = self.fs.root;

            var savedRootUrl = yield storage.get('rootURL');
            console.log(savedRootUrl, self.fs.root);
            if (savedRootUrl && window.resolveLocalFileSystemURL) {
                self.rootEntry = yield new Promise(function(resolve, reject) {
                    window.resolveLocalFileSystemURL(savedRootUrl, function(dirEntry) {
                        resolve(dirEntry);
                    }, function(err) {
                        console.error(err);
                        storage.set('rootURL', self.fs.root.nativeURL || self.fs.root.fullPath);
                        resolve(self.fs.root);
                    });
                });
            }
        }).catch(function(err) {
            console.error(err);
        });
    }

    /** API
     *
     *   getDirectory({@path: String, @root: DirEntry, @create: bool})
     *   getFiles(@dirEntry: DirEntry)
     *
     */
    FileController.prototype.renameFile = function(fileEntry, newName) {
        var self = this;
        var rootPath = self.rootEntry.name;
        return co(function*() {
            // if (fileEntry.isDirectory) {
            //     return fileEntry.removeRecursively(resolve, reject);
            // }
            // fileEntry.remove(resolve, reject);
            var currentName = fileEntry.fullPath;
            var filePaths = newName.split('/');
            var fileName = newName;
            var dirPaths;
            var dirEntry = self.rootEntry;
            if (filePaths.length > 1) {
                dirPaths = filePaths.slice(0, -1);
                fileName = filePaths.slice(-1)[0];
            }
            if (dirPaths) {
                for (var i = 0; i < dirPaths.length; i++) {
                    if ((i == 1 || i == 0) && (dirPaths[i] == rootPath)) {
                        // Chrome hak!
                        continue;
                    }
                    if (!dirPaths[i]) {
                        continue;
                    }
                    dirEntry = yield self.getDirectory({
                        root: dirEntry,
                        path: dirPaths[i],
                        create: true
                    });
                }
            }
            yield new Promise(function(resolve, reject) {
                fileEntry.moveTo(dirEntry, fileName, resolve, reject);
            });

            return fileEntry;
        });
    };

    FileController.prototype.deleteFile = function(fileEntry) {
        return new Promise(function(resolve, reject) {
            if (fileEntry.isDirectory) {
                return fileEntry.removeRecursively(resolve, reject);
            }
            fileEntry.remove(resolve, reject);
        });
    };

    FileController.prototype.writeFile = function(fileEntry, data) {
        var self = this;
        return co(function*() {
            var writableEntry = fileEntry;
            if (!window.LocalFileSystem && window.chrome) {
                writableEntry = yield new Promise(function(resolve, reject) {
                    chrome.fileSystem.getWritableEntry(fileEntry, resolve);
                });
            }

            writableEntry.createWriter(function(fileWriter) {
                // Writing data
                fileWriter.onwriteend = function() {
                    // console.log("Successful file write...", data);
                    fileWriter.onwriteend = function() {};
                    fileWriter.write(new Blob([data], {
                        type: 'text/plain'
                    }));
                };

                fileWriter.onerror = function(e) {
                    console.log("Failed file write: " + e.toString());
                    throw e;
                };

                fileWriter.truncate(0);
            });
        });
    };

    FileController.prototype.readFile = function(fileEntry) {
        return new Promise(function(resolve, reject) {
            fileEntry.file(function(file) {
                var reader = new FileReader();

                reader.onloadend = function() {
                    resolve(this.result);
                };

                reader.readAsText(file);

            }, reject);
        });
    };

    FileController.prototype.readFileByName = function(fileName) {
        var self = this;
        var rootPath = self.rootEntry.name;
        return new Promise(function(resolve, reject) {
            var filePaths = fileName.split('/');
            var dirEntry = self.rootEntry;

            if (filePaths.length > 1) {
                var dirPaths = filePaths.slice(0, -1);
                fileName = filePaths.slice(-1)[0];
                // console.log(dirPaths, filePaths.slice(-1));
            }

            co(function*() {
                if (dirPaths) {
                    for (var i = 0; i < dirPaths.length; i++) {
                        if ((i == 1 || i == 0) && (dirPaths[i] == rootPath)) {
                            // Chrome hak!
                            continue;
                        }
                        if (!dirPaths[i]) {
                            continue;
                        }
                        dirEntry = yield self.getDirectory({
                            root: dirEntry,
                            path: dirPaths[i],
                            create: true
                        });
                    }
                }

                if (!fileName) {
                    return resolve();
                }

                dirEntry.getFile(fileName, {
                    "create": true
                }, function(fileEntry) {
                    fileEntry.nativeURL = fileEntry.nativeURL || fileEntry.fullPath;
                    fileEntry.file(function(file) {
                        var reader = new FileReader();

                        reader.onloadend = function() {
                            resolve({
                                fileEntry: fileEntry,
                                fileContent: this.result
                            });
                        };

                        reader.readAsText(file);

                    }, reject);
                }, reject);
            });
        });

    };

    FileController.prototype.getDirectory = function(options) {
        var rootEntry = options.root || this.rootEntry;
        if (!options.path) {
            throw new Error("path attribute required");
        }

        return new Promise(function(resolve, reject) {
            rootEntry.getDirectory(options.path, {
                "create": options.create || false
            }, resolve, reject);
        });
    };

    FileController.prototype.getFiles = function(dirEntry, navEnabled) {
        dirEntry = dirEntry || this.rootEntry;
        var fileStructure = [];
        var self = this;

        return co(function*() {
            if (navEnabled) {
                if (self.rootEntry == dirEntry) {
                    try {
                        var parentDirectory = yield self.getDirectory({
                            path: '../',
                            create: false
                        });

                        parentDirectory.nativeURL = parentDirectory.nativeURL || parentDirectory.fullPath;
                        fileStructure.push({
                            'text': '..',
                            'id': '__up',
                            'entry': parentDirectory,
                            'itree': {
                                state: {
                                    selectable: false
                                }
                            },
                            'children': parentDirectory.isDirectory > 0
                        });
                    } catch (err) {
                        console.error('unable to get parentDirectory', err);
                    }
                }
            }
            var directoryReader = dirEntry.createReader();
            yield new Promise(function(resolve, reject) {

                directoryReader.readEntries(function(entries) {
                    var promises = [];
                    for (var i = 0; i < entries.length; i++) {

                        promises.push(co(function*() {
                            var entry = entries[i];

                          	entry.nativeURL = entry.nativeURL || entry.fullPath;
                            var fileDescription = {
                                'text': entry.name,
                                'id': md5(entry.nativeURL),
                                'entry': entry,
                                'itree': {
                                    state: {
                                        selectable: false
                                    }
                                },
                                'children': entry.isDirectory > 0
                            };

                            fileStructure.push(fileDescription);
                        }));

                    }
                    Promise.all(promises).then(function() {
                        resolve(fileStructure);
                    }, reject);
                });
            });

            // console.log(fileStructure.length);
            return fileStructure;
        });
    };

    FileController.prototype.wait = FileController.prototype.waitForInit = function() {
        return this.fsInitPromise;
    };

    // Private methods
    FileController.prototype._init = function() {
        var self = this;
        return co(function*() {
            try {
                self.fs = yield self._getFs();
                // console.log('file system open: ' + self.fs.name);
            } catch (err) {
                console.error(err);
                throw err;
            }
        });
    };

    FileController.prototype._getFs = function() {
        return new Promise(function(resolve, reject) {
            // console.log(window.LocalFileSystem, chrome);
            if (window.LocalFileSystem) {
                window.requestFileSystem(window.LocalFileSystem.PERSISTENT, 0, resolve, reject);
            } else if (chrome) {
                chrome.fileSystem.chooseEntry({
                    type: "openDirectory"
                }, function(rootEntry) {
                    resolve({
                        root: rootEntry
                    });
                });
            }
        });
    };

    return FileController;
});<commit_msg>fix issue with cyrillic symbols in files on Ubuntu Touch<commit_after>define(['co', 'md5', 'app/utils/storage'], function(co, md5, storage) {
    function FileController(options) {
        var self = this;
        this.fsInitPromise = co(function*() {
            yield self._init();
            self.rootEntry = self.fs.root;

            var savedRootUrl = yield storage.get('rootURL');
            console.log(savedRootUrl, self.fs.root);
            if (savedRootUrl && window.resolveLocalFileSystemURL) {
                self.rootEntry = yield new Promise(function(resolve, reject) {
                    window.resolveLocalFileSystemURL(savedRootUrl, function(dirEntry) {
                        resolve(dirEntry);
                    }, function(err) {
                        console.error(err);
                        storage.set('rootURL', self.fs.root.nativeURL || self.fs.root.fullPath);
                        resolve(self.fs.root);
                    });
                });
            }
        }).catch(function(err) {
            console.error(err);
        });
    }

    /** API
     *
     *   getDirectory({@path: String, @root: DirEntry, @create: bool})
     *   getFiles(@dirEntry: DirEntry)
     *
     */
    FileController.prototype.renameFile = function(fileEntry, newName) {
        var self = this;
        var rootPath = self.rootEntry.name;
        return co(function*() {
            // if (fileEntry.isDirectory) {
            //     return fileEntry.removeRecursively(resolve, reject);
            // }
            // fileEntry.remove(resolve, reject);
            var currentName = fileEntry.fullPath;
            var filePaths = newName.split('/');
            var fileName = newName;
            var dirPaths;
            var dirEntry = self.rootEntry;
            if (filePaths.length > 1) {
                dirPaths = filePaths.slice(0, -1);
                fileName = filePaths.slice(-1)[0];
            }
            if (dirPaths) {
                for (var i = 0; i < dirPaths.length; i++) {
                    if ((i == 1 || i == 0) && (dirPaths[i] == rootPath)) {
                        // Chrome hak!
                        continue;
                    }
                    if (!dirPaths[i]) {
                        continue;
                    }
                    dirEntry = yield self.getDirectory({
                        root: dirEntry,
                        path: dirPaths[i],
                        create: true
                    });
                }
            }
            yield new Promise(function(resolve, reject) {
                fileEntry.moveTo(dirEntry, fileName, resolve, reject);
            });

            return fileEntry;
        });
    };

    FileController.prototype.deleteFile = function(fileEntry) {
        return new Promise(function(resolve, reject) {
            if (fileEntry.isDirectory) {
                return fileEntry.removeRecursively(resolve, reject);
            }
            fileEntry.remove(resolve, reject);
        });
    };

    FileController.prototype.writeFile = function(fileEntry, data) {
        var self = this;
        return co(function*() {
            var writableEntry = fileEntry;
            if (!window.LocalFileSystem && window.chrome) {
                writableEntry = yield new Promise(function(resolve, reject) {
                    chrome.fileSystem.getWritableEntry(fileEntry, resolve);
                });
            }

            writableEntry.createWriter(function(fileWriter) {
                // Writing data
                fileWriter.onwriteend = function() {
                    // console.log("Successful file write...", data);
                    fileWriter.onwriteend = function() {};
                    if (window.chrome) {
                        fileWriter.write(new Blob([data], {
                            type: 'text/plain'
                        }));
                    } else {
                        fileWriter.write(data);
                    }
                };

                fileWriter.onerror = function(e) {
                    console.log("Failed file write: " + e.toString());
                    throw e;
                };

                fileWriter.truncate(0);
            });
        });
    };

    FileController.prototype.readFile = function(fileEntry) {
        return new Promise(function(resolve, reject) {
            fileEntry.file(function(file) {
                var reader = new FileReader();

                reader.onloadend = function() {
                    resolve(this.result);
                };

                reader.readAsText(file);

            }, reject);
        });
    };

    FileController.prototype.readFileByName = function(fileName) {
        var self = this;
        var rootPath = self.rootEntry.name;
        return new Promise(function(resolve, reject) {
            var filePaths = fileName.split('/');
            var dirEntry = self.rootEntry;

            if (filePaths.length > 1) {
                var dirPaths = filePaths.slice(0, -1);
                fileName = filePaths.slice(-1)[0];
                // console.log(dirPaths, filePaths.slice(-1));
            }

            co(function*() {
                if (dirPaths) {
                    for (var i = 0; i < dirPaths.length; i++) {
                        if ((i == 1 || i == 0) && (dirPaths[i] == rootPath)) {
                            // Chrome hak!
                            continue;
                        }
                        if (!dirPaths[i]) {
                            continue;
                        }
                        dirEntry = yield self.getDirectory({
                            root: dirEntry,
                            path: dirPaths[i],
                            create: true
                        });
                    }
                }

                if (!fileName) {
                    return resolve();
                }

                dirEntry.getFile(fileName, {
                    "create": true
                }, function(fileEntry) {
                    fileEntry.nativeURL = fileEntry.nativeURL || fileEntry.fullPath;
                    fileEntry.file(function(file) {
                        var reader = new FileReader();

                        reader.onloadend = function() {
                            resolve({
                                fileEntry: fileEntry,
                                fileContent: this.result
                            });
                        };

                        reader.readAsText(file);

                    }, reject);
                }, reject);
            });
        });

    };

    FileController.prototype.getDirectory = function(options) {
        var rootEntry = options.root || this.rootEntry;
        if (!options.path) {
            throw new Error("path attribute required");
        }

        return new Promise(function(resolve, reject) {
            rootEntry.getDirectory(options.path, {
                "create": options.create || false
            }, resolve, reject);
        });
    };

    FileController.prototype.getFiles = function(dirEntry, navEnabled) {
        dirEntry = dirEntry || this.rootEntry;
        var fileStructure = [];
        var self = this;

        return co(function*() {
            if (navEnabled) {
                if (self.rootEntry == dirEntry) {
                    try {
                        var parentDirectory = yield self.getDirectory({
                            path: '../',
                            create: false
                        });

                        parentDirectory.nativeURL = parentDirectory.nativeURL || parentDirectory.fullPath;
                        fileStructure.push({
                            'text': '..',
                            'id': '__up',
                            'entry': parentDirectory,
                            'itree': {
                                state: {
                                    selectable: false
                                }
                            },
                            'children': parentDirectory.isDirectory > 0
                        });
                    } catch (err) {
                        console.error('unable to get parentDirectory', err);
                    }
                }
            }
            var directoryReader = dirEntry.createReader();
            yield new Promise(function(resolve, reject) {

                directoryReader.readEntries(function(entries) {
                    var promises = [];
                    for (var i = 0; i < entries.length; i++) {

                        promises.push(co(function*() {
                            var entry = entries[i];

                            entry.nativeURL = entry.nativeURL || entry.fullPath;
                            var fileDescription = {
                                'text': entry.name,
                                'id': md5(entry.nativeURL),
                                'entry': entry,
                                'itree': {
                                    state: {
                                        selectable: false
                                    }
                                },
                                'children': entry.isDirectory > 0
                            };

                            fileStructure.push(fileDescription);
                        }));

                    }
                    Promise.all(promises).then(function() {
                        resolve(fileStructure);
                    }, reject);
                });
            });

            // console.log(fileStructure.length);
            return fileStructure;
        });
    };

    FileController.prototype.wait = FileController.prototype.waitForInit = function() {
        return this.fsInitPromise;
    };

    // Private methods
    FileController.prototype._init = function() {
        var self = this;
        return co(function*() {
            try {
                self.fs = yield self._getFs();
                // console.log('file system open: ' + self.fs.name);
            } catch (err) {
                console.error(err);
                throw err;
            }
        });
    };

    FileController.prototype._getFs = function() {
        return new Promise(function(resolve, reject) {
            // console.log(window.LocalFileSystem, chrome);
            if (window.LocalFileSystem) {
                window.requestFileSystem(window.LocalFileSystem.PERSISTENT, 0, resolve, reject);
            } else if (chrome) {
                chrome.fileSystem.chooseEntry({
                    type: "openDirectory"
                }, function(rootEntry) {
                    resolve({
                        root: rootEntry
                    });
                });
            }
        });
    };

    return FileController;
});<|endoftext|>


<commit_before>"use strict";

export default class WorkerMessenger {
  constructor(url) {
    this._requestId = 0;
    // worker jobs awaiting response { [requestId]: [ resolve, reject ] }
    this._pending = {};
    this._url = url;
    this._worker = null;
  }

  async release() {
    if (this._worker) {
      this._worker.terminate();
      this._worker = null;
    }
    Object.keys(this._pending).forEach(id => {
      this._fulfillPending(id, null, new Error("Worker terminated: " + this._url));
    });
  }

  _postMessage(message) {
    if (!this._worker) {
      this._worker = new Worker(this._url);
      this._worker.onmessage = (event) => {
        this._onMessage(event);
      };
    }

    this._worker.postMessage(message);
  }

  _onMessage(event) {
    if (!event.data.id) {
      console.log("Unexpected message", event);
      return;
    }

    this._fulfillPending(event.data.id, event.data.result, event.data.error);
  }

  _fulfillPending(id, result, error) {
    const resolver = this._pending[id];

    if (!resolver) {
      console.log("No resolver for", { id, result, error });
      return;
    }

    delete this._pending[id];

    if (error) {
      resolver[1](new Error(error));
      return;
    }

    resolver[0](result);
  }

  _requestResponse(message) {
    return new Promise((resolve, reject) => {
      message.id = ++this._requestId;
      this._pending[message.id] = [resolve, reject];
      this._postMessage(message);
    });
  }
}
<commit_msg>Loading workers sooner<commit_after>"use strict";

export default class WorkerMessenger {
  constructor(url) {
    this._requestId = 0;
    // worker jobs awaiting response { [requestId]: [ resolve, reject ] }
    this._pending = {};
    this._url = url;
    this._worker = new Worker(this._url);
    this._worker.onmessage = event => this._onMessage(event);
  }

  async release() {
    if (this._worker) {
      this._worker.terminate();
      this._worker = null;
    }
    for (const key of Object.keys(this._pending)) {
      this._fulfillPending(id, null, new Error("Worker terminated: " + this._url));
    }
  }

  _postMessage(message) {
    this._worker.postMessage(message);
  }

  _onMessage(event) {
    if (!event.data.id) {
      console.log("Unexpected message", event);
      return;
    }

    this._fulfillPending(event.data.id, event.data.result, event.data.error);
  }

  _fulfillPending(id, result, error) {
    const resolver = this._pending[id];

    if (!resolver) {
      console.log("No resolver for", { id, result, error });
      return;
    }

    delete this._pending[id];

    if (error) {
      resolver[1](new Error(error));
      return;
    }

    resolver[0](result);
  }

  _requestResponse(message) {
    return new Promise((resolve, reject) => {
      message.id = ++this._requestId;
      this._pending[message.id] = [resolve, reject];
      this._postMessage(message);
    });
  }
}
<|endoftext|>


<commit_before>import React from 'react'
import PropTypes from 'prop-types'

import {AccountPropType} from 'src/propTypes'
import {makeFaviconUrl} from 'src/utils'

/**
 * ユーザーの顔アイコン with ホスト
 */
export class UserIconWithHost extends React.Component {
  static propTypes = {
    account: AccountPropType.isRequired,
    size: PropTypes.string,
  }

  /**
   * @override
   */
  render() {
    const {account, size} = this.props
    let className = 'userIcon with-host'

    if(size)
      className += ` size-${size}`

    return (

    )
  }
}
<commit_msg>UserIconのshouldComponentUpdateを実装<commit_after>import React from 'react'
import PropTypes from 'prop-types'
import {is} from 'immutable'

import {AccountPropType} from 'src/propTypes'
import {makeFaviconUrl} from 'src/utils'

/**
 * ユーザーの顔アイコン with ホスト
 */
export class UserIconWithHost extends React.Component {
  static propTypes = {
    account: AccountPropType.isRequired,
    size: PropTypes.string,
  }

  /**
   * @override
   */
  shouldComponentUpdate(nextProps, nextState) {
    return (
      this.props.size === nextProps.size &&
      is(this.props.account, nextProps.account)
    ) ? false : true
  }

  /**
   * @override
   */
  render() {
    const {account, size} = this.props
    let className = 'userIcon with-host'

    if(size)
      className += ` size-${size}`

    return (

    )
  }
}
<|endoftext|>


<commit_before>'use strict';

var clone = require('../../utils/object').clone;
var format = require('../../utils/string').format;

function factory (type, config, load, typed) {
  var latex = require('../../utils/latex');

  var matrix = load(require('../../type/matrix/function/matrix'));

  var DenseMatrix = type.DenseMatrix,
      SparseMatrix = type.SparseMatrix;

  /**
   * Transpose a matrix. All values of the matrix are reflected over its
   * main diagonal. Only two dimensional matrices are supported.
   *
   * Syntax:
   *
   *     math.transpose(x)
   *
   * Examples:
   *
   *     var A = [[1, 2, 3], [4, 5, 6]];
   *     math.transpose(A);               // returns [[1, 4], [2, 5], [3, 6]]
   *
   * See also:
   *
   *     diag, inv, subset, squeeze
   *
   * @param {Array | Matrix} x  Matrix to be transposed
   * @return {Array | Matrix}   The transposed matrix
   */
  var transpose = typed('transpose', {

    'Array': function (x) {
      // use dense matrix implementation
      return transpose(matrix(x)).valueOf();
    },

    'Matrix': function (x) {
      // matrix size
      var size = x.size();

      // result
      var c;

      // process dimensions
      switch (size.length) {
        case 1:
          // vector
          c = x.clone();
          break;

        case 2:
          // rows and columns
          var rows = size[0];
          var columns = size[1];

          // check columns
          if (columns === 0) {
            // throw exception
            throw new RangeError('Cannot transpose a 2D matrix with no columns (size: ' + format(size) + ')');
          }

          // process storage format
          switch (x.storage()) {
            case 'dense':
              c = _denseTranspose(x, rows, columns);
              break;
            case 'sparse':
              c = _sparseTranspose(x, rows, columns);
              break;
          }
          break;

        default:
          // multi dimensional
          throw new RangeError('Matrix must be a vector or two dimensional (size: ' + format(this._size) + ')');
      }
      return c;
    },

    // scalars
    'any': function (x) {
      return clone(x);
    }
  });

  var _denseTranspose = function (m, rows, columns) {
    // matrix array
    var data = m._data;
    // transposed matrix data
    var transposed = [];
    var transposedRow;
    // loop columns
    for (var j = 0; j < columns; j++) {
      // initialize row
      transposedRow = transposed[j] = [];
      // loop rows
      for (var i = 0; i < rows; i++) {
        // set data
        transposedRow[i] = clone(data[i][j]);
      }
    }
    // return matrix
    return new DenseMatrix({
      data: transposed,
      size: [columns, rows],
      datatype: m._datatype
    });
  };

  var _sparseTranspose = function (m, rows, columns) {
    // matrix arrays
    var values = m._values;
    var index = m._index;
    var ptr = m._ptr;
    // result matrices
    var cvalues = values ? [] : undefined;
    var cindex = [];
    var cptr = [];
    // row counts
    var w = [];
    for (var x = 0; x < rows; x++)
      w[x] = 0;
    // vars
    var p, l, j;
    // loop values in matrix
    for (p = 0, l = index.length; p < l; p++) {
      // number of values in row
      w[index[p]]++;
    }
    // cumulative sum
    var sum = 0;
    // initialize cptr with the cummulative sum of row counts
    for (var i = 0; i < rows; i++) {
      // update cptr
      cptr.push(sum);
      // update sum
      sum += w[i];
      // update w
      w[i] = cptr[i];
    }
    // update cptr
    cptr.push(sum);
    // loop columns
    for (j = 0; j < columns; j++) {
      // values & index in column
      for (var k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) {
        // C values & index
        var q = w[index[k]]++;
        // C[j, i] = A[i, j]
        cindex[q] = j;
        // check we need to process values (pattern matrix)
        if (values)
          cvalues[q] = clone(values[k]);
      }
    }
    // return matrix
    return new SparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [columns, rows],
      datatype: m._datatype
    });
  };

  transpose.toTex = {1: '\\left(${args[0]}\\right)' + latex.operators['transpose']};

  return transpose;
}

exports.name = 'transpose';
exports.factory = factory;
<commit_msg>Improved docs on transpose function (see #706)<commit_after>'use strict';

var clone = require('../../utils/object').clone;
var format = require('../../utils/string').format;

function factory (type, config, load, typed) {
  var latex = require('../../utils/latex');

  var matrix = load(require('../../type/matrix/function/matrix'));

  var DenseMatrix = type.DenseMatrix,
      SparseMatrix = type.SparseMatrix;

  /**
   * Transpose a matrix. All values of the matrix are reflected over its
   * main diagonal. Only applicable to two dimensional matrices containing
   * a vector (i.e. having size `[1,n]` or `[n,1]`). One dimensional
   * vectors and scalars return the input unchanged.
   *
   * Syntax:
   *
   *     math.transpose(x)
   *
   * Examples:
   *
   *     var A = [[1, 2, 3], [4, 5, 6]];
   *     math.transpose(A);               // returns [[1, 4], [2, 5], [3, 6]]
   *
   * See also:
   *
   *     diag, inv, subset, squeeze
   *
   * @param {Array | Matrix} x  Matrix to be transposed
   * @return {Array | Matrix}   The transposed matrix
   */
  var transpose = typed('transpose', {

    'Array': function (x) {
      // use dense matrix implementation
      return transpose(matrix(x)).valueOf();
    },

    'Matrix': function (x) {
      // matrix size
      var size = x.size();

      // result
      var c;

      // process dimensions
      switch (size.length) {
        case 1:
          // vector
          c = x.clone();
          break;

        case 2:
          // rows and columns
          var rows = size[0];
          var columns = size[1];

          // check columns
          if (columns === 0) {
            // throw exception
            throw new RangeError('Cannot transpose a 2D matrix with no columns (size: ' + format(size) + ')');
          }

          // process storage format
          switch (x.storage()) {
            case 'dense':
              c = _denseTranspose(x, rows, columns);
              break;
            case 'sparse':
              c = _sparseTranspose(x, rows, columns);
              break;
          }
          break;

        default:
          // multi dimensional
          throw new RangeError('Matrix must be a vector or two dimensional (size: ' + format(this._size) + ')');
      }
      return c;
    },

    // scalars
    'any': function (x) {
      return clone(x);
    }
  });

  var _denseTranspose = function (m, rows, columns) {
    // matrix array
    var data = m._data;
    // transposed matrix data
    var transposed = [];
    var transposedRow;
    // loop columns
    for (var j = 0; j < columns; j++) {
      // initialize row
      transposedRow = transposed[j] = [];
      // loop rows
      for (var i = 0; i < rows; i++) {
        // set data
        transposedRow[i] = clone(data[i][j]);
      }
    }
    // return matrix
    return new DenseMatrix({
      data: transposed,
      size: [columns, rows],
      datatype: m._datatype
    });
  };

  var _sparseTranspose = function (m, rows, columns) {
    // matrix arrays
    var values = m._values;
    var index = m._index;
    var ptr = m._ptr;
    // result matrices
    var cvalues = values ? [] : undefined;
    var cindex = [];
    var cptr = [];
    // row counts
    var w = [];
    for (var x = 0; x < rows; x++)
      w[x] = 0;
    // vars
    var p, l, j;
    // loop values in matrix
    for (p = 0, l = index.length; p < l; p++) {
      // number of values in row
      w[index[p]]++;
    }
    // cumulative sum
    var sum = 0;
    // initialize cptr with the cummulative sum of row counts
    for (var i = 0; i < rows; i++) {
      // update cptr
      cptr.push(sum);
      // update sum
      sum += w[i];
      // update w
      w[i] = cptr[i];
    }
    // update cptr
    cptr.push(sum);
    // loop columns
    for (j = 0; j < columns; j++) {
      // values & index in column
      for (var k0 = ptr[j], k1 = ptr[j + 1], k = k0; k < k1; k++) {
        // C values & index
        var q = w[index[k]]++;
        // C[j, i] = A[i, j]
        cindex[q] = j;
        // check we need to process values (pattern matrix)
        if (values)
          cvalues[q] = clone(values[k]);
      }
    }
    // return matrix
    return new SparseMatrix({
      values: cvalues,
      index: cindex,
      ptr: cptr,
      size: [columns, rows],
      datatype: m._datatype
    });
  };

  transpose.toTex = {1: '\\left(${args[0]}\\right)' + latex.operators['transpose']};

  return transpose;
}

exports.name = 'transpose';
exports.factory = factory;
<|endoftext|>


<commit_before>(function () {
  // Obtain ALL anchors on the page.
  var links = document.links;

  // The previous/next urls if they exist.
  var prev = findHref(/(prev|back)/i);
  var next = findHref(/(next|forward)/i);

  // The first/last urls if they exist.
  var first = findHref(/(first|start|oldest)/i);
  var last = findHref(/(last|end|newest|latest)/i);

  /**
   * Find the href for a given name.
   * @param {String} name - The name of the anchor to search for.
   * @return {String} The href for a given tag, otherwise an empty string.
   */
  function findHref(name) {
    for (var index = 0; index < links.length; ++index) {
      // The complete anchor HTML element (<a>).
      var anchor = links[index];
      // Does the name exist in the anchor?
      if (isNameInAnchor(name, anchor.className) ||
          isNameInAnchor(name, anchor.rel) ||
          isNameInAnchor(name, anchor.text))
      {
        return anchor.href
      }
    }
  }

  /**
   * Does the word exist in a given element?
   * @param {String} name - The name to search for.
   * @param {String} element - The element to search in.
   * @return {Boolean} True if the name exists in the element, otherwise false.
   */
  function isNameInAnchor(name, element) {
    return element !== void 0 && element.search(name) >= 0;
  }

  // Go to the next/previous pages using the arrow keys.
  document.addEventListener('keydown', function(event) {
    if (event.keyCode !== 37 && event.keyCode !== 39) {
      return;
    }

    var key = (event.shiftKey && "shift_" || "") + event.keyCode,
      navTo = {
        "37": prev,
        "39": next,
        "shift_37": first,
        "shift_39": last
      }[key];

    if (navTo) {
      window.location = navTo;
    }
  });
})();<commit_msg>remove extra var statements<commit_after>(function () {
  // Obtain ALL anchors on the page.
  var links = document.links,

  // The previous/next urls if they exist.
      prev = findHref(/(prev|back)/i),
      next = findHref(/(next|forward)/i),

  // The first/last urls if they exist.
      first = findHref(/(first|start|oldest)/i),
      last = findHref(/(last|end|newest|latest)/i);

  /**
   * Find the href for a given name.
   * @param {String} name - The name of the anchor to search for.
   * @return {String} The href for a given tag, otherwise an empty string.
   */
  function findHref(name) {
    for (var index = 0; index < links.length; ++index) {
      // The complete anchor HTML element (<a>).
      var anchor = links[index];
      // Does the name exist in the anchor?
      if (isNameInAnchor(name, anchor.className) ||
          isNameInAnchor(name, anchor.rel) ||
          isNameInAnchor(name, anchor.text))
      {
        return anchor.href
      }
    }
  }

  /**
   * Does the word exist in a given element?
   * @param {String} name - The name to search for.
   * @param {String} element - The element to search in.
   * @return {Boolean} True if the name exists in the element, otherwise false.
   */
  function isNameInAnchor(name, element) {
    return element !== void 0 && element.search(name) >= 0;
  }

  // Go to the next/previous pages using the arrow keys.
  document.addEventListener('keydown', function(event) {
    if (event.keyCode !== 37 && event.keyCode !== 39) {
      return;
    }

    var key = (event.shiftKey && "shift_" || "") + event.keyCode,
      navTo = {
        "37": prev,
        "39": next,
        "shift_37": first,
        "shift_39": last
      }[key];

    if (navTo) {
      window.location = navTo;
    }
  });
})();
<|endoftext|>


<commit_before>/*global chai, sinon, ports:true, Port, PortCollection, handlers,
  _currentUserData:true, currentConversation:true, UserData,
  _presenceSocket:true, browserPort:true, currentUsers:true,
  Conversation, _config:true, _loginPending:true, _autologinPending: true,
  _cookieNickname:true, Server, server:true, _signinCallback */
/* jshint expr:true */

var expect = chai.expect;

describe('handlers', function() {
  var sandbox;

  beforeEach(function() {
    sandbox = sinon.sandbox.create();
    server = new Server({});
  });

  afterEach(function() {
    sandbox.restore();
  });

  describe("social.port-closing", function() {
    var port;

    beforeEach(function() {
      ports = new PortCollection();
      port = new Port({_portid: 42});
      ports.add(port);

      browserPort = {postEvent: sandbox.spy()};
    });

    afterEach(function() {
      currentConversation = undefined;
    });

    it("should remove a closed port on receiving social.port-closing",
      function() {
        handlers['social.port-closing'].bind(port)();
        expect(Object.keys(ports.ports)).to.have.length.of(0);
      });

    it("should clear the current conversation on receiving " +
       "social.port-closing for the conversation port", function() {
        currentConversation = new Conversation();
        currentConversation.port = port;

        handlers['social.port-closing'].bind(port)();
        expect(currentConversation).to.be.equal(undefined);
      });
  });

  describe("social.cookies-get-response", function() {
    var oldConfig;

    beforeEach(function() {
      oldConfig = _config;
      _cookieNickname = undefined;
    });

    afterEach(function() {
      _config = oldConfig;
      _cookieNickname = undefined;
    });

    it("should try to connect the presence socket",
      function() {
        _currentUserData = {};
        sandbox.stub(server, "autoconnect");
        var event = {
          data: [ {name: "nick", value: "Boriss"} ]
        };

        handlers['social.cookies-get-response'](event);

        sinon.assert.calledOnce(server.autoconnect);
        sinon.assert.calledWithExactly(server.autoconnect, "Boriss");
      });
  });

  describe("talkilla.login", function() {
    var xhr, rootURL, socketStub, requests;

    beforeEach(function() {
      socketStub = sinon.stub(server, "connect");
      // XXX For some reason, sandbox.useFakeXMLHttpRequest doesn't want to work
      // nicely so we have to manually xhr.restore for now.
      xhr = sinon.useFakeXMLHttpRequest();
      requests = [];
      xhr.onCreate = function (req) { requests.push(req); };

      rootURL = 'http://fake';
      _currentUserData = new UserData({}, {
        ROOTURL: rootURL
      });
      sandbox.stub(_currentUserData, "send");
      _loginPending = _autologinPending = false;
    });

    afterEach(function() {
      _currentUserData = undefined;
      xhr.restore();
      socketStub.restore();
    });

    it("should call postEvent with a failure message if I pass in bad data",
      function() {
        handlers.postEvent = sandbox.spy();
        handlers['talkilla.login']({topic: "talkilla.login", data: null});
        sinon.assert.calledOnce(handlers.postEvent);
        sinon.assert.calledWith(handlers.postEvent, "talkilla.login-failure");
      });

    it("should call postEvent with a pending message if I pass in valid data",
      function() {
        handlers.postEvent = sandbox.spy();
        handlers['talkilla.login']({
          topic: "talkilla.login",
          data: {assertion: "fake assertion"}
        });
        sinon.assert.calledOnce(handlers.postEvent);
        sinon.assert.calledWith(handlers.postEvent, "talkilla.login-pending");
      });

    it("should post an ajax message to the server if I pass valid login data",
      function() {
        handlers['talkilla.login']({
          topic: "talkilla.login",
          data: {assertion: "fake assertion"}
        });
        expect(requests.length).to.equal(1);
        expect(requests[0].url).to.equal('/signin');
        expect(requests[0].requestBody).to.be.not.empty;
        expect(requests[0].requestBody)
          .to.be.equal('{"assertion":"fake assertion"}');
      });

    it("should not do anything if a login is already pending", function() {
      _loginPending = true;
      sandbox.stub(window, "_signinCallback");
      handlers.postEvent = sandbox.spy();

      handlers['talkilla.login']({
        topic: "talkilla.login",
        data: {assertion: "fake assertion"}
      });

      sinon.assert.notCalled(handlers.postEvent);
      sinon.assert.notCalled(_signinCallback);
    });

    it("should not do anything if an auto login is already pending",
      function() {
        _autologinPending = true;
        sandbox.stub(window, "_signinCallback");
        handlers.postEvent = sandbox.spy();

        handlers['talkilla.login']({
          topic: "talkilla.login",
          data: {assertion: "fake assertion"}
        });

        sinon.assert.notCalled(handlers.postEvent);
        sinon.assert.notCalled(_signinCallback);
      });

    describe("Accepted Login", function() {
      var port;

      beforeEach(function() {
        port = {id: "tests", postEvent: sandbox.spy()};
        ports.add(port);

        handlers['talkilla.login']({
          topic: "talkilla.login",
          data: {assertion: "fake assertion"}
        });
        expect(requests.length).to.equal(1);

        requests[0].respond(200, { 'Content-Type': 'application/json' },
          '{"nick":"jb"}' );
      });

      afterEach(function() {
        ports.remove(port);
      });

      it("should store the userName if the server accepted login", function() {
        expect(_currentUserData.userName).to.be.equal("jb");
      });

      it("should set the current user name if the server accepted login",
        function() {
          sinon.assert.calledOnce(_currentUserData.send);
        });

      it("should store the username if the server accepted login",
        function() {
          expect(_currentUserData.userName).to.equal('jb');
        });
    });

    it("should notify new sidebars of the logged in user",
      function() {
        _currentUserData.userName = "jb";
        handlers.postEvent = sinon.spy();
        handlers['talkilla.sidebar-ready']({
          topic: "talkilla.sidebar-ready",
          data: {}
        });

        sinon.assert.calledOnce(handlers.postEvent);
        sinon.assert.calledWith(handlers.postEvent, "talkilla.login-success");
      });

    it("should notify new sidebars of current users",
      function() {
        _currentUserData.userName = "jb";
        _presenceSocket = {send: sinon.spy()};
        currentUsers = {};
        handlers.postEvent = sinon.spy();
        handlers['talkilla.presence-request']({
          topic: "talkilla.presence-request",
          data: {}
        });

        sinon.assert.calledWith(handlers.postEvent, "talkilla.users");
      });

    it("should request for the initial presence state" +
       "if there is no current users", function() {
        currentUsers = undefined;
        sandbox.stub(server, "send");
        handlers['talkilla.presence-request']({
          topic: "talkilla.presence-request",
          data: {}
        });

        sinon.assert.calledOnce(server.send);
        sinon.assert.calledWithExactly(server.send,
                                       {"presence_request": null});
      });

    it("should notify new sidebars only if there's a logged in user",
      function() {
        handlers.postEvent = sinon.spy();
        handlers['talkilla.sidebar-ready']({
          topic: "talkilla.sidebar-ready",
          data: {}
        });

        sinon.assert.notCalled(handlers.postEvent);
      });

    it("should post a fail message if the server rejected login",
      function() {
        handlers.postEvent = sinon.spy();
        handlers['talkilla.login']({
          topic: "talkilla.login",
          data: {assertion: "fake assertion"}
        });
        expect(requests.length).to.equal(1);

        requests[0].respond(401, {'Content-Type': 'text/plain'},
                            JSON.stringify({error: "some error"}));

        sinon.assert.calledTwice(handlers.postEvent);
        sinon.assert.calledWith(handlers.postEvent, "talkilla.login-failure");
      });
  });

  describe("talkilla.logout", function() {
    var xhr, requests;

    beforeEach(function() {
      // XXX For some reason, sandbox.useFakeXMLHttpRequest doesn't want to work
      // nicely so we have to manually xhr.restore for now.
      xhr = sinon.useFakeXMLHttpRequest();
      requests = [];
      xhr.onCreate = function (req) { requests.push(req); };

      sandbox.stub(UserData.prototype, "send");
      _currentUserData = new UserData({userName: 'romain'}, {});
      _presenceSocket = { close: sandbox.stub() };
    });

    afterEach(function() {
      _presenceSocket = undefined;
      _currentUserData = undefined;
      xhr.restore();
    });

    it("should post an ajax message to the server",
      function() {
        sandbox.stub(server, "signout");
        handlers['talkilla.logout']({
          topic: 'talkilla.logout'
        });
        sinon.assert.calledOnce(server.signout);
      });

    describe("Success logout", function() {
      var port;

      beforeEach(function () {
        port = {id: "tests", postEvent: sandbox.spy()};
        ports.add(port);

        sandbox.stub(_currentUserData, "reset");

        handlers['talkilla.logout']({
          topic: 'talkilla.logout'
        });

        requests[0].respond(200, { 'Content-Type': 'text/plain' },
          'OK' );
      });

      afterEach(function() {
        ports.remove(port);
      });

      it("should post a success message",
        function() {
          sinon.assert.calledOnce(port.postEvent);
          sinon.assert.calledWith(port.postEvent, 'talkilla.logout-success');
          ports.remove(port);
        });

      it("should reset the current user data", function() {
        sinon.assert.calledOnce(_currentUserData.reset);
      });
    });

    it("should log failure, if the server failed to sign the user out",
      function() {
        handlers.postEvent = sandbox.spy();
        handlers['talkilla.logout']({
          topic: 'talkilla.logout'
        });

        expect(requests.length).to.equal(1);

        requests[0].respond(401, { 'Content-Type': 'text/plain' },
                            'Not Authorised' );

        sinon.assert.calledOnce(handlers.postEvent);
        sinon.assert.calledWith(handlers.postEvent, 'talkilla.error');
      });
  });

  describe("talkilla.conversation-open", function() {
    beforeEach(function() {
      browserPort = {postEvent: sandbox.spy()};
    });

    afterEach(function() {
      currentConversation = undefined;
      browserPort = undefined;
    });

    it("should create a new conversation object when receiving a " +
       "talkilla.conversation-open event", function() {
        handlers.postEvent = sinon.spy();
        handlers['talkilla.conversation-open']({
          topic: "talkilla.conversation-open",
          data: {}
        });

        expect(currentConversation).to.be.an.instanceOf(Conversation);
      });
  });

  describe("talkilla.chat-window-ready", function() {
    beforeEach(function() {
      browserPort = {postEvent: sandbox.spy()};
      _currentUserData = new UserData();
      currentConversation = {
        windowOpened: sandbox.spy()
      };
    });

    afterEach(function() {
      currentConversation = undefined;
      _currentUserData = undefined;
      browserPort = undefined;
    });

    it("should tell the conversation the window has opened when " +
      "receiving a talkilla.chat-window-ready",
      function () {
        var chatAppPort = {postEvent: sinon.spy()};
        _currentUserData.userName = "bob";

        handlers['talkilla.chat-window-ready'].bind(chatAppPort)({
          topic: "talkilla.chat-window-ready",
          data: {}
        });

        sinon.assert.called(currentConversation.windowOpened);
        sinon.assert.calledWithExactly(currentConversation.windowOpened,
          chatAppPort);
      });
  });

  describe("talkilla.sidebar-ready", function() {

    beforeEach(function() {
      _currentUserData = new UserData();
    });

    afterEach(function() {
      _currentUserData = undefined;
    });

    it("should NOT try to connect if there is no nick provided",
      function () {
        sandbox.stub(server, "autoconnect");

        handlers['talkilla.sidebar-ready']({
          topic: "talkilla.sidebar-ready",
          data: {}
        });

        sinon.assert.notCalled(server.autoconnect);
      });
  });

  describe("talkilla.call-offer", function() {
    it("should send a websocket message when receiving talkilla.call-offer",
      function() {
        sandbox.stub(server, "send");
        var data = {
          peer: "tom",
          offer: { sdp: "sdp", type: "type" }
        };

        handlers['talkilla.call-offer']({
          topic: "talkilla.call-offer",
          data: data
        });

        sinon.assert.calledOnce(server.send);
        sinon.assert.calledWithExactly(server.send, {'call_offer': data });
      });
  });

  describe("talkilla.call-answer", function() {
    it("should send a websocket message when receiving talkilla.call-answer",
      function() {
        sandbox.stub(server, "send");
        var data = {
          peer: "fred",
          offer: { sdp: "sdp", type: "type" }
        };

        handlers['talkilla.call-answer']({
          topic: "talkilla.call-answer",
          data: data
        });

        sinon.assert.calledOnce(server.send);
        sinon.assert.calledWithExactly(server.send, { 'call_accepted': data });
      });
  });

  describe("talkilla.call-hangup", function() {
    afterEach(function() {
      currentConversation = undefined;
    });

    it("should send a websocket message when receiving talkilla.call-hangup",
      function() {
        sandbox.stub(server, "send");
        var data = {
          peer: "florian"
        };

        handlers['talkilla.call-hangup']({
          topic: "talkilla.call-hangup",
          data: data
        });

        sinon.assert.calledOnce(server.send);
        sinon.assert.calledWithExactly(server.send, { 'call_hangup': data });
      });
  });

});
<commit_msg>Rearrange some frontend tests so that they are in a relevant describe section, and make the server autoconnect test test against the correct function.<commit_after>/*global chai, sinon, ports:true, Port, PortCollection, handlers,
  _currentUserData:true, currentConversation:true, UserData,
  _presenceSocket:true, browserPort:true, currentUsers:true,
  Conversation, _config:true, _loginPending:true, _autologinPending: true,
  _cookieNickname:true, Server, server:true, _signinCallback */
/* jshint expr:true */

var expect = chai.expect;

describe('handlers', function() {
  var sandbox;

  beforeEach(function() {
    sandbox = sinon.sandbox.create();
    server = new Server({});
  });

  afterEach(function() {
    sandbox.restore();
  });

  describe("social.port-closing", function() {
    var port;

    beforeEach(function() {
      ports = new PortCollection();
      port = new Port({_portid: 42});
      ports.add(port);

      browserPort = {postEvent: sandbox.spy()};
    });

    afterEach(function() {
      currentConversation = undefined;
    });

    it("should remove a closed port on receiving social.port-closing",
      function() {
        handlers['social.port-closing'].bind(port)();
        expect(Object.keys(ports.ports)).to.have.length.of(0);
      });

    it("should clear the current conversation on receiving " +
       "social.port-closing for the conversation port", function() {
        currentConversation = new Conversation();
        currentConversation.port = port;

        handlers['social.port-closing'].bind(port)();
        expect(currentConversation).to.be.equal(undefined);
      });
  });

  describe("social.cookies-get-response", function() {
    var oldConfig;

    beforeEach(function() {
      oldConfig = _config;
      _cookieNickname = undefined;
    });

    afterEach(function() {
      _config = oldConfig;
      _cookieNickname = undefined;
    });

    it("should try to connect the presence socket",
      function() {
        _currentUserData = {};
        sandbox.stub(server, "autoconnect");
        var event = {
          data: [ {name: "nick", value: "Boriss"} ]
        };

        handlers['social.cookies-get-response'](event);

        sinon.assert.calledOnce(server.autoconnect);
        sinon.assert.calledWithExactly(server.autoconnect, "Boriss");
      });

    it("should NOT try to connect if there is no nick provided",
      function () {
        sandbox.stub(server, "autoconnect");

        handlers['social.cookies-get-response']({
          topic: "social.cookies-get-response",
          data: []
        });

        sinon.assert.notCalled(server.autoconnect);
      });

  });

  describe("talkilla.login", function() {
    var xhr, rootURL, socketStub, requests;

    beforeEach(function() {
      socketStub = sinon.stub(server, "connect");
      // XXX For some reason, sandbox.useFakeXMLHttpRequest doesn't want to work
      // nicely so we have to manually xhr.restore for now.
      xhr = sinon.useFakeXMLHttpRequest();
      requests = [];
      xhr.onCreate = function (req) { requests.push(req); };

      rootURL = 'http://fake';
      _currentUserData = new UserData({}, {
        ROOTURL: rootURL
      });
      sandbox.stub(_currentUserData, "send");
      _loginPending = _autologinPending = false;
    });

    afterEach(function() {
      _currentUserData = undefined;
      xhr.restore();
      socketStub.restore();
    });

    it("should call postEvent with a pending message if I pass in valid data",
      function() {
        handlers.postEvent = sandbox.spy();
        handlers['talkilla.login']({
          topic: "talkilla.login",
          data: {assertion: "fake assertion"}
        });
        sinon.assert.calledOnce(handlers.postEvent);
        sinon.assert.calledWith(handlers.postEvent, "talkilla.login-pending");
      });

    it("should post an ajax message to the server if I pass valid login data",
      function() {
        handlers['talkilla.login']({
          topic: "talkilla.login",
          data: {assertion: "fake assertion"}
        });
        expect(requests.length).to.equal(1);
        expect(requests[0].url).to.equal('/signin');
        expect(requests[0].requestBody).to.be.not.empty;
        expect(requests[0].requestBody)
          .to.be.equal('{"assertion":"fake assertion"}');
      });

    it("should not do anything if a login is already pending", function() {
      _loginPending = true;
      sandbox.stub(window, "_signinCallback");
      handlers.postEvent = sandbox.spy();

      handlers['talkilla.login']({
        topic: "talkilla.login",
        data: {assertion: "fake assertion"}
      });

      sinon.assert.notCalled(handlers.postEvent);
      sinon.assert.notCalled(_signinCallback);
    });

    it("should not do anything if an auto login is already pending",
      function() {
        _autologinPending = true;
        sandbox.stub(window, "_signinCallback");
        handlers.postEvent = sandbox.spy();

        handlers['talkilla.login']({
          topic: "talkilla.login",
          data: {assertion: "fake assertion"}
        });

        sinon.assert.notCalled(handlers.postEvent);
        sinon.assert.notCalled(_signinCallback);
      });

    describe("Failed login", function() {
      it("should call postEvent with a failure message if I pass in bad data",
        function() {
          handlers.postEvent = sandbox.spy();
          handlers['talkilla.login']({topic: "talkilla.login", data: null});
          sinon.assert.calledOnce(handlers.postEvent);
          sinon.assert.calledWith(handlers.postEvent, "talkilla.login-failure");
        });

      it("should post a fail message if the server rejected login",
        function() {
          handlers.postEvent = sinon.spy();
          handlers['talkilla.login']({
            topic: "talkilla.login",
            data: {assertion: "fake assertion"}
          });
          expect(requests.length).to.equal(1);

          requests[0].respond(401, {'Content-Type': 'text/plain'},
                              JSON.stringify({error: "some error"}));

          sinon.assert.calledTwice(handlers.postEvent);
          sinon.assert.calledWith(handlers.postEvent, "talkilla.login-failure");
        });
    });

    describe("Accepted Login", function() {
      var port;

      beforeEach(function() {
        port = {id: "tests", postEvent: sandbox.spy()};
        ports.add(port);

        handlers['talkilla.login']({
          topic: "talkilla.login",
          data: {assertion: "fake assertion"}
        });
        expect(requests.length).to.equal(1);

        requests[0].respond(200, { 'Content-Type': 'application/json' },
          '{"nick":"jb"}' );
      });

      afterEach(function() {
        ports.remove(port);
      });

      it("should store the userName if the server accepted login", function() {
        expect(_currentUserData.userName).to.be.equal("jb");
      });

      it("should set the current user name if the server accepted login",
        function() {
          sinon.assert.calledOnce(_currentUserData.send);
        });

      it("should store the username if the server accepted login",
        function() {
          expect(_currentUserData.userName).to.equal('jb');
        });
    });
  });

  describe("talkilla.logout", function() {
    var xhr, requests;

    beforeEach(function() {
      // XXX For some reason, sandbox.useFakeXMLHttpRequest doesn't want to work
      // nicely so we have to manually xhr.restore for now.
      xhr = sinon.useFakeXMLHttpRequest();
      requests = [];
      xhr.onCreate = function (req) { requests.push(req); };

      sandbox.stub(UserData.prototype, "send");
      _currentUserData = new UserData({userName: 'romain'}, {});
      _presenceSocket = { close: sandbox.stub() };
    });

    afterEach(function() {
      _presenceSocket = undefined;
      _currentUserData = undefined;
      xhr.restore();
    });

    it("should post an ajax message to the server",
      function() {
        sandbox.stub(server, "signout");
        handlers['talkilla.logout']({
          topic: 'talkilla.logout'
        });
        sinon.assert.calledOnce(server.signout);
      });

    describe("Success logout", function() {
      var port;

      beforeEach(function () {
        port = {id: "tests", postEvent: sandbox.spy()};
        ports.add(port);

        sandbox.stub(_currentUserData, "reset");

        handlers['talkilla.logout']({
          topic: 'talkilla.logout'
        });

        requests[0].respond(200, { 'Content-Type': 'text/plain' },
          'OK' );
      });

      afterEach(function() {
        ports.remove(port);
      });

      it("should post a success message",
        function() {
          sinon.assert.calledOnce(port.postEvent);
          sinon.assert.calledWith(port.postEvent, 'talkilla.logout-success');
          ports.remove(port);
        });

      it("should reset the current user data", function() {
        sinon.assert.calledOnce(_currentUserData.reset);
      });
    });

    it("should log failure, if the server failed to sign the user out",
      function() {
        handlers.postEvent = sandbox.spy();
        handlers['talkilla.logout']({
          topic: 'talkilla.logout'
        });

        expect(requests.length).to.equal(1);

        requests[0].respond(401, { 'Content-Type': 'text/plain' },
                            'Not Authorised' );

        sinon.assert.calledOnce(handlers.postEvent);
        sinon.assert.calledWith(handlers.postEvent, 'talkilla.error');
      });
  });

  describe("talkilla.conversation-open", function() {
    beforeEach(function() {
      browserPort = {postEvent: sandbox.spy()};
    });

    afterEach(function() {
      currentConversation = undefined;
      browserPort = undefined;
    });

    it("should create a new conversation object when receiving a " +
       "talkilla.conversation-open event", function() {
        handlers.postEvent = sinon.spy();
        handlers['talkilla.conversation-open']({
          topic: "talkilla.conversation-open",
          data: {}
        });

        expect(currentConversation).to.be.an.instanceOf(Conversation);
      });
  });

  describe("talkilla.chat-window-ready", function() {
    beforeEach(function() {
      browserPort = {postEvent: sandbox.spy()};
      _currentUserData = new UserData();
      currentConversation = {
        windowOpened: sandbox.spy()
      };
    });

    afterEach(function() {
      currentConversation = undefined;
      _currentUserData = undefined;
      browserPort = undefined;
    });

    it("should tell the conversation the window has opened when " +
      "receiving a talkilla.chat-window-ready",
      function () {
        var chatAppPort = {postEvent: sinon.spy()};
        _currentUserData.userName = "bob";

        handlers['talkilla.chat-window-ready'].bind(chatAppPort)({
          topic: "talkilla.chat-window-ready",
          data: {}
        });

        sinon.assert.called(currentConversation.windowOpened);
        sinon.assert.calledWithExactly(currentConversation.windowOpened,
          chatAppPort);
      });
  });

  describe("talkilla.sidebar-ready", function() {

    beforeEach(function() {
      _currentUserData = new UserData();
      sandbox.stub(_currentUserData, "send");
    });

    afterEach(function() {
      _currentUserData = undefined;
    });

    it("should notify new sidebars of the logged in user",
      function() {
        _currentUserData.userName = "jb";
        handlers.postEvent = sinon.spy();
        handlers['talkilla.sidebar-ready']({
          topic: "talkilla.sidebar-ready",
          data: {}
        });

        sinon.assert.calledOnce(handlers.postEvent);
        sinon.assert.calledWith(handlers.postEvent, "talkilla.login-success");
      });

    it("should notify new sidebars only if there's a logged in user",
      function() {
        handlers.postEvent = sinon.spy();
        handlers['talkilla.sidebar-ready']({
          topic: "talkilla.sidebar-ready",
          data: {}
        });

        sinon.assert.notCalled(handlers.postEvent);
      });

  });

  describe("talkilla.presence-request", function () {
    beforeEach(function() {
      _currentUserData = new UserData();
      sandbox.stub(_currentUserData, "send");
    });

    afterEach(function() {
      _currentUserData = null;
    });

    it("should notify new sidebars of current users",
      function() {
        _currentUserData.userName = "jb";
        _presenceSocket = {send: sinon.spy()};
        currentUsers = {};
        handlers.postEvent = sinon.spy();
        handlers['talkilla.presence-request']({
          topic: "talkilla.presence-request",
          data: {}
        });

        sinon.assert.calledWith(handlers.postEvent, "talkilla.users");
      });

    it("should request for the initial presence state" +
       "if there is no current users", function() {
        currentUsers = undefined;
        sandbox.stub(server, "send");
        handlers['talkilla.presence-request']({
          topic: "talkilla.presence-request",
          data: {}
        });

        sinon.assert.calledOnce(server.send);
        sinon.assert.calledWithExactly(server.send,
                                       {"presence_request": null});
      });
  });

  describe("talkilla.call-offer", function() {
    it("should send a websocket message when receiving talkilla.call-offer",
      function() {
        sandbox.stub(server, "send");
        var data = {
          peer: "tom",
          offer: { sdp: "sdp", type: "type" }
        };

        handlers['talkilla.call-offer']({
          topic: "talkilla.call-offer",
          data: data
        });

        sinon.assert.calledOnce(server.send);
        sinon.assert.calledWithExactly(server.send, {'call_offer': data });
      });
  });

  describe("talkilla.call-answer", function() {
    it("should send a websocket message when receiving talkilla.call-answer",
      function() {
        sandbox.stub(server, "send");
        var data = {
          peer: "fred",
          offer: { sdp: "sdp", type: "type" }
        };

        handlers['talkilla.call-answer']({
          topic: "talkilla.call-answer",
          data: data
        });

        sinon.assert.calledOnce(server.send);
        sinon.assert.calledWithExactly(server.send, { 'call_accepted': data });
      });
  });

  describe("talkilla.call-hangup", function() {
    afterEach(function() {
      currentConversation = undefined;
    });

    it("should send a websocket message when receiving talkilla.call-hangup",
      function() {
        sandbox.stub(server, "send");
        var data = {
          peer: "florian"
        };

        handlers['talkilla.call-hangup']({
          topic: "talkilla.call-hangup",
          data: data
        });

        sinon.assert.calledOnce(server.send);
        sinon.assert.calledWithExactly(server.send, { 'call_hangup': data });
      });
  });

});
<|endoftext|>


<commit_before>(function () {
  'use strict'
  let queries = {}
  window.location.search.substr(1).split('&').forEach(function (item) {
    let tmp = item.split('=')
    queries[tmp[0]] = tmp[1]
  })
  const keyword = queries.q
  let topbar = document.getElementById('topabar')
  let ivySearchContainer = document.createElement('div')
  ivySearchContainer.style.margin = '0 20px'
  ivySearchContainer.style.borderBottom = '1px solid rgba(0,0,0,0.07)'
  topbar.appendChild(ivySearchContainer)

  let header = document.createElement('div')
  header.style.fontSize = '18px'
  header.style.marginBottom = '10px'
  const pageUrl = `https://gyazo.com/search/${keyword}`
  header.innerHTML = `<span>IvySearch</span> <a href='${pageUrl}' target='_blank'>see more result</a>`
  ivySearchContainer.appendChild(header)

  chrome.runtime.sendMessage({keyword}, function (response) {
    JSON.parse(response).slice(0, 24).forEach(function (item) {
      let imageContainer = document.createElement('div')
      imageContainer.style.float = 'left'
      imageContainer.style.margin = '0 3px'
      imageContainer.innerHTML = `

      `
      ivySearchContainer.appendChild(imageContainer)
    })

    let clearDiv = document.createElement('div')
    clearDiv.style.clear = 'both'
    ivySearchContainer.appendChild(clearDiv)
  })
})()
<commit_msg>:art:<commit_after>(function () {
  'use strict'
  let queries = {}
  let topbar = document.getElementById('topabar')
  if (!topbar) {
    return false
  }
  window.location.search.substr(1).split('&').forEach(function (item) {
    let tmp = item.split('=')
    queries[tmp[0]] = tmp[1]
  })
  const keyword = queries.q
  let ivySearchContainer = document.createElement('div')
  ivySearchContainer.style.margin = '0 20px'
  ivySearchContainer.style.borderBottom = '1px solid rgba(0, 0, 0, 0.07)'
  ivySearchContainer.style.paddingBottom = '5px'
  topbar.appendChild(ivySearchContainer)

  let header = document.createElement('div')
  header.style.fontSize = '18px'
  header.style.marginBottom = '10px'
  const pageUrl = `https://gyazo.com/search/${keyword}`
  header.innerHTML = `
    IvySearch

      see more result

      Inserted by Gyoogle Extension
    `
  ivySearchContainer.appendChild(header)

  let imageListContainer = document.createElement('div')
  imageListContainer.style.height = '110px'
  imageListContainer.style.overflowY = 'scroll'
  ivySearchContainer.appendChild(imageListContainer)

  chrome.runtime.sendMessage({keyword}, function (response) {
    JSON.parse(response).slice(0, 24).forEach(function (item) {
      let imageContainer = document.createElement('span')
      imageContainer.style.margin = '0 3px'
      imageContainer.innerHTML = `

      `
      imageListContainer.appendChild(imageContainer)
    })
  })
})()
<|endoftext|>


<commit_before>"use strict";

const Generator = require("yeoman-generator");
const chalk = require("chalk");
const logSymbols = require("log-symbols");

const createCommonsChunkPlugin = require("webpack-addons")
	.createCommonsChunkPlugin;

const Input = require("webpack-addons").Input;
const Confirm = require("webpack-addons").Confirm;
const List = require("webpack-addons").List;

const getPackageManager = require("../utils/package-manager").getPackageManager;

const entryQuestions = require("./utils/entry");
const getBabelPlugin = require("./utils/module");
const getDefaultPlugins = require("./utils/plugins");
const tooltip = require("./utils/tooltip");

module.exports = class WebpackGenerator extends Generator {
	constructor(args, opts) {
		super(args, opts);
		this.isProd = false;
		this.dependencies = ["webpack", "uglifyjs-webpack-plugin"];
		this.configuration = {
			config: {
				webpackOptions: {},
				topScope: []
			}
		};
	}
	prompting() {
		let done = this.async();
		let self = this;
		let oneOrMoreEntries;
		let regExpForStyles;
		let ExtractUseProps;
		let outputPath = "dist";
		process.stdout.write(
			"\n" +
				logSymbols.info +
				chalk.blue(" INFO ") +
				"For more information and a detailed description of each question, have a look at " +
				chalk.bold.green(
					"https://github.com/webpack/webpack-cli/blob/master/INIT.md"
				) +
				"\n"
		);
		process.stdout.write(
			logSymbols.info +
				chalk.blue(" INFO ") +
				"Alternatively, run `webpack-cli --help` for usage info." +
				"\n\n"
		);
		this.configuration.config.webpackOptions.module = {
			rules: []
		};
		this.configuration.config.webpackOptions.plugins = getDefaultPlugins();
		this.configuration.config.topScope.push(
			"const webpack = require('webpack')",
			"const path = require('path')",
			tooltip.uglify(),
			"const UglifyJSPlugin = require('uglifyjs-webpack-plugin');",
			"\n"
		);

		this.prompt([
			Confirm("entryType", "Will your application have multiple bundles?")
		])
			.then(entryTypeAnswer => {
				// Ask different questions for entry points
				return entryQuestions(self, entryTypeAnswer);
			})
			.then(entryOptions => {
				this.configuration.config.webpackOptions.entry = entryOptions;
				oneOrMoreEntries = Object.keys(entryOptions);

				return this.prompt([
					Input(
						"outputType",
						"Which folder will your generated bundles be in? [default: dist]:"
					)
				]);
			})
			.then(outputTypeAnswer => {
				if (!this.configuration.config.webpackOptions.entry.length) {
					this.configuration.config.topScope.push(tooltip.commonsChunk());
					this.configuration.config.webpackOptions.output = {
						filename: "'[name].[chunkhash].js'",
						chunkFilename: "'[name].[chunkhash].js'"
					};
				} else {
					this.configuration.config.webpackOptions.output = {
						filename: "'[name].bundle.js'"
					};
				}
				if (outputTypeAnswer["outputType"].length) {
					outputPath = outputTypeAnswer["outputType"];
				}
				this.configuration.config.webpackOptions.output.path = `path.resolve(__dirname, '${outputPath}')`;
			})
			.then(() => {
				return this.prompt([
					Confirm("prodConfirm", "Are you going to use this in production?")
				]);
			})
			.then(prodAnswer => {
				if (prodAnswer["prodConfirm"] === true) {
					this.isProd = true;
				} else {
					this.isProd = false;
				}
			})
			.then(() => {
				return this.prompt([
					Confirm("babelConfirm", "Will you be using ES2015?")
				]);
			})
			.then(ans => {
				if (ans["babelConfirm"] === true) {
					this.configuration.config.webpackOptions.module.rules.push(
						getBabelPlugin()
					);
					this.dependencies.push(
						"babel-loader",
						"babel-core",
						"babel-preset-env"
					);
				}
			})
			.then(() => {
				return this.prompt([
					List("stylingType", "Will you use one of the below CSS solutions?", [
						"SASS",
						"LESS",
						"CSS",
						"PostCSS",
						"No"
					])
				]);
			})
			.then(stylingAnswer => {
				if (!this.isProd) {
					ExtractUseProps = [];
				}
				switch (stylingAnswer["stylingType"]) {
					case "SASS":
						this.dependencies.push(
							"sass-loader",
							"node-sass",
							"style-loader",
							"css-loader"
						);
						regExpForStyles = new RegExp(/\.(scss|css)$/);
						if (this.isProd) {
							ExtractUseProps = `
								use: [{
									loader: "css-loader",
									options: {
										sourceMap: true
									}
								}, {
									loader: "sass-loader",
									options: {
										sourceMap: true
									}
								}],
								fallback: "style-loader"
							`;
						} else {
							ExtractUseProps.push(
								{
									loader: "'style-loader'"
								},
								{
									loader: "'css-loader'"
								},
								{
									loader: "'sass-loader'"
								}
							);
						}
						break;
					case "LESS":
						regExpForStyles = new RegExp(/\.(less|css)$/);
						this.dependencies.push(
							"less-loader",
							"less",
							"style-loader",
							"css-loader"
						);
						if (this.isProd) {
							ExtractUseProps = `
								use: [{
									loader: "css-loader",
									options: {
										sourceMap: true
									}
								}, {
									loader: "less-loader",
									options: {
										sourceMap: true
									}
								}],
								fallback: "style-loader"
							`;
						} else {
							ExtractUseProps.push(
								{
									loader: "'css-loader'",
									options: {
										sourceMap: true
									}
								},
								{
									loader: "'less-loader'",
									options: {
										sourceMap: true
									}
								}
							);
						}
						break;
					case "PostCSS":
						this.configuration.config.topScope.push(
							tooltip.postcss(),
							"const autoprefixer = require('autoprefixer');",
							"const precss = require('precss');",
							"\n"
						);
						this.dependencies.push(
							"style-loader",
							"css-loader",
							"postcss-loader",
							"precss",
							"autoprefixer"
						);
						regExpForStyles = new RegExp(/\.css$/);
						if (this.isProd) {
							ExtractUseProps = `
								use: [{
									loader: "style-loader"
								},{
									loader: "css-loader",
									options: {
										sourceMap: true,
										importLoaders: 1
									}
								}, {
									loader: "postcss-loader",
									options: {
										plugins: function () {
											return [
												precss,
												autoprefixer
											];
										}
									}
								}],
								fallback: "style-loader"
							`;
						} else {
							ExtractUseProps.push(
								{
									loader: "'style-loader'"
								},
								{
									loader: "'css-loader'",
									options: {
										sourceMap: true,
										importLoaders: 1
									}
								},
								{
									loader: "'postcss-loader'",
									options: {
										plugins: `function () {
											return [
												precss,
												autoprefixer
											];
										}`
									}
								}
							);
						}
						break;
					case "CSS":
						this.dependencies.push("style-loader", "css-loader");
						regExpForStyles = new RegExp(/\.css$/);
						if (this.isProd) {
							ExtractUseProps = `
								use: [{
									loader: "css-loader",
									options: {
										sourceMap: true
									}
								}],
								fallback: "style-loader"
							`;
						} else {
							ExtractUseProps.push(
								{
									loader: "'style-loader'",
									options: {
										sourceMap: true
									}
								},
								{
									loader: "'css-loader'"
								}
							);
						}
						break;
					default:
						regExpForStyles = null;
				}
			})
			.then(() => {
				// Ask if the user wants to use extractPlugin
				return this.prompt([
					Input(
						"extractPlugin",
						"If you want to bundle your CSS files, what will you name the bundle? (press enter to skip)"
					)
				]);
			})
			.then(extractAnswer => {
				const cssBundleName = extractAnswer.extractPlugin;
				if (regExpForStyles) {
					if (this.isProd) {
						this.configuration.config.topScope.push(tooltip.cssPlugin());
						this.dependencies.push("extract-text-webpack-plugin");

						if (cssBundleName.length !== 0) {
							this.configuration.config.webpackOptions.plugins.push(
								`new ExtractTextPlugin('${cssBundleName}.[contentHash].css')`
							);
						} else {
							this.configuration.config.webpackOptions.plugins.push(
								"new ExtractTextPlugin('style.css')"
							);
						}

						const moduleRulesObj = {
							test: regExpForStyles,
							use: `ExtractTextPlugin.extract({ ${ExtractUseProps} })`
						};

						this.configuration.config.webpackOptions.module.rules.push(
							moduleRulesObj
						);
						this.configuration.config.topScope.push(
							"const ExtractTextPlugin = require('extract-text-webpack-plugin');",
							"\n"
						);
					} else {
						const moduleRulesObj = {
							test: regExpForStyles,
							use: ExtractUseProps
						};

						this.configuration.config.webpackOptions.module.rules.push(
							moduleRulesObj
						);
					}
				}
			})
			.then(() => {
				if (this.configuration.config.webpackOptions.entry.length === 0) {
					oneOrMoreEntries.forEach(prop => {
						this.configuration.config.webpackOptions.plugins.push(
							createCommonsChunkPlugin(prop)
						);
					});
				}
				done();
			});
	}
	installPlugins() {
		let asyncNamePrompt = this.async();
		let defaultName = this.isProd ? "prod" : "config";
		this.prompt([
			Input(
				"nameType",
				`Name your 'webpack.[name].js?' [default: '${defaultName}']:`
			)
		])
			.then(nameAnswer => {
				if (nameAnswer["nameType"].length) {
					this.configuration.config.configName = nameAnswer["nameType"];
				} else {
					this.configuration.config.configName = defaultName;
				}
			})
			.then(() => {
				asyncNamePrompt();
				this.runInstall(getPackageManager(), this.dependencies, {
					"save-dev": true
				});
			});
	}
};
<commit_msg>cli and webpack are both supported<commit_after>"use strict";

const Generator = require("yeoman-generator");
const chalk = require("chalk");
const logSymbols = require("log-symbols");

const createCommonsChunkPlugin = require("webpack-addons")
	.createCommonsChunkPlugin;

const Input = require("webpack-addons").Input;
const Confirm = require("webpack-addons").Confirm;
const List = require("webpack-addons").List;

const getPackageManager = require("../utils/package-manager").getPackageManager;

const entryQuestions = require("./utils/entry");
const getBabelPlugin = require("./utils/module");
const getDefaultPlugins = require("./utils/plugins");
const tooltip = require("./utils/tooltip");

module.exports = class WebpackGenerator extends Generator {
	constructor(args, opts) {
		super(args, opts);
		this.isProd = false;
		this.dependencies = ["webpack", "uglifyjs-webpack-plugin"];
		this.configuration = {
			config: {
				webpackOptions: {},
				topScope: []
			}
		};
	}
	prompting() {
		let done = this.async();
		let self = this;
		let oneOrMoreEntries;
		let regExpForStyles;
		let ExtractUseProps;
		let outputPath = "dist";
		process.stdout.write(
			"\n" +
				logSymbols.info +
				chalk.blue(" INFO ") +
				"For more information and a detailed description of each question, have a look at " +
				chalk.bold.green(
					"https://github.com/webpack/webpack-cli/blob/master/INIT.md"
				) +
				"\n"
		);
		process.stdout.write(
			logSymbols.info +
				chalk.blue(" INFO ") +
				"Alternatively, run `webpack(-cli) --help` for usage info." +
				"\n\n"
		);
		this.configuration.config.webpackOptions.module = {
			rules: []
		};
		this.configuration.config.webpackOptions.plugins = getDefaultPlugins();
		this.configuration.config.topScope.push(
			"const webpack = require('webpack')",
			"const path = require('path')",
			tooltip.uglify(),
			"const UglifyJSPlugin = require('uglifyjs-webpack-plugin');",
			"\n"
		);

		this.prompt([
			Confirm("entryType", "Will your application have multiple bundles?")
		])
			.then(entryTypeAnswer => {
				// Ask different questions for entry points
				return entryQuestions(self, entryTypeAnswer);
			})
			.then(entryOptions => {
				this.configuration.config.webpackOptions.entry = entryOptions;
				oneOrMoreEntries = Object.keys(entryOptions);

				return this.prompt([
					Input(
						"outputType",
						"Which folder will your generated bundles be in? [default: dist]:"
					)
				]);
			})
			.then(outputTypeAnswer => {
				if (!this.configuration.config.webpackOptions.entry.length) {
					this.configuration.config.topScope.push(tooltip.commonsChunk());
					this.configuration.config.webpackOptions.output = {
						filename: "'[name].[chunkhash].js'",
						chunkFilename: "'[name].[chunkhash].js'"
					};
				} else {
					this.configuration.config.webpackOptions.output = {
						filename: "'[name].bundle.js'"
					};
				}
				if (outputTypeAnswer["outputType"].length) {
					outputPath = outputTypeAnswer["outputType"];
				}
				this.configuration.config.webpackOptions.output.path = `path.resolve(__dirname, '${outputPath}')`;
			})
			.then(() => {
				return this.prompt([
					Confirm("prodConfirm", "Are you going to use this in production?")
				]);
			})
			.then(prodAnswer => {
				if (prodAnswer["prodConfirm"] === true) {
					this.isProd = true;
				} else {
					this.isProd = false;
				}
			})
			.then(() => {
				return this.prompt([
					Confirm("babelConfirm", "Will you be using ES2015?")
				]);
			})
			.then(ans => {
				if (ans["babelConfirm"] === true) {
					this.configuration.config.webpackOptions.module.rules.push(
						getBabelPlugin()
					);
					this.dependencies.push(
						"babel-loader",
						"babel-core",
						"babel-preset-env"
					);
				}
			})
			.then(() => {
				return this.prompt([
					List("stylingType", "Will you use one of the below CSS solutions?", [
						"SASS",
						"LESS",
						"CSS",
						"PostCSS",
						"No"
					])
				]);
			})
			.then(stylingAnswer => {
				if (!this.isProd) {
					ExtractUseProps = [];
				}
				switch (stylingAnswer["stylingType"]) {
					case "SASS":
						this.dependencies.push(
							"sass-loader",
							"node-sass",
							"style-loader",
							"css-loader"
						);
						regExpForStyles = new RegExp(/\.(scss|css)$/);
						if (this.isProd) {
							ExtractUseProps = `
								use: [{
									loader: "css-loader",
									options: {
										sourceMap: true
									}
								}, {
									loader: "sass-loader",
									options: {
										sourceMap: true
									}
								}],
								fallback: "style-loader"
							`;
						} else {
							ExtractUseProps.push(
								{
									loader: "'style-loader'"
								},
								{
									loader: "'css-loader'"
								},
								{
									loader: "'sass-loader'"
								}
							);
						}
						break;
					case "LESS":
						regExpForStyles = new RegExp(/\.(less|css)$/);
						this.dependencies.push(
							"less-loader",
							"less",
							"style-loader",
							"css-loader"
						);
						if (this.isProd) {
							ExtractUseProps = `
								use: [{
									loader: "css-loader",
									options: {
										sourceMap: true
									}
								}, {
									loader: "less-loader",
									options: {
										sourceMap: true
									}
								}],
								fallback: "style-loader"
							`;
						} else {
							ExtractUseProps.push(
								{
									loader: "'css-loader'",
									options: {
										sourceMap: true
									}
								},
								{
									loader: "'less-loader'",
									options: {
										sourceMap: true
									}
								}
							);
						}
						break;
					case "PostCSS":
						this.configuration.config.topScope.push(
							tooltip.postcss(),
							"const autoprefixer = require('autoprefixer');",
							"const precss = require('precss');",
							"\n"
						);
						this.dependencies.push(
							"style-loader",
							"css-loader",
							"postcss-loader",
							"precss",
							"autoprefixer"
						);
						regExpForStyles = new RegExp(/\.css$/);
						if (this.isProd) {
							ExtractUseProps = `
								use: [{
									loader: "style-loader"
								},{
									loader: "css-loader",
									options: {
										sourceMap: true,
										importLoaders: 1
									}
								}, {
									loader: "postcss-loader",
									options: {
										plugins: function () {
											return [
												precss,
												autoprefixer
											];
										}
									}
								}],
								fallback: "style-loader"
							`;
						} else {
							ExtractUseProps.push(
								{
									loader: "'style-loader'"
								},
								{
									loader: "'css-loader'",
									options: {
										sourceMap: true,
										importLoaders: 1
									}
								},
								{
									loader: "'postcss-loader'",
									options: {
										plugins: `function () {
											return [
												precss,
												autoprefixer
											];
										}`
									}
								}
							);
						}
						break;
					case "CSS":
						this.dependencies.push("style-loader", "css-loader");
						regExpForStyles = new RegExp(/\.css$/);
						if (this.isProd) {
							ExtractUseProps = `
								use: [{
									loader: "css-loader",
									options: {
										sourceMap: true
									}
								}],
								fallback: "style-loader"
							`;
						} else {
							ExtractUseProps.push(
								{
									loader: "'style-loader'",
									options: {
										sourceMap: true
									}
								},
								{
									loader: "'css-loader'"
								}
							);
						}
						break;
					default:
						regExpForStyles = null;
				}
			})
			.then(() => {
				// Ask if the user wants to use extractPlugin
				return this.prompt([
					Input(
						"extractPlugin",
						"If you want to bundle your CSS files, what will you name the bundle? (press enter to skip)"
					)
				]);
			})
			.then(extractAnswer => {
				const cssBundleName = extractAnswer.extractPlugin;
				if (regExpForStyles) {
					if (this.isProd) {
						this.configuration.config.topScope.push(tooltip.cssPlugin());
						this.dependencies.push("extract-text-webpack-plugin");

						if (cssBundleName.length !== 0) {
							this.configuration.config.webpackOptions.plugins.push(
								`new ExtractTextPlugin('${cssBundleName}.[contentHash].css')`
							);
						} else {
							this.configuration.config.webpackOptions.plugins.push(
								"new ExtractTextPlugin('style.css')"
							);
						}

						const moduleRulesObj = {
							test: regExpForStyles,
							use: `ExtractTextPlugin.extract({ ${ExtractUseProps} })`
						};

						this.configuration.config.webpackOptions.module.rules.push(
							moduleRulesObj
						);
						this.configuration.config.topScope.push(
							"const ExtractTextPlugin = require('extract-text-webpack-plugin');",
							"\n"
						);
					} else {
						const moduleRulesObj = {
							test: regExpForStyles,
							use: ExtractUseProps
						};

						this.configuration.config.webpackOptions.module.rules.push(
							moduleRulesObj
						);
					}
				}
			})
			.then(() => {
				if (this.configuration.config.webpackOptions.entry.length === 0) {
					oneOrMoreEntries.forEach(prop => {
						this.configuration.config.webpackOptions.plugins.push(
							createCommonsChunkPlugin(prop)
						);
					});
				}
				done();
			});
	}
	installPlugins() {
		let asyncNamePrompt = this.async();
		let defaultName = this.isProd ? "prod" : "config";
		this.prompt([
			Input(
				"nameType",
				`Name your 'webpack.[name].js?' [default: '${defaultName}']:`
			)
		])
			.then(nameAnswer => {
				if (nameAnswer["nameType"].length) {
					this.configuration.config.configName = nameAnswer["nameType"];
				} else {
					this.configuration.config.configName = defaultName;
				}
			})
			.then(() => {
				asyncNamePrompt();
				this.runInstall(getPackageManager(), this.dependencies, {
					"save-dev": true
				});
			});
	}
};
<|endoftext|>


<commit_before>/**
 * Created by hvallee on 7/23/15.
 */

var tables;
var findingTables = false;

chrome.runtime.onMessage.addListener(

    function(request, sender, sendResponse) {
        var id = 0;

        if( request.message === "find_tables" ) {
            chrome.runtime.sendMessage({
                "message": "get_gotIt_button"
            }, function(response) {
                if (!response) {
                    if (window.location.protocol == "https:") {
                        chrome.runtime.sendMessage({
                            "message": "displayHttpsInstructions"
                        });
                        // We add an iFrame to display the shield icon
                        var editor = '';

                        $("body").append(editor);
                    }
                }
            });

            tables =$("table");

            for(var index = 0; index < tables.length; index++) {
                var table = tables[index];

                var button = document.createElement("button");
                button.setAttribute("class", "waves-effect waves-light btn");
                button.setAttribute("style", "margin-top: 10px");
                button.setAttribute("id", index.toString());
                button.setAttribute("data-type", 'OpenCompareButton');

                button.addEventListener('click', function(event) {

                    id = event.target.getAttribute("id");
                    $('#'+id).hide();

                    chrome.runtime.sendMessage({
                        "message": "convert_to_editor",
                        "table": tables[id].outerHTML,
                        "index": id
                    });
                });
                var buttonContent = document.createTextNode("Replace this table");
                button.appendChild(buttonContent);
                var parentDiv = tables[index].parentNode;
                parentDiv.insertBefore(button, tables[index]);
            }
        }

        if( request.message === "remove_buttons" ) {
            var buttons =$("button[data-type='OpenCompareButton']");
            buttons.remove();
        }

        if( request.message === "replace_table" ) {
            var editor = '';

            tables.eq(request.tableIndex).replaceWith(editor);
        }
        else if( request.message === "store_find_button" ) {
            findingTables = true;
        }
        else if( request.message === "get_find_button" ) {
            sendResponse(findingTables);
        }
    }
);

<commit_msg>Same height than table<commit_after>/**
 * Created by hvallee on 7/23/15.
 */

var tables;
var findingTables = false;

chrome.runtime.onMessage.addListener(

    function(request, sender, sendResponse) {
        var id = 0;

        if( request.message === "find_tables" ) {
            chrome.runtime.sendMessage({
                "message": "get_gotIt_button"
            }, function(response) {
                if (!response) {
                    if (window.location.protocol == "https:") {
                        chrome.runtime.sendMessage({
                            "message": "displayHttpsInstructions"
                        });
                        // We add an iFrame to display the shield icon
                        var editor = '';

                        $("body").append(editor);
                    }
                }
            });

            tables =$("table");

            for(var index = 0; index < tables.length; index++) {
                var table = tables[index];

                var button = document.createElement("button");
                button.setAttribute("class", "waves-effect waves-light btn");
                button.setAttribute("style", "margin-top: 10px");
                button.setAttribute("id", index.toString());
                button.setAttribute("data-type", 'OpenCompareButton');

                button.addEventListener('click', function(event) {

                    id = event.target.getAttribute("id");
                    $('#'+id).hide();

                    chrome.runtime.sendMessage({
                        "message": "convert_to_editor",
                        "table": tables[id].outerHTML,
                        "index": id
                    });
                });
                var buttonContent = document.createTextNode("Replace this table");
                button.appendChild(buttonContent);
                var parentDiv = tables[index].parentNode;
                parentDiv.insertBefore(button, tables[index]);
            }
        }

        if( request.message === "remove_buttons" ) {
            var buttons =$("button[data-type='OpenCompareButton']");
            buttons.remove();
        }

        if( request.message === "replace_table" ) {
            var editor = '';

            tables.eq(request.tableIndex).replaceWith(editor);
        }
        else if( request.message === "store_find_button" ) {
            findingTables = true;
        }
        else if( request.message === "get_find_button" ) {
            sendResponse(findingTables);
        }
    }
);

<|endoftext|>