<commit_before>// This magic double-underscored identifier gets replaced in
// tools/isobuild/bundler.js with a tree of hashes of all dynamic
// modules, for use in client.js and cache.js.
var versions = __DYNAMIC_VERSIONS__;

exports.get = function (id) {
  var tree = versions;
  var version = null;

  id.split("/").some(function (part) {
    if (part) {
      // If the tree contains identifiers for Meteor packages with colons
      // in their names, the colons should not have been replaced by
      // underscores, but there's a bug that results in that behavior, so
      // for now it seems safest to be tolerant of underscores here.
      // https://github.com/meteor/meteor/pull/9103
      tree = tree[part] || tree[part.replace(":", "_")];
    }

    if (! tree) {
      // Terminate the search without reassigning version.
      return true;
    }

    if (typeof tree === "string") {
      version = tree;
      return true;
    }
  });

  return version;
};
<commit_msg>Prefetch dynamic modules when appcache is active (#9482)<commit_after>// This magic double-underscored identifier gets replaced in
// tools/isobuild/bundler.js with a tree of hashes of all dynamic
// modules, for use in client.js and cache.js.
var versions = __DYNAMIC_VERSIONS__;

exports.get = function (id) {
  var tree = versions;
  var version = null;

  id.split("/").some(function (part) {
    if (part) {
      // If the tree contains identifiers for Meteor packages with colons
      // in their names, the colons should not have been replaced by
      // underscores, but there's a bug that results in that behavior, so
      // for now it seems safest to be tolerant of underscores here.
      // https://github.com/meteor/meteor/pull/9103
      tree = tree[part] || tree[part.replace(":", "_")];
    }

    if (! tree) {
      // Terminate the search without reassigning version.
      return true;
    }

    if (typeof tree === "string") {
      version = tree;
      return true;
    }
  });

  return version;
};

function getFlatModuleArray(tree) {
  var parts = [""];
  var result = [];

  function walk(t) {
    if (t && typeof t === "object") {
      Object.keys(t).forEach(function (key) {
        parts.push(key);
        walk(t[key]);
        parts.pop();
      });
    } else if (typeof t === "string") {
      result.push(parts.join("/"));
    }
  }

  walk(tree);

  return result;
}

// If Package.appcache is loaded, preload additional modules after the
// core bundle has been loaded.
function precacheOnLoad(event) {
  // Check inside onload to make sure Package.appcache has had a chance to
  // become available.
  if (! Package.appcache) {
    return;
  }

  // Prefetch in chunks to reduce overhead. If we call module.prefetch(id)
  // multiple times in the same tick of the event loop, all those modules
  // will be fetched in one HTTP POST request.
  function prefetchInChunks(modules, amount) {
    Promise.all(modules.splice(0, amount).map(function (id) {
      return module.prefetch(id);
    })).then(function () {
      if (modules.length > 0) {
        prefetchInChunks(modules, amount);
      }
    });
  }

  // Get a flat array of modules and start prefetching.
  prefetchInChunks(getFlatModuleArray(versions), 50);
}

// Use window.onload to only prefetch after the main bundle has loaded.
if (global.addEventListener) {
  global.addEventListener('load', precacheOnLoad, false);
} else if (global.attachEvent) {
  global.attachEvent('onload', precacheOnLoad);
}
<|endoftext|>


<commit_before>import InjectedProperty from "ember-metal/injected_property";
import {
  createInjectionHelper,
  default as inject
} from "ember-runtime/inject";
import Container from "ember-runtime/system/container";
import Object from "ember-runtime/system/object";

if (Ember.FEATURES.isEnabled('ember-metal-injected-properties')) {
  QUnit.module('inject');

  test("calling `inject` directly should error", function() {
    throws(function() {
      inject('foo');
    }, /Injected properties must be created through helpers/);
  });

  test("injection type validation function is run once at mixin time", function() {
    expect(1);

    createInjectionHelper('foo', function() {
      ok(true, 'should call validation function');
    });

    var AnObject = Object.extend({
      bar: inject.foo(),
      baz: inject.foo()
    });

    // Prototype chains are lazy, make sure it's evaluated
    AnObject.proto();
  });

  test("attempting to inject a nonexistent container key should error", function() {
    var container = new Container();
    var AnObject = Object.extend({
      container: container,
      foo: new InjectedProperty('bar', 'baz')
    });

    container.register('foo:main', AnObject);

    throws(function() {
      container.lookup('foo:main');
    }, /Attempting to inject an unknown injection: `bar:baz`/);
  });

  test("factories should return a list of lazy injection full names", function() {
    var AnObject = Object.extend({
      foo: new InjectedProperty('foo', 'bar'),
      bar: new InjectedProperty('quux')
    });

    deepEqual(AnObject.lazyInjections(), { 'foo': 'foo:bar', 'bar': 'quux:bar' }, "should return injected container keys");
  });
}
<commit_msg>[FEATURE ember-metal-injected-properties] Ensure tests work in prod builds.<commit_after>/* global EmberDev */

import InjectedProperty from "ember-metal/injected_property";
import {
  createInjectionHelper,
  default as inject
} from "ember-runtime/inject";
import Container from "ember-runtime/system/container";
import Object from "ember-runtime/system/object";

if (Ember.FEATURES.isEnabled('ember-metal-injected-properties')) {
  QUnit.module('inject');

  test("calling `inject` directly should error", function() {
    expectAssertion(function() {
      inject('foo');
    }, /Injected properties must be created through helpers/);
  });

  if (!EmberDev.runningProdBuild) {
    // this check is done via an assertion which is stripped from
    // production builds
    test("injection type validation function is run once at mixin time", function() {
      expect(1);

      createInjectionHelper('foo', function() {
        ok(true, 'should call validation function');
      });

      var AnObject = Object.extend({
        bar: inject.foo(),
        baz: inject.foo()
      });

      // Prototype chains are lazy, make sure it's evaluated
      AnObject.proto();
    });
  }

  test("attempting to inject a nonexistent container key should error", function() {
    var container = new Container();
    var AnObject = Object.extend({
      container: container,
      foo: new InjectedProperty('bar', 'baz')
    });

    container.register('foo:main', AnObject);

    throws(function() {
      container.lookup('foo:main');
    }, /Attempting to inject an unknown injection: `bar:baz`/);
  });

  test("factories should return a list of lazy injection full names", function() {
    var AnObject = Object.extend({
      foo: new InjectedProperty('foo', 'bar'),
      bar: new InjectedProperty('quux')
    });

    deepEqual(AnObject.lazyInjections(), { 'foo': 'foo:bar', 'bar': 'quux:bar' }, "should return injected container keys");
  });
}
<|endoftext|>


<commit_before>/* Copyright (c) 2012-2015 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
define(function(require, exports, module) {
  'use strict';
  console.log('Loading perspective.manager.js ...');
  var perspectives;
  var TSCORE = require('tscore');

  function initPerspective(extPath) {
    return new Promise(function(resolve, reject) {
      require([extPath], function(perspective) {
        perspectives.push(perspective);

        // Creating perspective's toolbar
        $('#viewToolbars').append($('
', {
          id: perspective.ID + 'Toolbar',
          class: 'btn-toolbar'
        }).hide());
        // Creating perspective's container
        $('#viewContainers').append($('
', {
          id: perspective.ID + 'Container',
          style: 'width: 100%; height: 100%'
        }).hide());
        // Creating perspective's footer
        $('#viewFooters').append($('
', {
          id: perspective.ID + 'Footer'
        }).hide());
        //TODO: return init as promise
        perspective.init();
        resolve(true);
      }); // jshint ignore:line
    });
  }

  function initPerspectives() {
    perspectives = [];
    $('#viewSwitcher').empty();
    $('#viewToolbars').empty();
    $('#viewContainers').empty();
    $('#viewFooters').empty();
    initWelcomeScreen();

    var extensions = TSCORE.Config.getPerspectives();
    var promises = [];
    for (var i = 0; i < extensions.length; i++) {
      var extPath = TSCORE.Config.getExtensionPath() + '/' + extensions[i].id + '/extension.js';
      promises.push(initPerspective(extPath));
    }

    return Promise.all(promises).then(function() {
      initPerspectiveSwitcher();
      // Opening last saved location by the start of the application
      var lastLocation = TSCORE.Config.getLastOpenedLocation();
      if (TSCORE.Config.getUseDefaultLocation()) {
        lastLocation = TSCORE.Config.getDefaultLocation();
      }
      if (lastLocation && lastLocation.length >= 1) {
        TSCORE.openLocation(lastLocation);
        TSCORE.IO.checkAccessFileURLAllowed();
        var evt = TSCORE.createDocumentEvent("initApp");
        TSCORE.fireDocumentEvent(evt);
        $("#viewContainers").removeClass("appBackgroundTile");
      }
      $('#loading').hide();
      if (isNode) {
        TSCORE.IO.showMainWindow();
      }
      return true;
    });
  }

  var initWelcomeScreen = function() {
    /* require([
              "text!templates/WelcomeScreen.html",
            ], function(uiTPL) {
                // Check if dialog already created
                if($("#dialogLocationEdit").length < 1) {
                    var uiTemplate = Handlebars.compile( uiTPL );
                    $("#viewContainers").append(uiTemplate());
                }
        }); */
    $('#viewContainers').append('

');
  };

  var initPerspectiveSwitcher = function() {
    var extensions = TSCORE.Config.getPerspectives();
    var $perspectiveSwitcher = $('#perspectiveSwitcher');
    $perspectiveSwitcher.empty();
    $perspectiveSwitcher.append($('
', {
      class: 'dropdown-header',
      text: $.i18n.t('ns.common:perspectiveSwitch')
    }).prepend("<button class='close'>×</button>"))
    .append("

");

    for (var i = 0; i < extensions.length; i++) {
      var curPers;
      // Finding the right perspective
      perspectives.forEach(function(value) {
        if (value.ID === extensions[i].id) {
          curPers = value;
        }
      }); // jshint ignore:line
      $perspectiveSwitcher.append($('
', {}).append($('', {
        'viewid': curPers.ID,
        'title': curPers.ID,
        'id': curPers.ID + 'Button',
        'text': curPers.Title
      }).prepend($('', {
        'class': curPers.Icon + ' fa-lg',
        'style': 'margin-right: 15px'
      }))));
      // Adding event listener & icon to the radio button
      $('#' + curPers.ID + 'Button').click(function() {
        changePerspective($(this).attr('viewid'));
      }); // jshint ignore:line
    }
  };

  var redrawCurrentPerspective = function() {
    for (var i = 0; i < perspectives.length; i++) {
      if (perspectives[i].ID === TSCORE.currentPerspectiveID) {
        try {
          perspectives[i].load();
          break;
        } catch (e) {
          console.warn("Error while executing 'redrawCurrentPerspective' on " + perspectives[i].ID + ' ' + e);
        }
      }
    }
  };

  var removeFileUI = function(filePath) {
    console.log('Removing file from perspectives');
    for (var i = 0; i < perspectives.length; i++) {
      try {
        perspectives[i].removeFileUI(filePath);
      } catch (e) {
        console.warn("Error while executing 'removeFileUI' on " + perspectives[i].ID + ' ' + e);
      }
    }
  };

  var updateFileUI = function(oldFilePath, newFilePath) {
    console.log('Updating file in perspectives');
    for (var i = 0; i < perspectives.length; i++) {
      try {
        perspectives[i].updateFileUI(oldFilePath, newFilePath);
      } catch (e) {
        console.warn("Error while executing 'updateFileUI' on " + perspectives[i].ID + ' ' + e);
      }
    }
  };

  var getNextFile = function(filePath) {
    for (var i = 0; i < perspectives.length; i++) {
      if (perspectives[i].ID === TSCORE.currentPerspectiveID) {
        try {
          return perspectives[i].getNextFile(filePath);
        } catch (e) {
          console.warn("Error while executing 'getNextFile' on " + perspectives[i].ID + ' ' + e);
        }
      }
    }
  };

  var getPrevFile = function(filePath) {
    for (var i = 0; i < perspectives.length; i++) {
      if (perspectives[i].ID === TSCORE.currentPerspectiveID) {
        try {
          return perspectives[i].getPrevFile(filePath);
        } catch (e) {
          console.warn("Error while executing 'getPrevFile' on " + perspectives[i].ID + ' ' + e);
        }
      }
    }
  };

  var updateTreeData = function(treeData) {
    for (var i = 0; i < perspectives.length; i++) {
      try {
        perspectives[i].updateTreeData(treeData);
      } catch (e) {
        console.warn("Error while executing 'updateTreeData' on "); // + perspectives[i].ID + ' ' + e);
      }
    }
  };

  var updateFileBrowserData = function(dirList) {
    console.log('Updating the file browser data...');
    TSCORE.fileList = [];
    var workers = [];
    var tags, ext, title, fileSize, fileLMDT, path, filename, entry;
    for (var i = 0; i < dirList.length; i++) {
      // Considering Unix HiddenEntries (. in the beginning of the filename)
      if (TSCORE.Config.getShowUnixHiddenEntries() || !TSCORE.Config.getShowUnixHiddenEntries() && dirList[i].path.indexOf(TSCORE.dirSeparator + '.') < 0) {
        filename = dirList[i].name.replace(/(<([^>]+)>)/gi, ''); // sanitizing filename
        path = dirList[i].path.replace(/(<([^>]+)>)/gi, ''); // sanitizing filepath
        title = TSCORE.TagUtils.extractTitle(path);

        if (dirList[i].isFile) {
          ext = TSCORE.TagUtils.extractFileExtension(path);
          tags = TSCORE.TagUtils.extractTags(path);
          fileSize = dirList[i].size;
          fileLMDT = dirList[i].lmdt;
          if (fileSize === undefined) {
            fileSize = '';
          }
          if (fileLMDT === undefined) {
            fileLMDT = '';
          }
          var metaObj = {
            thumbnailPath: "",
            metaData: null
          };
          entry = [
            ext,
            title,
            tags,
            fileSize,
            fileLMDT,
            path,
            filename,
            metaObj
          ];
          TSCORE.fileList.push(entry);
          workers.push(TSCORE.Meta.loadMetaDataFromFile(entry));
        } else {
          entry = [
            path,
            filename
          ];
          TSCORE.subDirsList.push(entry);
        }
      }
    }

    changePerspective(TSCORE.currentPerspectiveID);
    Promise.all(workers).then(function(result) {
      console.log("MetaData loaded");
      //changePerspective(TSCORE.currentPerspectiveID);
    }).catch(function(e) {
      console.error("MetaData Error: " + e);
    });
  };

  var refreshFileListContainer = function() {
    // TODO consider search view
    TSCORE.IO.listDirectory(TSCORE.currentPath);
  };

  var hideAllPerspectives = function() {
    $('#welcomeScreen').hide();
    for (var i = 0; i < perspectives.length; i++) {
      $('#' + perspectives[i].ID + 'Container').hide();
      $('#' + perspectives[i].ID + 'Toolbar').hide();
      $('#' + perspectives[i].ID + 'Footer').hide();
    }
  };

  var changePerspective = function(viewType) {
    console.log('Change to ' + viewType + ' perspective.');
    TSCORE.showLoadingAnimation();
    // Loading first perspective by default
    if (viewType === undefined) {
      TSCORE.currentPerspectiveID = perspectives[0].ID;
    } else {
      //Setting the current view
      TSCORE.currentPerspectiveID = viewType;
    }
    if (TSCORE.currentPerspectiveID === undefined) {
      TSCORE.showAlertDialog('No Perspectives found', '');
      return false;
    }
    hideAllPerspectives();
    for (var i = 0; i < perspectives.length; i++) {
      if (perspectives[i].ID === viewType) {
        var $currentPerspectitveIcon = $('#currentPerspectitveIcon');
        var $currentPerspectitveName = $('#currentPerspectitveName');
        $currentPerspectitveIcon.removeClass();
        $currentPerspectitveIcon.addClass(perspectives[i].Icon);
        $currentPerspectitveIcon.addClass('fa-lg');
        $currentPerspectitveName.text(' ' + perspectives[i].Title);
        $currentPerspectitveName.attr('title', perspectives[i].ID);
        perspectives[i].load();
        $('#' + perspectives[i].ID + 'Container').show();
        $('#' + perspectives[i].ID + 'Toolbar').show();
        $('#' + perspectives[i].ID + 'Footer').show();
      }
    }
    // Clear the list with the selected files
    clearSelectedFiles();
    // Enabled the main toolbar e.g. search functionality
    TSCORE.enableTopToolbar();
  };

  var clearSelectedFiles = function() {
    // Clear selected files
    TSCORE.selectedFiles = [];
    for (var i = 0; i < perspectives.length; i++) {
      try {
        perspectives[i].clearSelectedFiles();
      } catch (e) {
        console.error('Error while executing \'clearSelectedFiles\' on ' + perspectives[i].ID + ' - ' + e);
      }
    }
  };

  exports.initPerspectives = initPerspectives;
  exports.hideAllPerspectives = hideAllPerspectives;
  exports.redrawCurrentPerspective = redrawCurrentPerspective;
  exports.getNextFile = getNextFile;
  exports.getPrevFile = getPrevFile;
  exports.updateTreeData = updateTreeData;
  exports.updateFileBrowserData = updateFileBrowserData;
  exports.refreshFileListContainer = refreshFileListContainer;
  exports.clearSelectedFiles = clearSelectedFiles;
  exports.removeFileUI = removeFileUI;
  exports.updateFileUI = updateFileUI;
  exports.changePerspective = changePerspective; //exports.generateDesktop              = generateDesktop;
});
<commit_msg>loading thumbnails optimization<commit_after>/* Copyright (c) 2012-2015 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that
 * can be found in the LICENSE file. */
define(function(require, exports, module) {
  'use strict';
  console.log('Loading perspective.manager.js ...');
  var perspectives;
  var TSCORE = require('tscore');

  function initPerspective(extPath) {
    return new Promise(function(resolve, reject) {
      require([extPath], function(perspective) {
        perspectives.push(perspective);

        // Creating perspective's toolbar
        $('#viewToolbars').append($('
', {
          id: perspective.ID + 'Toolbar',
          class: 'btn-toolbar'
        }).hide());
        // Creating perspective's container
        $('#viewContainers').append($('
', {
          id: perspective.ID + 'Container',
          style: 'width: 100%; height: 100%'
        }).hide());
        // Creating perspective's footer
        $('#viewFooters').append($('
', {
          id: perspective.ID + 'Footer'
        }).hide());
        //TODO: return init as promise
        perspective.init();
        resolve(true);
      }); // jshint ignore:line
    });
  }

  function initPerspectives() {
    perspectives = [];
    $('#viewSwitcher').empty();
    $('#viewToolbars').empty();
    $('#viewContainers').empty();
    $('#viewFooters').empty();
    initWelcomeScreen();

    var extensions = TSCORE.Config.getPerspectives();
    var promises = [];
    for (var i = 0; i < extensions.length; i++) {
      var extPath = TSCORE.Config.getExtensionPath() + '/' + extensions[i].id + '/extension.js';
      promises.push(initPerspective(extPath));
    }

    return Promise.all(promises).then(function() {
      initPerspectiveSwitcher();
      // Opening last saved location by the start of the application
      var lastLocation = TSCORE.Config.getLastOpenedLocation();
      if (TSCORE.Config.getUseDefaultLocation()) {
        lastLocation = TSCORE.Config.getDefaultLocation();
      }
      if (lastLocation && lastLocation.length >= 1) {
        TSCORE.openLocation(lastLocation);
        TSCORE.IO.checkAccessFileURLAllowed();
        var evt = TSCORE.createDocumentEvent("initApp");
        TSCORE.fireDocumentEvent(evt);
        $("#viewContainers").removeClass("appBackgroundTile");
      }
      $('#loading').hide();
      if (isNode) {
        TSCORE.IO.showMainWindow();
      }
      return true;
    });
  }

  var initWelcomeScreen = function() {
    /* require([
              "text!templates/WelcomeScreen.html",
            ], function(uiTPL) {
                // Check if dialog already created
                if($("#dialogLocationEdit").length < 1) {
                    var uiTemplate = Handlebars.compile( uiTPL );
                    $("#viewContainers").append(uiTemplate());
                }
        }); */
    $('#viewContainers').append('

');
  };

  var initPerspectiveSwitcher = function() {
    var extensions = TSCORE.Config.getPerspectives();
    var $perspectiveSwitcher = $('#perspectiveSwitcher');
    $perspectiveSwitcher.empty();
    $perspectiveSwitcher.append($('
', {
      class: 'dropdown-header',
      text: $.i18n.t('ns.common:perspectiveSwitch')
    }).prepend("<button class='close'>×</button>"))
    .append("

");

    for (var i = 0; i < extensions.length; i++) {
      var curPers;
      // Finding the right perspective
      perspectives.forEach(function(value) {
        if (value.ID === extensions[i].id) {
          curPers = value;
        }
      }); // jshint ignore:line
      $perspectiveSwitcher.append($('
', {}).append($('', {
        'viewid': curPers.ID,
        'title': curPers.ID,
        'id': curPers.ID + 'Button',
        'text': curPers.Title
      }).prepend($('', {
        'class': curPers.Icon + ' fa-lg',
        'style': 'margin-right: 15px'
      }))));
      // Adding event listener & icon to the radio button
      $('#' + curPers.ID + 'Button').click(function() {
        changePerspective($(this).attr('viewid'));
      }); // jshint ignore:line
    }
  };

  var redrawCurrentPerspective = function() {
    for (var i = 0; i < perspectives.length; i++) {
      if (perspectives[i].ID === TSCORE.currentPerspectiveID) {
        try {
          perspectives[i].load();
          break;
        } catch (e) {
          console.warn("Error while executing 'redrawCurrentPerspective' on " + perspectives[i].ID + ' ' + e);
        }
      }
    }
  };

  var removeFileUI = function(filePath) {
    console.log('Removing file from perspectives');
    for (var i = 0; i < perspectives.length; i++) {
      try {
        perspectives[i].removeFileUI(filePath);
      } catch (e) {
        console.warn("Error while executing 'removeFileUI' on " + perspectives[i].ID + ' ' + e);
      }
    }
  };

  var updateFileUI = function(oldFilePath, newFilePath) {
    console.log('Updating file in perspectives');
    for (var i = 0; i < perspectives.length; i++) {
      try {
        perspectives[i].updateFileUI(oldFilePath, newFilePath);
      } catch (e) {
        console.warn("Error while executing 'updateFileUI' on " + perspectives[i].ID + ' ' + e);
      }
    }
  };

  var getNextFile = function(filePath) {
    for (var i = 0; i < perspectives.length; i++) {
      if (perspectives[i].ID === TSCORE.currentPerspectiveID) {
        try {
          return perspectives[i].getNextFile(filePath);
        } catch (e) {
          console.warn("Error while executing 'getNextFile' on " + perspectives[i].ID + ' ' + e);
        }
      }
    }
  };

  var getPrevFile = function(filePath) {
    for (var i = 0; i < perspectives.length; i++) {
      if (perspectives[i].ID === TSCORE.currentPerspectiveID) {
        try {
          return perspectives[i].getPrevFile(filePath);
        } catch (e) {
          console.warn("Error while executing 'getPrevFile' on " + perspectives[i].ID + ' ' + e);
        }
      }
    }
  };

  var updateTreeData = function(treeData) {
    for (var i = 0; i < perspectives.length; i++) {
      try {
        perspectives[i].updateTreeData(treeData);
      } catch (e) {
        console.warn("Error while executing 'updateTreeData' on "); // + perspectives[i].ID + ' ' + e);
      }
    }
  };

  var updateFileBrowserData = function(dirList) {
    console.log('Updating the file browser data...');
    TSCORE.fileList = [];
    var workers = [];
    var tags, ext, title, fileSize, fileLMDT, path, filename, entry;
    for (var i = 0; i < dirList.length; i++) {
      // Considering Unix HiddenEntries (. in the beginning of the filename)
      if (TSCORE.Config.getShowUnixHiddenEntries() || !TSCORE.Config.getShowUnixHiddenEntries() && dirList[i].path.indexOf(TSCORE.dirSeparator + '.') < 0) {
        filename = dirList[i].name.replace(/(<([^>]+)>)/gi, ''); // sanitizing filename
        path = dirList[i].path.replace(/(<([^>]+)>)/gi, ''); // sanitizing filepath
        title = TSCORE.TagUtils.extractTitle(path);

        if (dirList[i].isFile) {
          ext = TSCORE.TagUtils.extractFileExtension(path);
          tags = TSCORE.TagUtils.extractTags(path);
          fileSize = dirList[i].size;
          fileLMDT = dirList[i].lmdt;
          if (fileSize === undefined) {
            fileSize = '';
          }
          if (fileLMDT === undefined) {
            fileLMDT = '';
          }
          var metaObj = {
            thumbnailPath: "",
            metaData: null
          };
          entry = [
            ext,
            title,
            tags,
            fileSize,
            fileLMDT,
            path,
            filename,
            metaObj
          ];
          TSCORE.fileList.push(entry);
          workers.push(TSCORE.Meta.loadMetaDataFromFile(entry));
        } else {
          entry = [
            path,
            filename
          ];
          TSCORE.subDirsList.push(entry);
        }
      }
    }

    changePerspective(TSCORE.currentPerspectiveID);
    Promise.all(workers).then(function(result) {
      console.log("MetaData loaded");
      changePerspective(TSCORE.currentPerspectiveID);
    }).catch(function(e) {
      console.error("MetaData Error: " + e);
    });
  };

  var refreshFileListContainer = function() {
    // TODO consider search view
    TSCORE.IO.listDirectory(TSCORE.currentPath);
  };

  var hideAllPerspectives = function() {
    $('#welcomeScreen').hide();
    for (var i = 0; i < perspectives.length; i++) {
      $('#' + perspectives[i].ID + 'Container').hide();
      $('#' + perspectives[i].ID + 'Toolbar').hide();
      $('#' + perspectives[i].ID + 'Footer').hide();
    }
  };

  var changePerspective = function(viewType) {
    console.log('Change to ' + viewType + ' perspective.');
    TSCORE.showLoadingAnimation();
    // Loading first perspective by default
    if (viewType === undefined) {
      TSCORE.currentPerspectiveID = perspectives[0].ID;
    } else {
      //Setting the current view
      TSCORE.currentPerspectiveID = viewType;
    }
    if (TSCORE.currentPerspectiveID === undefined) {
      TSCORE.showAlertDialog('No Perspectives found', '');
      return false;
    }
    hideAllPerspectives();
    for (var i = 0; i < perspectives.length; i++) {
      if (perspectives[i].ID === viewType) {
        var $currentPerspectitveIcon = $('#currentPerspectitveIcon');
        var $currentPerspectitveName = $('#currentPerspectitveName');
        $currentPerspectitveIcon.removeClass();
        $currentPerspectitveIcon.addClass(perspectives[i].Icon);
        $currentPerspectitveIcon.addClass('fa-lg');
        $currentPerspectitveName.text(' ' + perspectives[i].Title);
        $currentPerspectitveName.attr('title', perspectives[i].ID);
        perspectives[i].load();
        $('#' + perspectives[i].ID + 'Container').show();
        //$('#' + perspectives[i].ID + 'Toolbar').show();
      }
    }
    // Clear the list with the selected files
    clearSelectedFiles();
    // Enabled the main toolbar e.g. search functionality
    TSCORE.enableTopToolbar();
  };

  var clearSelectedFiles = function() {
    // Clear selected files
    TSCORE.selectedFiles = [];
    for (var i = 0; i < perspectives.length; i++) {
      try {
        perspectives[i].clearSelectedFiles();
      } catch (e) {
        console.error('Error while executing \'clearSelectedFiles\' on ' + perspectives[i].ID + ' - ' + e);
      }
    }
  };

  exports.initPerspectives = initPerspectives;
  exports.hideAllPerspectives = hideAllPerspectives;
  exports.redrawCurrentPerspective = redrawCurrentPerspective;
  exports.getNextFile = getNextFile;
  exports.getPrevFile = getPrevFile;
  exports.updateTreeData = updateTreeData;
  exports.updateFileBrowserData = updateFileBrowserData;
  exports.refreshFileListContainer = refreshFileListContainer;
  exports.clearSelectedFiles = clearSelectedFiles;
  exports.removeFileUI = removeFileUI;
  exports.updateFileUI = updateFileUI;
  exports.changePerspective = changePerspective; //exports.generateDesktop              = generateDesktop;
});
<|endoftext|>


<commit_before>var LRU = require('lru-cache'),
  request = require('request'),
  url = require('url'),
  util = require('util'),
  cache = LRU(10),
  equals = function(b) {
    return function(a) {
      return a == b;
    };
  },
  staticPages = [
    '',
    '/faq',
    '/about',
    '/about/careers',
    '/about/contact',
    '/about/team',
    '/admin',
    '/styleguide'
  ];

module.exports = {

  proxy: function(req, res) {
    if (process.env.DISABLE_PROXY) {
      return res.status(503).send('Service Unavailable');
    }

    var u = url.parse(req.url);

    // remove trailing slash
    u.pathname = u.pathname.replace(/\/$/, '');

    // a path without an extension should be served by index.html in
    // the folder of the same name.
    if (!u.pathname.match(/\.\w{3,4}$/)) {

      // for any paths not explicitly listed, serve the Angular app.
      if (!_.any(staticPages, equals(u.pathname))) {
        u.pathname = '/app';
      }

      u.pathname += '/index.html';
    }

    // add the deploy-specific (cache-busting) path prefix
    u.pathname = util.format('assets/%s%s', process.env.BUNDLE_VERSION, u.pathname);

    var newUrl = util.format('%s/%s', process.env.ASSET_HOST_URL, url.format(u));

    // use path without query params as cache key
    var cacheKey = u.pathname,
      cached = (sails.config.environment === 'development' ? null : cache.get(cacheKey));

    if (cached) {
      sails.log.info(util.format(' ☺ %s', newUrl));
      res.ok(cached);
    } else {
      sails.log.info(util.format(' ↑ %s', newUrl));
      request(newUrl, function(err, response, body) {
        if (response && response.statusCode == 403) {
          // a 403 from S3 could also be a 404
          return res.notFound();
        }

        if (err || response.statusCode != 200) {
          var code = (response ? response.statusCode : 'X');
          return res.serverError(util.format("upstream: %s %s", code, err));
        }

        cache.set(cacheKey, body);
        res.ok(body);
      })
    }
  }

}<commit_msg>allow 2-letter extensions<commit_after>var LRU = require('lru-cache'),
  request = require('request'),
  url = require('url'),
  util = require('util'),
  cache = LRU(10),
  equals = function(b) {
    return function(a) {
      return a == b;
    };
  },
  staticPages = [
    '',
    '/faq',
    '/about',
    '/about/careers',
    '/about/contact',
    '/about/team',
    '/admin',
    '/styleguide'
  ];

module.exports = {

  proxy: function(req, res) {
    if (process.env.DISABLE_PROXY) {
      return res.status(503).send('Service Unavailable');
    }

    var u = url.parse(req.url);

    // remove trailing slash
    u.pathname = u.pathname.replace(/\/$/, '');

    // a path without an extension should be served by index.html in
    // the folder of the same name.
    if (!u.pathname.match(/\.\w{2,4}$/)) {

      // for any paths not explicitly listed, serve the Angular app.
      if (!_.any(staticPages, equals(u.pathname))) {
        u.pathname = '/app';
      }

      u.pathname += '/index.html';
    }

    // add the deploy-specific (cache-busting) path prefix
    u.pathname = util.format('assets/%s%s', process.env.BUNDLE_VERSION, u.pathname);

    var newUrl = util.format('%s/%s', process.env.ASSET_HOST_URL, url.format(u));

    // use path without query params as cache key
    var cacheKey = u.pathname,
      cached = (sails.config.environment === 'development' ? null : cache.get(cacheKey));

    if (cached) {
      sails.log.info(util.format(' ☺ %s', newUrl));
      res.ok(cached);
    } else {
      sails.log.info(util.format(' ↑ %s', newUrl));
      request(newUrl, function(err, response, body) {
        if (response && response.statusCode == 403) {
          // a 403 from S3 could also be a 404
          return res.notFound();
        }

        if (err || response.statusCode != 200) {
          var code = (response ? response.statusCode : 'X');
          return res.serverError(util.format("upstream: %s %s", code, err));
        }

        cache.set(cacheKey, body);
        res.ok(body);
      })
    }
  }

}<|endoftext|>


<commit_before>'use strict';
let app = require('app'),
  BrowserWindow = require('browser-window'),
  ipc = require('electron').ipcMain,
  Menu = require('menu'),
  WebSocketServer = require('ws').Server,
  wss = new WebSocketServer({ 'port': 1234 }),
  EddystoneBeacon = require('eddystone-beacon'),
  mainWindow = null,
  mdns = require('mdns'),
  mdnsAd = null,
  modeBLE = null,
  modeMDNS = null,
  activeModes = '';

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  app.quit();
});

function setBleUrl(url, ws) {
  return new Promise((resolve, reject) => {
    try {
      EddystoneBeacon.advertiseUrl(url);
      activeModes += 'Bluetooth';
      mainWindow.webContents.send('status', [`${url} ${activeModes}`, 'Advertising', true]);
      console.log(`ble advertising: ${url}`);
      if (ws) {
        ws.send(`ble advertising: ${url}`);
      }
      resolve();
    } catch (e) {
      console.log(`error: ${e}`);
      mainWindow.webContents.send('status', [e.message, 'Error', false]);
      if (ws) {
        ws.send(`error: ${e}`);
      }
      reject();
    }
  });
}

function setMdnsUrl(url, ws) {
  return new Promise((resolve, reject) => {
    try {
      let urlParts = url.split('/'),
        protocol = urlParts[0].replace(':', ''),
        port = protocol === 'https' ? 443 : 80,
        host = urlParts[2],
        path = urlParts.filter((part, i) => {
          return i > 2 ? part : false;
        }).join('/');
      mdnsAd = new mdns.Advertisement(mdns.tcp(protocol), port, {
        'name': url,
        'txtRecord': {
          'path': path
        },
        'host': host,
        'domain': 'local',
        'ip': host
      });
      mdnsAd.start();
      activeModes += 'mDNS';
      mainWindow.webContents.send('status', [`${url} ${activeModes}`, 'Advertising', true]);
      console.log(`mdns advertising: ${url}`);
      if (ws) {
        ws.send(`mdns advertising: ${url}`);
      }
      resolve();
    } catch (e) {
      console.log(`error: ${e}`);
      mainWindow.webContents.send('status', [e.message, 'Error', false]);
      if (ws) {
        ws.send(`error: ${e}`);
      }
      reject();
    }
  });
}

function stopMdns() {
  if (mdnsAd) {
    mdnsAd.stop();
  }
}

function setUrl(url, ws) {
  activeModes = '';
  stopMdns();
  if (modeBLE.checked || modeMDNS.checked) {
    if (modeBLE.checked) {
      setBleUrl(url, ws).then(() => {
        if (modeMDNS.checked) {
          setMdnsUrl(url, ws);
        }
      });
    }
    if (!modeBLE.checked && modeMDNS.checked) {
      setMdnsUrl(url, ws);
    }
  } else {
    mainWindow.webContents.send('status', ['Choose at least one advertising mode', 'Error', false]);
  }
}

function toggleMode(item) {
  if (item.checked) {
    mainWindow.webContents.send('mode', [item.id, true]);
  } else {
    mainWindow.webContents.send('mode', [item.id, false]);
  }
}

app.on('ready', () => {
  const menuTemplate = [
    {
      'label': 'Eddystone',
      'submenu': [
        {
          'label': 'Advertise URL',
          'accelerator': 'Command+A',
          'click': () => {
            mainWindow.webContents.send('enter-url', 'go');
          }
        },
        {
          'label': 'Stop advertising',
          'accelerator': 'Command+S',
          'click': () => {
            EddystoneBeacon.stop();
            stopMdns();
            mainWindow.webContents.send('status', ['Use bookmarklet or ⌘ + A to enter', 'Waiting', true]);
          }
        },
        {
          'label': 'Quit',
          'accelerator': 'Command+Q',
          'click': () => { app.quit(); }
        }
      ]
    },
    {
      'label': 'Edit',
      'submenu': [
        { 'label': 'Paste', 'accelerator': 'CmdOrCtrl+V', 'selector': 'paste:' }
      ]
    },
    {
      'label': 'Broadcasting modes',
      'submenu': [
        {
          'label': 'Bluetooth',
          'type': 'checkbox',
          'id': 'mode-ble',
          'checked': true,
          'click': item => {
            toggleMode(item);
          }
        },
        {
          'label': 'mDNS',
          'type': 'checkbox',
          'id': 'mode-mdns',
          'checked': false,
          'click': item => {
            toggleMode(item);
          }
        }
      ]
    }
  ];

  let menu = Menu.buildFromTemplate(menuTemplate);
  Menu.setApplicationMenu(menu);
  modeBLE = menu.items[2].submenu.items[0];
  modeMDNS = menu.items[2].submenu.items[1];

  mainWindow = new BrowserWindow({'width': 600, 'height': 400, 'resizable': false});
  mainWindow.loadURL(`file://${__dirname}/index.html`);
  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.webContents.send('status', ['Use bookmarklet or ⌘ + A to enter', 'Waiting', true]);
  });

  wss.on('connection', ws => {
    ws.on('message', url => {
      console.log(`received: ${url}`);
      ws.send(`received: ${url}`);
      setUrl(url, ws);
    });
  });

  ipc.on('set-url', (event, arg) => {
    setUrl(arg);
  });

  ipc.on('set-mode', (event, arg) => {
    switch (arg) {
    case 'mode-ble':
      modeBLE.checked ? modeBLE.checked = false : modeBLE.checked = true;
      toggleMode(modeBLE);
      break;
    case 'mode-mdns':
      modeMDNS.checked ? modeMDNS.checked = false : modeMDNS.checked = true;
      toggleMode(modeMDNS);
      break;
    default:
      break;
    }
  });
});
<commit_msg>change keyboard shortcut to cmd+b for broadcast wording change<commit_after>'use strict';
let app = require('app'),
  BrowserWindow = require('browser-window'),
  ipc = require('electron').ipcMain,
  Menu = require('menu'),
  WebSocketServer = require('ws').Server,
  wss = new WebSocketServer({ 'port': 1234 }),
  EddystoneBeacon = require('eddystone-beacon'),
  mainWindow = null,
  mdns = require('mdns'),
  mdnsAd = null,
  modeBLE = null,
  modeMDNS = null,
  activeModes = '';

// Quit when all windows are closed.
app.on('window-all-closed', () => {
  app.quit();
});

function setBleUrl(url, ws) {
  return new Promise((resolve, reject) => {
    try {
      EddystoneBeacon.advertiseUrl(url);
      activeModes += 'Bluetooth';
      mainWindow.webContents.send('status', [`${url} ${activeModes}`, 'Advertising', true]);
      console.log(`ble advertising: ${url}`);
      if (ws) {
        ws.send(`ble advertising: ${url}`);
      }
      resolve();
    } catch (e) {
      console.log(`error: ${e}`);
      mainWindow.webContents.send('status', [e.message, 'Error', false]);
      if (ws) {
        ws.send(`error: ${e}`);
      }
      reject();
    }
  });
}

function setMdnsUrl(url, ws) {
  return new Promise((resolve, reject) => {
    try {
      let urlParts = url.split('/'),
        protocol = urlParts[0].replace(':', ''),
        port = protocol === 'https' ? 443 : 80,
        host = urlParts[2],
        path = urlParts.filter((part, i) => {
          return i > 2 ? part : false;
        }).join('/');
      mdnsAd = new mdns.Advertisement(mdns.tcp(protocol), port, {
        'name': url,
        'txtRecord': {
          'path': path
        },
        'host': host,
        'domain': 'local',
        'ip': host
      });
      mdnsAd.start();
      activeModes += 'mDNS';
      mainWindow.webContents.send('status', [`${url} ${activeModes}`, 'Advertising', true]);
      console.log(`mdns advertising: ${url}`);
      if (ws) {
        ws.send(`mdns advertising: ${url}`);
      }
      resolve();
    } catch (e) {
      console.log(`error: ${e}`);
      mainWindow.webContents.send('status', [e.message, 'Error', false]);
      if (ws) {
        ws.send(`error: ${e}`);
      }
      reject();
    }
  });
}

function stopMdns() {
  if (mdnsAd) {
    mdnsAd.stop();
  }
}

function setUrl(url, ws) {
  activeModes = '';
  stopMdns();
  if (modeBLE.checked || modeMDNS.checked) {
    if (modeBLE.checked) {
      setBleUrl(url, ws).then(() => {
        if (modeMDNS.checked) {
          setMdnsUrl(url, ws);
        }
      });
    }
    if (!modeBLE.checked && modeMDNS.checked) {
      setMdnsUrl(url, ws);
    }
  } else {
    mainWindow.webContents.send('status', ['Choose at least one advertising mode', 'Error', false]);
  }
}

function toggleMode(item) {
  if (item.checked) {
    mainWindow.webContents.send('mode', [item.id, true]);
  } else {
    mainWindow.webContents.send('mode', [item.id, false]);
  }
}

app.on('ready', () => {
  const menuTemplate = [
    {
      'label': 'Eddystone',
      'submenu': [
        {
          'label': 'Broadcast URL',
          'accelerator': 'Command+B',
          'click': () => {
            mainWindow.webContents.send('enter-url', 'go');
          }
        },
        {
          'label': 'Stop broadcasting',
          'accelerator': 'Command+S',
          'click': () => {
            EddystoneBeacon.stop();
            stopMdns();
            mainWindow.webContents.send('status', ['Use bookmarklet or ⌘ + B to enter', 'Waiting', true]);
          }
        },
        {
          'label': 'Quit',
          'accelerator': 'Command+Q',
          'click': () => { app.quit(); }
        }
      ]
    },
    {
      'label': 'Edit',
      'submenu': [
        { 'label': 'Paste', 'accelerator': 'CmdOrCtrl+V', 'selector': 'paste:' }
      ]
    },
    {
      'label': 'Broadcasting modes',
      'submenu': [
        {
          'label': 'Bluetooth',
          'type': 'checkbox',
          'id': 'mode-ble',
          'checked': true,
          'click': item => {
            toggleMode(item);
          }
        },
        {
          'label': 'mDNS',
          'type': 'checkbox',
          'id': 'mode-mdns',
          'checked': false,
          'click': item => {
            toggleMode(item);
          }
        }
      ]
    }
  ];

  let menu = Menu.buildFromTemplate(menuTemplate);
  Menu.setApplicationMenu(menu);
  modeBLE = menu.items[2].submenu.items[0];
  modeMDNS = menu.items[2].submenu.items[1];

  mainWindow = new BrowserWindow({'width': 600, 'height': 400, 'resizable': false});
  mainWindow.loadURL(`file://${__dirname}/index.html`);
  mainWindow.on('closed', () => {
    mainWindow = null;
  });

  mainWindow.webContents.on('did-finish-load', () => {
    mainWindow.webContents.send('status', ['Use bookmarklet or ⌘ + B to enter', 'Waiting', true]);
  });

  wss.on('connection', ws => {
    ws.on('message', url => {
      console.log(`received: ${url}`);
      ws.send(`received: ${url}`);
      setUrl(url, ws);
    });
  });

  ipc.on('set-url', (event, arg) => {
    setUrl(arg);
  });

  ipc.on('set-mode', (event, arg) => {
    switch (arg) {
    case 'mode-ble':
      modeBLE.checked ? modeBLE.checked = false : modeBLE.checked = true;
      toggleMode(modeBLE);
      break;
    case 'mode-mdns':
      modeMDNS.checked ? modeMDNS.checked = false : modeMDNS.checked = true;
      toggleMode(modeMDNS);
      break;
    default:
      break;
    }
  });
});
<|endoftext|>


<commit_before>const Config = require('webpack-chain')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const webpackBar = require('webpackbar')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const path = require('path')
const fs = require('fs')
const { e2e } = require('yargs').argv
const execa = require('execa')
const isProd = process.env.NODE_ENV === 'production'

function resolve(dir) {
  return path.join(__dirname, '../', dir)
}

const webpackConfig = new Config()
console.log('-----', isProd)
webpackConfig
  .mode(isProd ? 'production' : 'development')
  .devtool(isProd ? 'false' : 'eval-source-map')
  .entry('app')
    .add('./vue/main.js')
    .end()
  .output
    .path(isProd ? path.resolve(__dirname, '../dist/vue') : undefined)
    .publicPath(isProd ? '/examples/' : '/')
    .filename(isProd ? 'static/js/[name].[chunkhash].js' : '[name].js')
    .chunkFilename(isProd ? 'static/js/[id].[chunkhash].js' : '[name].js')
    .end()
  .resolve
    .alias
      .set('vue-example', resolve('vue'))
      .set('common', resolve('common'))
      .end()
    .extensions
      .add('.js')
      .add('.vue')
      .add('.json')
      .add('.ts')
      .end()
    .end()
  .module
    .rule('compileVue')
      .test(/\.vue$/)
      .use('vue')
        .loader('vue-loader')
        .end()
      .end()
    .rule('transformJs')
      .test(/\.js$/)
      .use('babel')
        .loader('babel-loader')
        .options({
          presets: ["@babel/preset-env"]
        })
        .end()
      .include
        .add(resolve('common'))
        .add(resolve('vue'))
        .end()
      .end()
    .rule('url')
      .test(/\.(png|jpe?g|gif|svg|webp)(\?.*)?$/)
      .use('url')
        .loader('url-loader')
        .options({
          limit: 10000,
          name: 'static/img/[name].[hash:7].[ext]'
        })
        .end()
      .end()
    .rule('ts')
      .test(/\.ts$/)
      .use('ts')
        .loader('ts-loader')
        .options({
          transpileOnly: true
        })
        .end()
      .end()
    .rule('css')
      .test(/\.css$/)
      .use('style-loader')
        .loader(
          process.env.NODE_ENV !== 'production' ?
          'vue-style-loader' :
          MiniCssExtractPlugin.loader
        )
        .end()
      .use('css-loader')
        .loader('css-loader')
        .end()
      .end()
    .rule('stylus')
      .test(/.styl(us)?$/)
      .use('style-loader')
        .loader(
          process.env.NODE_ENV !== 'production' ?
          'vue-style-loader' :
          MiniCssExtractPlugin.loader
        )
        .end()
      .use('css-loader')
        .loader('css-loader')
        .end()
      .use('postcss-loader')
        .loader('postcss-loader')
        .end()
      .use('stylus-loader')
        .loader('stylus-loader')
        .end()
      .end()
    .end()
  .plugin('VueLoaderPlugin')
    .use(VueLoaderPlugin)
    .end()
  .plugin('WebpackBar')
    .use(webpackBar)
    .end()
  .plugin('MiniCssExtractPlugin')
    .use(MiniCssExtractPlugin, [{
      filename: 'static/css/[name].[contenthash].css'
    }])
    .end()
  .when(!isProd, () => {
    webpackConfig
      .devServer
        .open(true)
        .hot(true)
        .compress(true)
        .end()
      .plugin('HotModuleReplacementPlugin')
        .use(webpack.HotModuleReplacementPlugin)
        .end()
      .plugin('NoEmitOnErrorsPlugin')
        .use(webpack.NoEmitOnErrorsPlugin)
        .end()
      .plugin('HtmlWebpackPlugin')
        .use(HtmlWebpackPlugin, [{
          filename: 'index.html',
          template: './vue/index.html',
          inject: true
        }])
        .end()
      .plugin('FriendlyErrorsPlugin')
        .use(FriendlyErrorsPlugin)
        .end()
  }, () => {
    webpackConfig
      .optimization
        .minimizer('TerserPlugin')
          .use(TerserPlugin)
        .end()
      .end()
      .plugin('OptimizeCSSPlugin')
        .use(OptimizeCSSPlugin, [{
          cssProcessorOptions: {
            safe: true
          }
        }])
        .end()
      .plugin('HtmlWebpackPlugin')
        .use(HtmlWebpackPlugin, [{
          filename: 'index.html',
          template: './vue/index.html',
          inject: true,
          minify: {
            removeComments: true,
            collapseWhitespace: true,
            removeAttributeQuotes: true
            // more options:
            // https://github.com/kangax/html-minifier#options-quick-reference
          },
          // necessary to consistently work with multiple chunks via CommonsChunkPlugin
          chunksSortMode: 'dependency'
        }])
        .end()
      .plugin('CopyWebpackPlugin')
        .use(CopyWebpackPlugin, [[{
          from: path.resolve(__dirname, '../static'),
          to: 'static',
          ignore: ['.*']
        }]])
        .end()
  })
function getPackagesName() {
  let ret
  let all = fs.readdirSync(resolve('../../packages'))

  // drop hidden file whose name is startWidth '.'
  // drop packages which would not be published(eg: examples and vuepress-docs)
  ret = all
          .filter(name => {
            const isHiddenFile = /^\./g.test(name)
            return !isHiddenFile
          })
          .filter(name => {
            const isPrivatePackages = require(resolve(`../../packages/${name}/package.json`)).private
            return !isPrivatePackages
          })
          .map((name) => {
            return require(resolve(`../../packages/${name}/package.json`)).name
          })

  return ret
}

// add alias
getPackagesName().forEach((name) => {
  webpackConfig.resolve.alias.set(`${name}$`, `${name}/src/index.ts`)
})

let config = { ...webpackConfig.toConfig(), devServer: { host: '0.0.0.0', disableHostCheck: true }}
// run test e2e
if (e2e) {
  config.devServer.setup = (app, server) => {
    server.middleware.waitUntilValid(async () => {
      // back to src directory
      const cwd = path.join(__dirname, '../../')

      await execa('yarn', ['test:e2e'], { stdio: 'inherit', cwd })
    })
  }
}

module.exports = config
<commit_msg>fix(vue-examples): fix url-loader compate<commit_after>const Config = require('webpack-chain')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const webpackBar = require('webpackbar')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')
const TerserPlugin = require('terser-webpack-plugin')
const path = require('path')
const fs = require('fs')
const { e2e } = require('yargs').argv
const execa = require('execa')
const isProd = process.env.NODE_ENV === 'production'

function resolve(dir) {
  return path.join(__dirname, '../', dir)
}

const webpackConfig = new Config()
console.log('-----', isProd)
webpackConfig
  .mode(isProd ? 'production' : 'development')
  .devtool(isProd ? 'false' : 'eval-source-map')
  .entry('app')
    .add('./vue/main.js')
    .end()
  .output
    .path(isProd ? path.resolve(__dirname, '../dist/vue') : undefined)
    .publicPath(isProd ? '/examples/' : '/')
    .filename(isProd ? 'static/js/[name].[chunkhash].js' : '[name].js')
    .chunkFilename(isProd ? 'static/js/[id].[chunkhash].js' : '[name].js')
    .end()
  .resolve
    .alias
      .set('vue-example', resolve('vue'))
      .set('common', resolve('common'))
      .end()
    .extensions
      .add('.js')
      .add('.vue')
      .add('.json')
      .add('.ts')
      .end()
    .end()
  .module
    .rule('compileVue')
      .test(/\.vue$/)
      .use('vue')
        .loader('vue-loader')
        .end()
      .end()
    .rule('transformJs')
      .test(/\.js$/)
      .use('babel')
        .loader('babel-loader')
        .options({
          presets: ["@babel/preset-env"]
        })
        .end()
      .include
        .add(resolve('common'))
        .add(resolve('vue'))
        .end()
      .end()
    .rule('url')
      .test(/\.(png|jpe?g|gif|svg|webp)(\?.*)?$/)
      .use('url')
        .loader('url-loader')
        .options({
          esModule: false,
          limit: 10000,
          name: 'static/img/[name].[hash:7].[ext]'
        })
        .end()
      .end()
    .rule('ts')
      .test(/\.ts$/)
      .use('ts')
        .loader('ts-loader')
        .options({
          transpileOnly: true
        })
        .end()
      .end()
    .rule('css')
      .test(/\.css$/)
      .use('style-loader')
        .loader(
          process.env.NODE_ENV !== 'production' ?
          'vue-style-loader' :
          MiniCssExtractPlugin.loader
        )
        .end()
      .use('css-loader')
        .loader('css-loader')
        .end()
      .end()
    .rule('stylus')
      .test(/.styl(us)?$/)
      .use('style-loader')
        .loader(
          process.env.NODE_ENV !== 'production' ?
          'vue-style-loader' :
          MiniCssExtractPlugin.loader
        )
        .end()
      .use('css-loader')
        .loader('css-loader')
        .end()
      .use('postcss-loader')
        .loader('postcss-loader')
        .end()
      .use('stylus-loader')
        .loader('stylus-loader')
        .end()
      .end()
    .end()
  .plugin('VueLoaderPlugin')
    .use(VueLoaderPlugin)
    .end()
  .plugin('WebpackBar')
    .use(webpackBar)
    .end()
  .plugin('MiniCssExtractPlugin')
    .use(MiniCssExtractPlugin, [{
      filename: 'static/css/[name].[contenthash].css'
    }])
    .end()
  .when(!isProd, () => {
    webpackConfig
      .devServer
        .open(true)
        .hot(true)
        .compress(true)
        .end()
      .plugin('HotModuleReplacementPlugin')
        .use(webpack.HotModuleReplacementPlugin)
        .end()
      .plugin('NoEmitOnErrorsPlugin')
        .use(webpack.NoEmitOnErrorsPlugin)
        .end()
      .plugin('HtmlWebpackPlugin')
        .use(HtmlWebpackPlugin, [{
          filename: 'index.html',
          template: './vue/index.html',
          inject: true
        }])
        .end()
      .plugin('FriendlyErrorsPlugin')
        .use(FriendlyErrorsPlugin)
        .end()
  }, () => {
    webpackConfig
      .optimization
        .minimizer('TerserPlugin')
          .use(TerserPlugin)
        .end()
      .end()
      .plugin('OptimizeCSSPlugin')
        .use(OptimizeCSSPlugin, [{
          cssProcessorOptions: {
            safe: true
          }
        }])
        .end()
      .plugin('HtmlWebpackPlugin')
        .use(HtmlWebpackPlugin, [{
          filename: 'index.html',
          template: './vue/index.html',
          inject: true,
          minify: {
            removeComments: true,
            collapseWhitespace: true,
            removeAttributeQuotes: true
            // more options:
            // https://github.com/kangax/html-minifier#options-quick-reference
          },
          // necessary to consistently work with multiple chunks via CommonsChunkPlugin
          chunksSortMode: 'dependency'
        }])
        .end()
      .plugin('CopyWebpackPlugin')
        .use(CopyWebpackPlugin, [[{
          from: path.resolve(__dirname, '../static'),
          to: 'static',
          ignore: ['.*']
        }]])
        .end()
  })
function getPackagesName() {
  let ret
  let all = fs.readdirSync(resolve('../../packages'))

  // drop hidden file whose name is startWidth '.'
  // drop packages which would not be published(eg: examples and vuepress-docs)
  ret = all
          .filter(name => {
            const isHiddenFile = /^\./g.test(name)
            return !isHiddenFile
          })
          .filter(name => {
            const isPrivatePackages = require(resolve(`../../packages/${name}/package.json`)).private
            return !isPrivatePackages
          })
          .map((name) => {
            return require(resolve(`../../packages/${name}/package.json`)).name
          })

  return ret
}

// add alias
getPackagesName().forEach((name) => {
  webpackConfig.resolve.alias.set(`${name}$`, `${name}/src/index.ts`)
})

let config = { ...webpackConfig.toConfig(), devServer: { host: '0.0.0.0', disableHostCheck: true }}
// run test e2e
if (e2e) {
  config.devServer.setup = (app, server) => {
    server.middleware.waitUntilValid(async () => {
      // back to src directory
      const cwd = path.join(__dirname, '../../')

      await execa('yarn', ['test:e2e'], { stdio: 'inherit', cwd })
    })
  }
}

module.exports = config
<|endoftext|>


<commit_before>angular.module('scraper', []);

angular.module('scraper',[])
  .controller('MainController', function($scope, $interval, $http) {

    $scope.successItem = 0;
    $scope.failureItem = 0;

    $scope.startCount = 1;
    $scope.endCount = 2000;

    $scope.scraping = false;

    // loop through the start count and stop count.
    var pullAndwrite = function() {
      if ( $scope.startCount < $scope.endCount ) {
        for ( var i = $scope.startCount; i < $scope.endCount; i++) {
          $http.get("https://hacker-news.firebaseio.com/v0/item/" + i + ".json")
            // able to pull from the Hacker News API
            .success(function(firebaseData) {
              $http({
                url: 'http://localhost:8000/',
                method: 'POST',
                data: firebaseData
              })
              // $http.post("http://localhost:8000/", firebaseData )
              // able to store to the file *should be database*
              .success(function(data, status, headers, config) {
                $scope.successItem++;
              })
              // unable to store to the file
              .error(function(data, status, headers, config) {
                console.log(data);
                $scope.failureItem++;
              });
            })
            // unable to pull from the Hacker News API
            .error(function(data, status, headers, config) {
              console.log(data);
              $scope.failureItem++;
            });
        }
      } else {
        for ( var i = $scope.startCount; i > $scope.endCount; i--) {
          $http.get("https://hacker-news.firebaseio.com/v0/item/" + i + ".json")
            // able to pull from the Hacker News API
            .success(function(firebaseData) {
              $http({
                url: 'http://localhost:8000/',
                method: 'POST',
                data: firebaseData
              })
              // $http.post("http://localhost:8000/", firebaseData )
              // able to store to the file *should be database*
              .success(function(data, status, headers, config) {
                $scope.successItem++;
              })
              // unable to store to the file
              .error(function(data, status, headers, config) {
                console.log(data);
                $scope.failureItem++;
              });
            })
            // unable to pull from the Hacker News API
            .error(function(data, status, headers, config) {
              console.log(data);
              $scope.failureItem++;
            });
        }
      }
    };

    $scope.startScrape = function() {
      $scope.scraping = true;
      // pullAndwrite();

      // every minute run http get and post requests.
      // $interval(function() {
      //   pullAndwrite();
      // }, 60000);

      // if ($scope.startCount < $scope.endCount) {
      //   $scope.startCount += 2000;
      //   $scope.endCount += 2000;
      // } else {
      //   $scope.startCount -= 2000;
      //   $scope.endCount -= 2000;
      // }
    };

  });<commit_msg>(refactor) un-commented for functionality<commit_after>angular.module('scraper', []);

angular.module('scraper',[])
  .controller('MainController', function($scope, $interval, $http) {

    $scope.successItem = 0;
    $scope.failureItem = 0;

    $scope.startCount = 1;
    $scope.endCount = 2000;

    $scope.scraping = false;

    // loop through the start count and stop count.
    var pullAndwrite = function() {
      if ( $scope.startCount < $scope.endCount ) {
        for ( var i = $scope.startCount; i < $scope.endCount; i++) {
          $http.get("https://hacker-news.firebaseio.com/v0/item/" + i + ".json")
            // able to pull from the Hacker News API
            .success(function(firebaseData) {
              $http({
                url: 'http://localhost:8000/',
                method: 'POST',
                data: firebaseData
              })
              // $http.post("http://localhost:8000/", firebaseData )
              // able to store to the file *should be database*
              .success(function(data, status, headers, config) {
                $scope.successItem++;
              })
              // unable to store to the file
              .error(function(data, status, headers, config) {
                console.log(data);
                $scope.failureItem++;
              });
            })
            // unable to pull from the Hacker News API
            .error(function(data, status, headers, config) {
              console.log(data);
              $scope.failureItem++;
            });
        }
      } else {
        for ( var i = $scope.startCount; i > $scope.endCount; i--) {
          $http.get("https://hacker-news.firebaseio.com/v0/item/" + i + ".json")
            // able to pull from the Hacker News API
            .success(function(firebaseData) {
              $http({
                url: 'http://localhost:8000/',
                method: 'POST',
                data: firebaseData
              })
              // $http.post("http://localhost:8000/", firebaseData )
              // able to store to the file *should be database*
              .success(function(data, status, headers, config) {
                $scope.successItem++;
              })
              // unable to store to the file
              .error(function(data, status, headers, config) {
                console.log(data);
                $scope.failureItem++;
              });
            })
            // unable to pull from the Hacker News API
            .error(function(data, status, headers, config) {
              console.log(data);
              $scope.failureItem++;
            });
        }
      }
    };

    $scope.startScrape = function() {
      $scope.scraping = true;
      pullAndwrite();

      // every minute run http get and post requests.
      $interval(function() {
        pullAndwrite();
      }, 60000);

      if ($scope.startCount < $scope.endCount) {
        $scope.startCount += 2000;
        $scope.endCount += 2000;
      } else {
        $scope.startCount -= 2000;
        $scope.endCount -= 2000;
      }
    };

  });<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations under
// the License.

// Do some basic tests.
couchTests.basics = function(debug) {
    var result = JSON.parse(CouchDB.request("GET", "/").responseText);
    T(result.couchdb == "Welcome");

    var db = new CouchDB("test_suite_db");
    db.deleteDb();

    // bug COUCHDB-100: DELETE on non-existent DB returns 500 instead of 404
    db.deleteDb();

    db.createDb();

    // PUT on existing DB should return 412 instead of 500
    xhr = CouchDB.request("PUT", "/test_suite_db/");
    T(xhr.status == 412);
    if (debug) debugger;

    // creating a new DB should return Location header
    xhr = CouchDB.request("DELETE", "/new-db");
    xhr = CouchDB.request("PUT", "/new-db");
    TEquals("/new-db", xhr.getResponseHeader("Location"),
      "should return newly created database name in location header");

    // Get the database info, check the db_name
    T(db.info().db_name == "test_suite_db");

    // Get the database info, check the doc_count
    T(db.info().doc_count == 0);

    // create a document and save it to the database
    var doc = {_id:"0",a:1,b:1};
    var result = db.save(doc);

    T(result.ok==true); // return object has an ok member with a value true
    T(result.id); // the _id of the document is set.
    T(result.rev); // the revision id of the document is set.

    // Verify the input doc is now set with the doc id and rev
    // (for caller convenience).
    T(doc._id == result.id && doc._rev == result.rev);

    var id = result.id; // save off the id for later

    // make sure the revs_info status is good
    var doc = db.open(id, {revs_info:true});
    T(doc._revs_info[0].status == "available");

    // Create some more documents.
    // Notice the use of the ok member on the return result.
    T(db.save({_id:"1",a:2,b:4}).ok);
    T(db.save({_id:"2",a:3,b:9}).ok);
    T(db.save({_id:"3",a:4,b:16}).ok);

    // Check the database doc count
    T(db.info().doc_count == 4);

    // Test a simple map functions

    // create a map function that selects all documents whose "a" member
    // has a value of 4, and then returns the document's b value.
    var mapFunction = function(doc){
      if (doc.a==4)
        emit(null, doc.b);
    };

    results = db.query(mapFunction);

    // verify only one document found and the result value (doc.b).
    T(results.total_rows == 1 && results.rows[0].value == 16);

    // reopen document we saved earlier
    existingDoc = db.open(id);

    T(existingDoc.a==1);

    //modify and save
    existingDoc.a=4;
    db.save(existingDoc);

    // redo the map query
    results = db.query(mapFunction);

    // the modified document should now be in the results.
    T(results.total_rows == 2);

    // write 2 more documents
    T(db.save({a:3,b:9}).ok);
    T(db.save({a:4,b:16}).ok);

    results = db.query(mapFunction);

    // 1 more document should now be in the result.
    T(results.total_rows == 3);
    T(db.info().doc_count == 6);

    var reduceFunction = function(keys, values){
      return sum(values);
    };

    results = db.query(mapFunction, reduceFunction);

    T(results.rows[0].value == 33);

    // delete a document
    T(db.deleteDoc(existingDoc).ok);

    // make sure we can't open the doc
    T(db.open(existingDoc._id) == null);

    results = db.query(mapFunction);

    // 1 less document should now be in the results.
    T(results.total_rows == 2);
    T(db.info().doc_count == 5);

    // make sure we can still open the old rev of the deleted doc
    T(db.open(existingDoc._id, {rev: existingDoc._rev}) != null);

    // make sure restart works
    T(db.ensureFullCommit().ok);
    restartServer();

    // make sure we can still open
    T(db.open(existingDoc._id, {rev: existingDoc._rev}) != null);

    // test that the POST response has a Location header
    var xhr = CouchDB.request("POST", "/test_suite_db", {
      body: JSON.stringify({"foo":"bar"})
    });
    var resp = JSON.parse(xhr.responseText);
    T(resp.ok);
    var loc = xhr.getResponseHeader("Location");
    T(loc, "should have a Location header");
    var locs = loc.split('/');
    T(locs[4] == resp.id);
    T(locs[3] == "test_suite_db");

    // deleting a non-existent doc should be 404
    xhr = CouchDB.request("DELETE", "/test_suite_db/doc-does-not-exist");
    T(xhr.status == 404);
  };
<commit_msg>return a Location header on newly created documents using PUT requests<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License.  You may obtain a copy
// of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
// License for the specific language governing permissions and limitations under
// the License.

// Do some basic tests.
couchTests.basics = function(debug) {
    var result = JSON.parse(CouchDB.request("GET", "/").responseText);
    T(result.couchdb == "Welcome");

    var db = new CouchDB("test_suite_db");
    db.deleteDb();

    // bug COUCHDB-100: DELETE on non-existent DB returns 500 instead of 404
    db.deleteDb();

    db.createDb();

    // PUT on existing DB should return 412 instead of 500
    xhr = CouchDB.request("PUT", "/test_suite_db/");
    T(xhr.status == 412);
    if (debug) debugger;

    // creating a new DB should return Location header
    xhr = CouchDB.request("DELETE", "/new-db");
    xhr = CouchDB.request("PUT", "/new-db");
    TEquals("/new-db", xhr.getResponseHeader("Location"),
      "should return newly created database name in location header");

    // Get the database info, check the db_name
    T(db.info().db_name == "test_suite_db");

    // Get the database info, check the doc_count
    T(db.info().doc_count == 0);

    // create a document and save it to the database
    var doc = {_id:"0",a:1,b:1};
    var result = db.save(doc);

    T(result.ok==true); // return object has an ok member with a value true
    T(result.id); // the _id of the document is set.
    T(result.rev); // the revision id of the document is set.

    // Verify the input doc is now set with the doc id and rev
    // (for caller convenience).
    T(doc._id == result.id && doc._rev == result.rev);

    var id = result.id; // save off the id for later

    // make sure the revs_info status is good
    var doc = db.open(id, {revs_info:true});
    T(doc._revs_info[0].status == "available");

    // Create some more documents.
    // Notice the use of the ok member on the return result.
    T(db.save({_id:"1",a:2,b:4}).ok);
    T(db.save({_id:"2",a:3,b:9}).ok);
    T(db.save({_id:"3",a:4,b:16}).ok);

    // Check the database doc count
    T(db.info().doc_count == 4);

    // Test a simple map functions

    // create a map function that selects all documents whose "a" member
    // has a value of 4, and then returns the document's b value.
    var mapFunction = function(doc){
      if (doc.a==4)
        emit(null, doc.b);
    };

    results = db.query(mapFunction);

    // verify only one document found and the result value (doc.b).
    T(results.total_rows == 1 && results.rows[0].value == 16);

    // reopen document we saved earlier
    existingDoc = db.open(id);

    T(existingDoc.a==1);

    //modify and save
    existingDoc.a=4;
    db.save(existingDoc);

    // redo the map query
    results = db.query(mapFunction);

    // the modified document should now be in the results.
    T(results.total_rows == 2);

    // write 2 more documents
    T(db.save({a:3,b:9}).ok);
    T(db.save({a:4,b:16}).ok);

    results = db.query(mapFunction);

    // 1 more document should now be in the result.
    T(results.total_rows == 3);
    T(db.info().doc_count == 6);

    var reduceFunction = function(keys, values){
      return sum(values);
    };

    results = db.query(mapFunction, reduceFunction);

    T(results.rows[0].value == 33);

    // delete a document
    T(db.deleteDoc(existingDoc).ok);

    // make sure we can't open the doc
    T(db.open(existingDoc._id) == null);

    results = db.query(mapFunction);

    // 1 less document should now be in the results.
    T(results.total_rows == 2);
    T(db.info().doc_count == 5);

    // make sure we can still open the old rev of the deleted doc
    T(db.open(existingDoc._id, {rev: existingDoc._rev}) != null);

    // make sure restart works
    T(db.ensureFullCommit().ok);
    restartServer();

    // make sure we can still open
    T(db.open(existingDoc._id, {rev: existingDoc._rev}) != null);

    // test that the POST response has a Location header
    var xhr = CouchDB.request("POST", "/test_suite_db", {
      body: JSON.stringify({"foo":"bar"})
    });
    var resp = JSON.parse(xhr.responseText);
    T(resp.ok);
    var loc = xhr.getResponseHeader("Location");
    T(loc, "should have a Location header");
    var locs = loc.split('/');
    T(locs[4] == resp.id);
    T(locs[3] == "test_suite_db");

    // document put's should return a Location header
    var xhr = CouchDB.request("PUT", "/test_suite_db/newdoc", {
      body: JSON.stringify({"a":1})
    });
    TEquals("/test_suite_db/newdoc", xhr.getResponseHeader("Location"),
      "should return Location header to newly created document");

    // deleting a non-existent doc should be 404
    xhr = CouchDB.request("DELETE", "/test_suite_db/doc-does-not-exist");
    T(xhr.status == 404);
  };
<|endoftext|>


<commit_before>var app = require('app')
var setting = require('./module/setting')
var BrowserWindow = require('browser-window')

var window = null

// Generate default settings
setting
.default('app.check_for_updates', true)
.default('app.startup_update_delay', 1000)
.default('game.show_ko_warning', true)
.default('game.show_suicide_warning', true)
.default('graph.delay', 300)
.default('graph.grid_size', 25)
.default('graph.node_size', 4)
.default('scoring.method', 'territory')
.default('sound.enable', true)
.default('view.fuzzy_stone_placement', true)
.default('view.show_coordinates', false)
.default('view.show_variations', true)
.default('view.show_sidebar', false)
.default('view.sidebar_width', 200)
.default('view.sidebar_minwidth', 100)
.default('window.height', 648)
.default('window.minheight', 590)
.default('window.minwidth', 550)
.default('window.width', 608)

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    if (process.platform != 'darwin')
        app.quit()
})

app.on('ready', function() {
    window = new BrowserWindow({
        'width': setting.get('window.width'),
        'height': setting.get('window.height'),
        'min-width': setting.get('window.minwidth'),
        'min-height': setting.get('window.minheight'),
        'use-content-size': true,
        'show': false,
        'web-preferences': {
            'text-areas-are-resizable': false
        }
    })

    // window.toggleDevTools()
    window.webContents.setAudioMuted(!setting.get('sound.enable'))

    window.on('closed', function() { window = null })
    window.webContents.on("will-navigate", function(e, url) { e.preventDefault() })
    window.webContents.on('dom-ready', function() { window.show() })

    window.loadUrl('file://' + __dirname + '/view/index.html')
})
<commit_msg>Refreshing works again<commit_after>var app = require('app')
var setting = require('./module/setting')
var BrowserWindow = require('browser-window')

var window = null

// Generate default settings
setting
.default('app.check_for_updates', true)
.default('app.startup_update_delay', 1000)
.default('game.show_ko_warning', true)
.default('game.show_suicide_warning', true)
.default('graph.delay', 300)
.default('graph.grid_size', 25)
.default('graph.node_size', 4)
.default('scoring.method', 'territory')
.default('sound.enable', true)
.default('view.fuzzy_stone_placement', true)
.default('view.show_coordinates', false)
.default('view.show_variations', true)
.default('view.show_sidebar', false)
.default('view.sidebar_width', 200)
.default('view.sidebar_minwidth', 100)
.default('window.height', 648)
.default('window.minheight', 590)
.default('window.minwidth', 550)
.default('window.width', 608)

// Quit when all windows are closed.
app.on('window-all-closed', function() {
    if (process.platform != 'darwin')
        app.quit()
})

app.on('ready', function() {
    window = new BrowserWindow({
        'width': setting.get('window.width'),
        'height': setting.get('window.height'),
        'min-width': setting.get('window.minwidth'),
        'min-height': setting.get('window.minheight'),
        'use-content-size': true,
        'show': false,
        'web-preferences': {
            'text-areas-are-resizable': false
        }
    })

    // window.toggleDevTools()
    window.webContents.setAudioMuted(!setting.get('sound.enable'))

    window.on('closed', function() { window = null })
    window.webContents.on('dom-ready', function() { window.show() })

    window.loadUrl('file://' + __dirname + '/view/index.html')
})
<|endoftext|>


<commit_before>/**
 * HashTable Class
 */

function HashTable(objeto) {

  var colecao = {};
  var tamanho = 0;

  for (var propriedade in objeto) {
    if (objeto.hasOwnProperty(propriedade)) {
      this.colecao[propriedade] = objeto[propriedade];
      this.tamanho++;
    }
  }

  console.log(objeto);

}

HashTable.prototype = {

};

exports.HashTable = HashTable;

if (require.main == module) {
  var ht = new HashTable({t: 't', s: 's', k: 'k'});
  console.log(ht);
  console.log(ht.list());
}
<commit_msg>Adiciona getters and setters<commit_after>/**
 * HashTable Class
 */

function HashTable(objeto) {

  var items = {};
  var tamanho = 0;

  for (var propriedade in objeto) {
    if (objeto.hasOwnProperty(propriedade)) {
      this.items[propriedade] = objeto[propriedade];
      this.tamanho++;
    }
  }

  console.log(objeto);

}

HashTable.prototype = {

  setItem = function (chave, argumento) {
    var antecedente = undefined;
    if (this.hasItem(chave)) {
      antecedente = this.items[chave];
    } else {
      this.length++;
    }
    this.items[chave] = valor;
    return antecedente;
  },

  getItem = function (chave) {
    return this.hasItem(chave) ? this.items[chave] : undefined;
  }

};

exports.HashTable = HashTable;

if (require.main == module) {
  var ht = new HashTable({t: 't', s: 's', k: 'k'});
  console.log(ht);
  console.log(ht.list());
}
<|endoftext|>


<commit_before>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

couchTests.config = function(debug) {
  var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"false"});
  db.deleteDb();
  db.createDb();
  if (debug) debugger;

  // test that /_config returns all the settings
  var xhr = CouchDB.request("GET", "/_config");
  var config = JSON.parse(xhr.responseText);

  /*
    if we run on standard ports, we can't extract
    the number from the URL. Instead we try to guess
    from the protocol what port we are running on.
    If we can't guess, we don't test for the port.
    Overengineering FTW.
  */
  var server_port = CouchDB.host.split(':');
  if(server_port.length == 1 && CouchDB.inBrowser) {
    if(CouchDB.protocol == "http://") {
      port = "80";
    }
    if(CouchDB.protocol == "https://") {
      port = "443";
    }
  } else {
    port = server_port.pop();
  }

  if(CouchDB.protocol == "http://") {
    config_port = config.httpd.port;
  }
  if(CouchDB.protocol == "https://") {
    config_port = config.ssl.port;
  }

  if(port && config_port != "0") {
    TEquals(config_port, port, "ports should match");
  }

  T(config.couchdb.database_dir);
  T(config.daemons.httpd);
  T(config.httpd_global_handlers._config);
  T(config.log.level);
  T(config.query_servers.javascript);

  // test that settings can be altered, and that an undefined whitelist allows any change
  TEquals(undefined, config.httpd.config_whitelist, "Default whitelist is empty");
  xhr = CouchDB.request("PUT", "/_config/test/foo",{
    body : JSON.stringify("bar"),
    headers: {"X-Couch-Persist": "false"}
  });
  T(xhr.status == 200);
  xhr = CouchDB.request("GET", "/_config/test");
  config = JSON.parse(xhr.responseText);
  T(config.foo == "bar");

  // you can get a single key
  xhr = CouchDB.request("GET", "/_config/test/foo");
  config = JSON.parse(xhr.responseText);
  T(config == "bar");

  // Non-term whitelist values allow further modification of the whitelist.
  xhr = CouchDB.request("PUT", "/_config/httpd/config_whitelist",{
    body : JSON.stringify("!This is an invalid Erlang term!"),
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Set config whitelist to an invalid Erlang term");
  xhr = CouchDB.request("DELETE", "/_config/httpd/config_whitelist",{
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Modify whitelist despite it being invalid syntax");

  // Non-list whitelist values allow further modification of the whitelist.
  xhr = CouchDB.request("PUT", "/_config/httpd/config_whitelist",{
    body : JSON.stringify("{[yes, a_valid_erlang_term, but_unfortunately, not_a_list]}"),
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Set config whitelist to an non-list term");
  xhr = CouchDB.request("DELETE", "/_config/httpd/config_whitelist",{
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Modify whitelist despite it not being a list");

  // Keys not in the whitelist may not be modified.
  xhr = CouchDB.request("PUT", "/_config/httpd/config_whitelist",{
    body : JSON.stringify("[{httpd,config_whitelist}, {test,foo}]"),
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Set config whitelist to something valid");

  ["PUT", "DELETE"].forEach(function(method) {
    ["test/not_foo", "not_test/foo", "neither_test/nor_foo"].forEach(function(pair) {
      var path = "/_config/" + pair;
      var test_name = method + " to " + path + " disallowed: not whitelisted";

      xhr = CouchDB.request(method, path, {
        body : JSON.stringify("Bummer! " + test_name),
        headers: {"X-Couch-Persist": "false"}
      });
      TEquals(400, xhr.status, test_name);
    });
  });

  // Keys in the whitelist may be modified.
  ["PUT", "DELETE"].forEach(function(method) {
    xhr = CouchDB.request(method, "/_config/test/foo",{
      body : JSON.stringify(method + " to whitelisted config variable"),
      headers: {"X-Couch-Persist": "false"}
    });
    TEquals(200, xhr.status, "Keys in the whitelist may be modified");
  });

  // Non-2-tuples in the whitelist are ignored
  xhr = CouchDB.request("PUT", "/_config/httpd/config_whitelist",{
    body : JSON.stringify("[{httpd,config_whitelist}, these, {are}, {nOt, 2, tuples}," +
                          " [so], [they, will], [all, become, noops], {test,foo}]"),
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Set config whitelist with some inert values");
  ["PUT", "DELETE"].forEach(function(method) {
    xhr = CouchDB.request(method, "/_config/test/foo",{
      body : JSON.stringify(method + " to whitelisted config variable"),
      headers: {"X-Couch-Persist": "false"}
    });
    TEquals(200, xhr.status, "Update whitelisted variable despite invalid entries");
  });

  // Atoms, binaries, and strings suffice as whitelist sections and keys.
  ["{test,foo}", '{"test","foo"}', '{<<"test">>,<<"foo">>}'].forEach(function(pair) {
    xhr = CouchDB.request("PUT", "/_config/httpd/config_whitelist",{
      body : JSON.stringify("[{httpd,config_whitelist}, " + pair + "]"),
      headers: {"X-Couch-Persist": "false"}
    });
    TEquals(200, xhr.status, "Set config whitelist to include " + pair);

    var pair_format = {"t":"tuple", '"':"string", "<":"binary"}[pair[1]];
    ["PUT", "DELETE"].forEach(function(method) {
      xhr = CouchDB.request(method, "/_config/test/foo",{
        body : JSON.stringify(method + " with " + pair_format),
        headers: {"X-Couch-Persist": "false"}
      });
      TEquals(200, xhr.status, "Whitelist works with " + pair_format);
    });
  });

  xhr = CouchDB.request("DELETE", "/_config/httpd/config_whitelist",{
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Reset config whitelist to undefined");
};
<commit_msg>Allow storing a pre-hashed admin password<commit_after>// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.

couchTests.config = function(debug) {
  var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"false"});
  db.deleteDb();
  db.createDb();
  if (debug) debugger;

  // test that /_config returns all the settings
  var xhr = CouchDB.request("GET", "/_config");
  var config = JSON.parse(xhr.responseText);

  /*
    if we run on standard ports, we can't extract
    the number from the URL. Instead we try to guess
    from the protocol what port we are running on.
    If we can't guess, we don't test for the port.
    Overengineering FTW.
  */
  var server_port = CouchDB.host.split(':');
  if(server_port.length == 1 && CouchDB.inBrowser) {
    if(CouchDB.protocol == "http://") {
      port = "80";
    }
    if(CouchDB.protocol == "https://") {
      port = "443";
    }
  } else {
    port = server_port.pop();
  }

  if(CouchDB.protocol == "http://") {
    config_port = config.httpd.port;
  }
  if(CouchDB.protocol == "https://") {
    config_port = config.ssl.port;
  }

  if(port && config_port != "0") {
    TEquals(config_port, port, "ports should match");
  }

  T(config.couchdb.database_dir);
  T(config.daemons.httpd);
  T(config.httpd_global_handlers._config);
  T(config.log.level);
  T(config.query_servers.javascript);

  // test that settings can be altered, and that an undefined whitelist allows any change
  TEquals(undefined, config.httpd.config_whitelist, "Default whitelist is empty");
  xhr = CouchDB.request("PUT", "/_config/test/foo",{
    body : JSON.stringify("bar"),
    headers: {"X-Couch-Persist": "false"}
  });
  T(xhr.status == 200);
  xhr = CouchDB.request("GET", "/_config/test");
  config = JSON.parse(xhr.responseText);
  T(config.foo == "bar");

  // you can get a single key
  xhr = CouchDB.request("GET", "/_config/test/foo");
  config = JSON.parse(xhr.responseText);
  T(config == "bar");

  // Server-side password hashing, and raw updates disabling that.
  var password_plain = 's3cret';
  var password_hashed = null;

  xhr = CouchDB.request("PUT", "/_config/admins/administrator",{
    body : JSON.stringify(password_plain),
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Create an admin in the config");

  T(CouchDB.login("administrator", password_plain).ok);

  xhr = CouchDB.request("GET", "/_config/admins/administrator");
  password_hashed = JSON.parse(xhr.responseText);
  T(password_hashed.match(/^-pbkdf2-/) || password_hashed.match(/^-hashed-/),
    "Admin password is hashed");

  xhr = CouchDB.request("PUT", "/_config/admins/administrator?raw=nothanks",{
    body : JSON.stringify(password_hashed),
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(400, xhr.status, "CouchDB rejects an invalid 'raw' option");

  xhr = CouchDB.request("PUT", "/_config/admins/administrator?raw=true",{
    body : JSON.stringify(password_hashed),
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Set an raw, pre-hashed admin password");

  xhr = CouchDB.request("PUT", "/_config/admins/administrator?raw=false",{
    body : JSON.stringify(password_hashed),
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Set an admin password with raw=false");

  // The password is literally the string "-pbkdf2-abcd...".
  T(CouchDB.login("administrator", password_hashed).ok);

  xhr = CouchDB.request("GET", "/_config/admins/administrator");
  T(password_hashed != JSON.parse(xhr.responseText),
    "Hashed password was not stored as a raw string");

  xhr = CouchDB.request("DELETE", "/_config/admins/administrator",{
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Delete an admin from the config");
  T(CouchDB.logout().ok);

  // Non-term whitelist values allow further modification of the whitelist.
  xhr = CouchDB.request("PUT", "/_config/httpd/config_whitelist",{
    body : JSON.stringify("!This is an invalid Erlang term!"),
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Set config whitelist to an invalid Erlang term");
  xhr = CouchDB.request("DELETE", "/_config/httpd/config_whitelist",{
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Modify whitelist despite it being invalid syntax");

  // Non-list whitelist values allow further modification of the whitelist.
  xhr = CouchDB.request("PUT", "/_config/httpd/config_whitelist",{
    body : JSON.stringify("{[yes, a_valid_erlang_term, but_unfortunately, not_a_list]}"),
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Set config whitelist to an non-list term");
  xhr = CouchDB.request("DELETE", "/_config/httpd/config_whitelist",{
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Modify whitelist despite it not being a list");

  // Keys not in the whitelist may not be modified.
  xhr = CouchDB.request("PUT", "/_config/httpd/config_whitelist",{
    body : JSON.stringify("[{httpd,config_whitelist}, {test,foo}]"),
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Set config whitelist to something valid");

  ["PUT", "DELETE"].forEach(function(method) {
    ["test/not_foo", "not_test/foo", "neither_test/nor_foo"].forEach(function(pair) {
      var path = "/_config/" + pair;
      var test_name = method + " to " + path + " disallowed: not whitelisted";

      xhr = CouchDB.request(method, path, {
        body : JSON.stringify("Bummer! " + test_name),
        headers: {"X-Couch-Persist": "false"}
      });
      TEquals(400, xhr.status, test_name);
    });
  });

  // Keys in the whitelist may be modified.
  ["PUT", "DELETE"].forEach(function(method) {
    xhr = CouchDB.request(method, "/_config/test/foo",{
      body : JSON.stringify(method + " to whitelisted config variable"),
      headers: {"X-Couch-Persist": "false"}
    });
    TEquals(200, xhr.status, "Keys in the whitelist may be modified");
  });

  // Non-2-tuples in the whitelist are ignored
  xhr = CouchDB.request("PUT", "/_config/httpd/config_whitelist",{
    body : JSON.stringify("[{httpd,config_whitelist}, these, {are}, {nOt, 2, tuples}," +
                          " [so], [they, will], [all, become, noops], {test,foo}]"),
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Set config whitelist with some inert values");
  ["PUT", "DELETE"].forEach(function(method) {
    xhr = CouchDB.request(method, "/_config/test/foo",{
      body : JSON.stringify(method + " to whitelisted config variable"),
      headers: {"X-Couch-Persist": "false"}
    });
    TEquals(200, xhr.status, "Update whitelisted variable despite invalid entries");
  });

  // Atoms, binaries, and strings suffice as whitelist sections and keys.
  ["{test,foo}", '{"test","foo"}', '{<<"test">>,<<"foo">>}'].forEach(function(pair) {
    xhr = CouchDB.request("PUT", "/_config/httpd/config_whitelist",{
      body : JSON.stringify("[{httpd,config_whitelist}, " + pair + "]"),
      headers: {"X-Couch-Persist": "false"}
    });
    TEquals(200, xhr.status, "Set config whitelist to include " + pair);

    var pair_format = {"t":"tuple", '"':"string", "<":"binary"}[pair[1]];
    ["PUT", "DELETE"].forEach(function(method) {
      xhr = CouchDB.request(method, "/_config/test/foo",{
        body : JSON.stringify(method + " with " + pair_format),
        headers: {"X-Couch-Persist": "false"}
      });
      TEquals(200, xhr.status, "Whitelist works with " + pair_format);
    });
  });

  xhr = CouchDB.request("DELETE", "/_config/httpd/config_whitelist",{
    headers: {"X-Couch-Persist": "false"}
  });
  TEquals(200, xhr.status, "Reset config whitelist to undefined");
};
<|endoftext|>