<commit_before>/**
 * Will calculate the number of current warnings for each ASAT and then sets it
 */
function updateASATWarningsCount(d) {
	var mainLabels = ["checkStyleLabel", "PMDLabel", "FindBugsLabel"];
	var mainTitles = ["CheckStyle", "PMD", "FindBugs"];

		var total = 0;
		var cat = categoryMapper.getDefects(i);
		for ( var index =0; index < mainTitles.length; index++){
			var warning = sumNodeForASAT(d, getTotalASATWarning(mainTitles[index], d.fileName));
			document.getElementById(mainLabels[index]).innerHTML = '  '+ mainLabels[index] + ' (' + warning + ")";
				total += warning;
		}
}

/**
 * Will calculate the number of current warnings for the function defects category and then sets it
 */
function updateDefectsCount(d) {
	var mainLabels = ["FuncDefLabel", "MainDefLabel", "OthLabel"];
	var mainLabelsTitles = ["Functional Defects", "Maintainability Defects", "Other"];

	for ( var i =0; i< 2; i++) {
		var total = 0;
		var catLabel = categoryMapper.getDefectLabels(i);
		var cat = categoryMapper.getDefects(i);
		for ( var index =0; index < cat.length; index++){
			var warning = sumNodeForASAT(d, getTotalCategoryWarning(cat[index], d.fileName));
		console.log(warning);
			document.getElementById(catLabel[index]).innerHTML = '  '+ cat[index] + ' (' + warning + ")";
			if( acceptedCategories.indexOf(cat[index]) >= 0){
				total += warning;
			}
		}
		document.getElementById(mainLabels[i]).innerHTML = ' ' + mainLabelsTitles[i] + ' (' +
			total + ")  ";
	}
}

/**
 * Sums for each node how many warnings they have.
 */
function sumNodeForASAT(d, root) {
    var nodeAndSummation = [];
    var sum = 0;
    if (d.fileName == projectName) {
        for (var i = 0; i < root.length; i++) {
            for (var j = 0; j < root[i].length; j++) {
                sum += root[i][j].amountOfWarnings;
             }
         }
         return sum;
    } else {
        for (var i = 0; i < root.length; i++) {
            if(treeMapBuilder.getSourceCodeLevel()) {
                if (root[i].packageName == d.parent.fileName) {
                    for (var j = 0; j < root[i].length; j++) {
                        if(treeMapBuilder.getSourceCodeLevel() && root[i][j].fileName == treeMapBuilder.getCurrentClassName()) {
                            return root[i][j].amountOfWarnings;
                        }
                        sum += root[i][j].amountOfWarnings;
                    }
                    return sum;
                }
            } else {
                if (root[i].packageName == d.fileName) {
                    for (var j = 0; j < root[i].length; j++) {
                        sum += root[i][j].amountOfWarnings;
                    }
                    return sum;
                }
            }
        }
    }
    return -1;
}<commit_msg>Removed console logs<commit_after>/**
 * Will calculate the number of current warnings for each ASAT and then sets it
 */
function updateASATWarningsCount(d) {
	var mainLabels = ["checkStyleLabel", "PMDLabel", "FindBugsLabel"];
	var mainTitles = ["CheckStyle", "PMD", "FindBugs"];
	var cat = categoryMapper.getDefects(i);
	for ( var index =0; index < mainTitles.length; index++) {
		var warning = sumNodeForASAT(d, getTotalASATWarning(mainTitles[index], d.fileName));
		document.getElementById(mainLabels[index]).innerHTML = '  '+ mainLabels[index] + ' (' + warning + ")";
	}
}

/**
 * Will calculate the number of current warnings for the function defects category and then sets it
 */
function updateDefectsCount(d) {
	var mainLabels = ["FuncDefLabel", "MainDefLabel", "OthLabel"];
	var mainLabelsTitles = ["Functional Defects", "Maintainability Defects", "Other"];
	for ( var i =0; i< 2; i++) {
		var total = 0;
		var catLabel = categoryMapper.getDefectLabels(i);
		var cat = categoryMapper.getDefects(i);
		for ( var index =0; index < cat.length; index++) {
			var warning = sumNodeForASAT(d, getTotalCategoryWarning(cat[index], d.fileName));
			document.getElementById(catLabel[index]).innerHTML = '  '+ cat[index] + ' (' + warning + ")";
			if( acceptedCategories.indexOf(cat[index]) >= 0) {
				total += warning;
			}
		}
		document.getElementById(mainLabels[i]).innerHTML = ' ' + mainLabelsTitles[i] + ' (' +  total + ")  ";
	}
}

/**
 * Sums for each node how many warnings they have.
 */
function sumNodeForASAT(d, root) {
    var nodeAndSummation = [];
    var sum = 0;
    if (d.fileName == projectName) {
        for (var i = 0; i < root.length; i++) {
            for (var j = 0; j < root[i].length; j++) {
                sum += root[i][j].amountOfWarnings;
             }
         }
         return sum;
    } else {
        for (var i = 0; i < root.length; i++) {
            if(treeMapBuilder.getSourceCodeLevel()) {
                if (root[i].packageName == d.parent.fileName) {
                    for (var j = 0; j < root[i].length; j++) {
                        if(treeMapBuilder.getSourceCodeLevel() && root[i][j].fileName == treeMapBuilder.getCurrentClassName()) {
                            return root[i][j].amountOfWarnings;
                        }
                        sum += root[i][j].amountOfWarnings;
                    }
                    return sum;
                }
            } else {
                if (root[i].packageName == d.fileName) {
                    for (var j = 0; j < root[i].length; j++) {
                        sum += root[i][j].amountOfWarnings;
                    }
                    return sum;
                }
            }
        }
    }
    return -1;
}<|endoftext|>


<commit_before>/* converts given number of seconds to standard time display format
 * http://goo.gl/kEvnKn
 */
function convertToTime(number) {
  const hours = Math.floor(number / (60 * 60));
  const mins = Math.floor(number / 60) - hours * 60;
  const secs = (number % 60).toFixed();
  let time = hours > 0 ? `${hours}:` : '';
  time += `${mins < 10 && hours > 0 ? '0' : ''}${mins}:`;
  time += `${secs < 10 ? '0' : ''}${secs}`;
  return time;
}

export default convertToTime;
<commit_msg>Round down (instead of up) to nearest second (#429)<commit_after>/* converts given number of seconds to standard time display format
 * http://goo.gl/kEvnKn
 */
function convertToTime(number) {
  const hours = Math.floor(number / (60 * 60));
  const mins = Math.floor(number / 60) - hours * 60;
  const secs = Math.floor(number % 60);
  let time = hours > 0 ? `${hours}:` : '';
  time += `${mins < 10 && hours > 0 ? '0' : ''}${mins}:`;
  time += `${secs < 10 ? '0' : ''}${secs}`;
  return time;
}

export default convertToTime;
<|endoftext|>


<commit_before>load('vertx_tests.js');

var crypto = require('crypto');

function testCreateHash() {
  vassert.assertTrue(typeof crypto.createHash == 'function');
  var hash = crypto.createHash('sha1');
  vassert.assertTrue(hash instanceof crypto.Hash);
  vassert.assertEquals('sha1', hash.algorithm);
  vassert.testComplete();
}

function testHashUpdate() {
  var hash = crypto.createHash('sha1');
  hash.update('Now is the winter of our discontent ');
  hash.update('made glorious summer');
  vassert.testComplete();
}

function testHashDigest() {
  var hash = crypto.createHash('sha1');
  hash.update('Now is the winter of our discontent ');
  hash.update('made glorious summer');
  vassert.assertEquals('2365c163a22c69f11c2394ee6064fcfec1d19284', hash.digest('hex'));
  vassert.testComplete();
}

initTests(this);
<commit_msg>Add Hash.digest tests for MD5, SHA256 and SHA512<commit_after>load('vertx_tests.js');

var crypto = require('crypto');

function testCreateHash() {
  vassert.assertTrue(typeof crypto.createHash == 'function');
  var hash = crypto.createHash('sha1');
  vassert.assertTrue(hash instanceof crypto.Hash);
  vassert.assertEquals('sha1', hash.algorithm);
  vassert.testComplete();
}

function testSHA1HashDigest() {
  var hash = crypto.createHash('sha1');
  hash.update('Now is the winter of our discontent ');
  hash.update('made glorious summer');
  vassert.assertEquals('2365c163a22c69f11c2394ee6064fcfec1d19284', hash.digest('hex'));
  vassert.testComplete();
}

function testMD5HashDigest() {
  var hash = crypto.createHash('md5');
  hash.update('Now is the winter of our discontent ');
  hash.update('made glorious summer');
  vassert.assertEquals('74402c8710d5107209ee554e2e11bcf7', hash.digest('hex'));
  vassert.testComplete();
}

function testSHA256HashDigest() {
  var hash = crypto.createHash('sha256');
  hash.update('Now is the winter of our discontent ');
  hash.update('made glorious summer');
  vassert.assertEquals('453a07e8b7124e0cb136b7ef838e6dd78b2e4944f0e5546b802de6b774bec2e8', hash.digest('hex'));
  vassert.testComplete();
}

function testSHA512HashDigest() {
  var hash = crypto.createHash('sha512');
  hash.update('Now is the winter of our discontent ');
  hash.update('made glorious summer');
  vassert.assertEquals('e62168d80ddc7d992053122b166de7d8db0112422baf4b1255b7421789fd595a3be341c2740153579456fdecf8264a7fc2a0c7aa6851ae531b36ebe94ad16b61', hash.digest('hex'));
  vassert.testComplete();
}

initTests(this);
<|endoftext|>


<commit_before>import path from 'path';
import webpack from 'webpack';

export default {
  devtool: 'source-map',
  entry: path.resolve(__dirname, 'src/index.js'),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index.js',
    library: 'grommet-cms-content-blocks',
    libraryTarget: 'umd',
    umdNamedDefine: true,
    sourceMapFilename: "[name].js.map",
  },
  plugins: [
    // new webpack.optimize.UglifyJsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
  ],
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: path.join(__dirname, 'src'),
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
    ],
  },
};<commit_msg>Fix: re-add uglification script for webpack configuration<commit_after>import path from 'path';
import webpack from 'webpack';

export default {
  devtool: 'source-map',
  entry: path.resolve(__dirname, 'src/index.js'),
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'index.js',
    library: 'grommet-cms-content-blocks',
    libraryTarget: 'umd',
    umdNamedDefine: true,
    sourceMapFilename: "[name].js.map",
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin(),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production'),
    }),
  ],
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        include: path.join(__dirname, 'src'),
        exclude: /node_modules/,
        loader: 'babel-loader',
      },
    ],
  },
};<|endoftext|>


<commit_before>/* Copyright 2013-2014 Extended Mind Technologies Oy
 *
 * 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.
 */

 /* global angular, useOfflineBuffer */
 'use strict';

 function UserSessionService(base64, LocalStorageService, PersistentStorageService, SessionStorageService) {
  var swapTokenBufferTime = 10*60*1000; // 10 minutes in milliseconds
  // When offline isn't enabled, use transient value for latest modified
  var latestModified = {};
  var itemsSynchronized = {};
  var offlineEnabled = false;
  var notifyOwnerCallbacks = {};

  // Sync session storage with local storage.
  function syncWebStorages() {
    if (LocalStorageService.getExpires() && SessionStorageService.getExpires() !== LocalStorageService.getExpires()) {
      setUserSessionStorageData();
    }
  }

  function setUserSessionStorageData() {
    SessionStorageService.setBackendDelta(LocalStorageService.getBackendDelta());
    SessionStorageService.setCollectives(LocalStorageService.getCollectives());
    SessionStorageService.setEmail(LocalStorageService.getEmail());
    SessionStorageService.setExpires(LocalStorageService.getExpires());
    SessionStorageService.setCredentials(LocalStorageService.getCredentials());
    SessionStorageService.setUserType(LocalStorageService.getUserType());
    SessionStorageService.setUserUUID(LocalStorageService.getUserUUID());
    SessionStorageService.setCohort(LocalStorageService.getCohort());
    SessionStorageService.setPreferences(LocalStorageService.getPreferences());
    SessionStorageService.setUserModified(LocalStorageService.getUserModified());
    SessionStorageService.setUserState(LocalStorageService.getUserState());
    SessionStorageService.setLatestModified(LocalStorageService.getLatestModified());
    SessionStorageService.setOffline(LocalStorageService.getOffline());
  }

  function encodeUsernamePassword(username, password) {
    return base64.encode(username + ':' + password);
  }

  function setEmail(email) {
    if (email) {
      SessionStorageService.setEmail(email);
      if (offlineEnabled || LocalStorageService.getReplaceable() !== null) {
        LocalStorageService.setEmail(email);
      }
    }
  }

  function migrateTransportPreferences(transportPreferences) {
    if (transportPreferences) {
      var preferences = {
        onboarded: transportPreferences.onboarded
      };
      if (transportPreferences.ui) {
        preferences.ui = JSON.parse(transportPreferences.ui);
      }
      return preferences;
    } else {
      return {};
    }
  }

  function executeNotifyOwnerCallbacks(userUUID, collectives) {
    for (var id in notifyOwnerCallbacks) {
      notifyOwnerCallbacks[id](userUUID);
      if (collectives){
        for (var uuid in collectives){
          notifyOwnerCallbacks[id](uuid, true);
        }
      }
    }
  }

  return {
    enableOffline: function(bypass) {
      offlineEnabled = true;
      if (bypass){
        // when bypassing store the value to stores
        LocalStorageService.setOffline(true);
        SessionStorageService.setOffline(true);
      }
    },
    isAuthenticated: function() {
      return SessionStorageService.getExpires() || LocalStorageService.getExpires();
    },
    isAuthenticateValid: function() {
      var authenticateCurrentReferenceTime, authenticateValidTime;

      authenticateValidTime = parseInt(SessionStorageService.getExpires() || LocalStorageService.getExpires());
      authenticateCurrentReferenceTime = Date.now() + swapTokenBufferTime;

      if (authenticateValidTime && (authenticateValidTime > authenticateCurrentReferenceTime)) {
        return true;
      }
    },
    isAuthenticateReplaceable: function() {
      var authenticateCurrentReferenceTime, authenticateValidTime;

      if (LocalStorageService.getReplaceable()) {
        authenticateValidTime = LocalStorageService.getReplaceable();
        authenticateCurrentReferenceTime = Date.now() + swapTokenBufferTime;
        if (authenticateValidTime > authenticateCurrentReferenceTime) {
          return true;
        }
      }
    },
    isOfflineEnabled: function() {
      syncWebStorages();
      var storedOffline = SessionStorageService.getOffline();
      if (storedOffline !== undefined){
        offlineEnabled = storedOffline;
      }
      return offlineEnabled;
    },
    clearUser: function() {
      SessionStorageService.clearUser();
      LocalStorageService.clearUser();
      itemsSynchronized = {};
      if (offlineEnabled){
        PersistentStorageService.destroyAll();
      }
      offlineEnabled = false;
    },

    // Web storage setters
    setAuthenticateInformation: function(authenticateResponse, email) {
      var backendDelta = Date.now() - authenticateResponse.authenticated;
      var credentials = encodeUsernamePassword('token', authenticateResponse.token);
      var preferences = migrateTransportPreferences(authenticateResponse.preferences);

      SessionStorageService.setBackendDelta(backendDelta);
      SessionStorageService.setCollectives(authenticateResponse.collectives);
      SessionStorageService.setExpires(authenticateResponse.expires + backendDelta);
      SessionStorageService.setCredentials(credentials);
      SessionStorageService.setUserType(authenticateResponse.userType);
      SessionStorageService.setUserUUID(authenticateResponse.userUUID);
      SessionStorageService.setCohort(authenticateResponse.cohort);
      SessionStorageService.setPreferences(preferences);
      SessionStorageService.setUserModified(authenticateResponse.modified);

      if (authenticateResponse.replaceable) {
        LocalStorageService.setBackendDelta(backendDelta);
        LocalStorageService.setExpires(authenticateResponse.expires + backendDelta);
        LocalStorageService.setCollectives(authenticateResponse.collectives);
        LocalStorageService.setCredentials(credentials);
        LocalStorageService.setReplaceable(authenticateResponse.replaceable + backendDelta);
        LocalStorageService.setUserType(authenticateResponse.userType);
        LocalStorageService.setUserUUID(authenticateResponse.userUUID);
        LocalStorageService.setCohort(authenticateResponse.cohort);
        LocalStorageService.setPreferences(preferences);
        LocalStorageService.setUserModified(authenticateResponse.modified);
      }
      if (email) {
        setEmail(email);
      }

      // Notify owner UUID's
      executeNotifyOwnerCallbacks(authenticateResponse.userUUID, authenticateResponse.collectives);
      return credentials;
    },
    setEmail: function(email) {
      setEmail(email);
    },
    setPreference: function(name, value) {
      var preferences = this.getPreferences() || {};
      if (value !== undefined) {
        preferences[name] = value;
      } else if (preferences[name] !== undefined) {
        delete preferences[name];
      }
      this.setPreferences(preferences);
    },
    setUIPreference: function(name, value) {
      var preferences = this.getPreferences() || {};
      if (!preferences.ui) preferences.ui = {};

      if (value !== undefined){
        preferences.ui[name] = value;
      }else if (preferences.ui[name] !== undefined) {
        delete preferences.ui[name];
      }
      this.setPreferences(preferences);
    },
    setPreferences: function(preferences) {
      SessionStorageService.setPreferences(preferences);
      if (offlineEnabled || LocalStorageService.getReplaceable() !== null) {
        LocalStorageService.setPreferences(preferences);
      }
    },
    setTransportPreferences: function(transportPreferences) {
      this.setPreferences(migrateTransportPreferences(transportPreferences));
    },
    setLatestModified: function(modified, ownerUUID) {
      // Only set if given value is larger than set value
      var currentLatestModified = this.getLatestModified(ownerUUID);
      if (!currentLatestModified || (modified && currentLatestModified < modified)) {
        if (offlineEnabled){
          SessionStorageService.setLatestModified(modified, ownerUUID);
          if (offlineEnabled) {
            LocalStorageService.setLatestModified(modified, ownerUUID);
          }
        }else{
          latestModified[ownerUUID] = modified;
        }
      }
    },
    setUserModified: function(modified) {
      SessionStorageService.setUserModified(modified);
      if (offlineEnabled || LocalStorageService.getReplaceable() !== null) {
        LocalStorageService.setUserModified(modified);
      }
    },
    setItemsSynchronized: function(timestamp, ownerUUID) {
      itemsSynchronized[ownerUUID] = timestamp;
    },
    // Web storage getters
    getCollectives: function() {
      syncWebStorages();
      return SessionStorageService.getCollectives();
    },
    getCredentials: function() {
      syncWebStorages();
      return SessionStorageService.getCredentials();
    },
    getBackendDelta: function(){
      syncWebStorages();
      var storedDelta = SessionStorageService.getBackendDelta();
      return storedDelta ? parseInt(storedDelta) : undefined;
    },
    getEmail: function() {
      // Sync only email in Web Storages.
      if (LocalStorageService.getEmail()) {
        SessionStorageService.setEmail(LocalStorageService.getEmail());
      }
      return SessionStorageService.getEmail();
    },
    getUserUUID: function() {
      syncWebStorages();
      return SessionStorageService.getUserUUID();
    },
    getCohort: function() {
      syncWebStorages();
      return SessionStorageService.getCohort();
    },
    getLatestModified: function(ownerUUID) {
      if (offlineEnabled){
        var currentLatestModified = SessionStorageService.getLatestModified(ownerUUID);
        if (currentLatestModified) return parseInt(currentLatestModified);
      }else{
        return latestModified[ownerUUID];
      }
    },
    getItemsSynchronized: function(ownerUUID) {
      return itemsSynchronized[ownerUUID];
    },
    isItemsSynchronized: function(ownerUUID) {
      return itemsSynchronized[ownerUUID] !== undefined;
    },
    getTransportPreferences: function() {
      syncWebStorages();
      var preferences = SessionStorageService.getPreferences();

      var transportPreferences = {};
      for (var property in preferences){
        if (preferences.hasOwnProperty(property)){
          transportPreferences[property] = preferences[property];
        }
      }
      if (transportPreferences.ui) {
        transportPreferences.ui = JSON.stringify(preferences.ui);
      }
      return transportPreferences;
    },
    getPreferences: function() {
      syncWebStorages();
      return SessionStorageService.getPreferences();
    },
    getUIPreference: function(key) {
      syncWebStorages();
      var preferences = SessionStorageService.getPreferences();
      if (preferences && preferences.ui) {
        return preferences.ui[key];
      }
    },
    getRememberByDefault: function() {
      return offlineEnabled;
    },
    getUser: function() {
      syncWebStorages();
      if (SessionStorageService.getUserUUID()) {
        var user = {
          uuid: SessionStorageService.getUserUUID(),
          type: parseInt(SessionStorageService.getUserType()),
          modified: SessionStorageService.getUserModified()
        };
        if (SessionStorageService.getCohort()) {
          user.cohort = parseInt(SessionStorageService.getCohort());
        }
        return user;
      }
    },
    getUserType: function() {
      return parseInt(SessionStorageService.getUserType());
    },
    registerNofifyOwnerCallback: function(callback, id){
      notifyOwnerCallbacks[id] = callback;

      // In case the registration comes after UserSessionService has received owners,
      // notify caller immediately
      var userUUID = this.getUserUUID();
      if (userUUID){
        callback(userUUID);
      }
      var collectives = this.getCollectives();
      if (collectives){
        for (var uuid in collectives){
          callback(uuid, true);
        }
      }
    },
    // NOTE: Here for easier testing!
    executeNotifyOwnerCallbacks: function(userUUID, collectives){
      executeNotifyOwnerCallbacks(userUUID, collectives);
    }
  };
}
UserSessionService['$inject'] = ['base64', 'LocalStorageService', 'PersistentStorageService',
'SessionStorageService'];
angular.module('em.base').factory('UserSessionService', UserSessionService);
<commit_msg>Fixed offline handling to not revert back to false also in apps<commit_after>/* Copyright 2013-2014 Extended Mind Technologies Oy
 *
 * 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.
 */

 /* global angular, useOfflineBuffer */
 'use strict';

 function UserSessionService(base64, LocalStorageService, PersistentStorageService, SessionStorageService) {
  var swapTokenBufferTime = 10*60*1000; // 10 minutes in milliseconds
  // When offline isn't enabled, use transient value for latest modified
  var latestModified = {};
  var itemsSynchronized = {};
  var offlineEnabled = false;
  var notifyOwnerCallbacks = {};

  // Sync session storage with local storage.
  function syncWebStorages() {
    if (LocalStorageService.getExpires() && SessionStorageService.getExpires() !== LocalStorageService.getExpires()) {
      setUserSessionStorageData();
    }
  }

  function setUserSessionStorageData() {
    SessionStorageService.setBackendDelta(LocalStorageService.getBackendDelta());
    SessionStorageService.setCollectives(LocalStorageService.getCollectives());
    SessionStorageService.setEmail(LocalStorageService.getEmail());
    SessionStorageService.setExpires(LocalStorageService.getExpires());
    SessionStorageService.setCredentials(LocalStorageService.getCredentials());
    SessionStorageService.setUserType(LocalStorageService.getUserType());
    SessionStorageService.setUserUUID(LocalStorageService.getUserUUID());
    SessionStorageService.setCohort(LocalStorageService.getCohort());
    SessionStorageService.setPreferences(LocalStorageService.getPreferences());
    SessionStorageService.setUserModified(LocalStorageService.getUserModified());
    SessionStorageService.setUserState(LocalStorageService.getUserState());
    SessionStorageService.setLatestModified(LocalStorageService.getLatestModified());
    SessionStorageService.setOffline(LocalStorageService.getOffline());
  }

  function encodeUsernamePassword(username, password) {
    return base64.encode(username + ':' + password);
  }

  function setEmail(email) {
    if (email) {
      SessionStorageService.setEmail(email);
      if (offlineEnabled || LocalStorageService.getReplaceable() !== null) {
        LocalStorageService.setEmail(email);
      }
    }
  }

  function migrateTransportPreferences(transportPreferences) {
    if (transportPreferences) {
      var preferences = {
        onboarded: transportPreferences.onboarded
      };
      if (transportPreferences.ui) {
        preferences.ui = JSON.parse(transportPreferences.ui);
      }
      return preferences;
    } else {
      return {};
    }
  }

  function executeNotifyOwnerCallbacks(userUUID, collectives) {
    for (var id in notifyOwnerCallbacks) {
      notifyOwnerCallbacks[id](userUUID);
      if (collectives){
        for (var uuid in collectives){
          notifyOwnerCallbacks[id](uuid, true);
        }
      }
    }
  }

  return {
    enableOffline: function(bypass) {
      offlineEnabled = true;
      if (bypass){
        // when bypassing store the value to stores
        LocalStorageService.setOffline(true);
        SessionStorageService.setOffline(true);
      }
    },
    isAuthenticated: function() {
      return SessionStorageService.getExpires() || LocalStorageService.getExpires();
    },
    isAuthenticateValid: function() {
      var authenticateCurrentReferenceTime, authenticateValidTime;

      authenticateValidTime = parseInt(SessionStorageService.getExpires() || LocalStorageService.getExpires());
      authenticateCurrentReferenceTime = Date.now() + swapTokenBufferTime;

      if (authenticateValidTime && (authenticateValidTime > authenticateCurrentReferenceTime)) {
        return true;
      }
    },
    isAuthenticateReplaceable: function() {
      var authenticateCurrentReferenceTime, authenticateValidTime;

      if (LocalStorageService.getReplaceable()) {
        authenticateValidTime = LocalStorageService.getReplaceable();
        authenticateCurrentReferenceTime = Date.now() + swapTokenBufferTime;
        if (authenticateValidTime > authenticateCurrentReferenceTime) {
          return true;
        }
      }
    },
    isOfflineEnabled: function() {
      syncWebStorages();
      var storedOffline = SessionStorageService.getOffline();
      if (storedOffline !== undefined){
        offlineEnabled = storedOffline;
      }
      return offlineEnabled;
    },
    clearUser: function() {
      if (SessionStorageService.getOffline() === true){
        PersistentStorageService.destroyAll();
        offlineEnabled = false;
      }
      SessionStorageService.clearUser();
      LocalStorageService.clearUser();
      itemsSynchronized = {};
    },

    // Web storage setters
    setAuthenticateInformation: function(authenticateResponse, email) {
      var backendDelta = Date.now() - authenticateResponse.authenticated;
      var credentials = encodeUsernamePassword('token', authenticateResponse.token);
      var preferences = migrateTransportPreferences(authenticateResponse.preferences);

      SessionStorageService.setBackendDelta(backendDelta);
      SessionStorageService.setCollectives(authenticateResponse.collectives);
      SessionStorageService.setExpires(authenticateResponse.expires + backendDelta);
      SessionStorageService.setCredentials(credentials);
      SessionStorageService.setUserType(authenticateResponse.userType);
      SessionStorageService.setUserUUID(authenticateResponse.userUUID);
      SessionStorageService.setCohort(authenticateResponse.cohort);
      SessionStorageService.setPreferences(preferences);
      SessionStorageService.setUserModified(authenticateResponse.modified);

      if (authenticateResponse.replaceable) {
        LocalStorageService.setBackendDelta(backendDelta);
        LocalStorageService.setExpires(authenticateResponse.expires + backendDelta);
        LocalStorageService.setCollectives(authenticateResponse.collectives);
        LocalStorageService.setCredentials(credentials);
        LocalStorageService.setReplaceable(authenticateResponse.replaceable + backendDelta);
        LocalStorageService.setUserType(authenticateResponse.userType);
        LocalStorageService.setUserUUID(authenticateResponse.userUUID);
        LocalStorageService.setCohort(authenticateResponse.cohort);
        LocalStorageService.setPreferences(preferences);
        LocalStorageService.setUserModified(authenticateResponse.modified);
      }
      if (email) {
        setEmail(email);
      }

      // Notify owner UUID's
      executeNotifyOwnerCallbacks(authenticateResponse.userUUID, authenticateResponse.collectives);
      return credentials;
    },
    setEmail: function(email) {
      setEmail(email);
    },
    setPreference: function(name, value) {
      var preferences = this.getPreferences() || {};
      if (value !== undefined) {
        preferences[name] = value;
      } else if (preferences[name] !== undefined) {
        delete preferences[name];
      }
      this.setPreferences(preferences);
    },
    setUIPreference: function(name, value) {
      var preferences = this.getPreferences() || {};
      if (!preferences.ui) preferences.ui = {};

      if (value !== undefined){
        preferences.ui[name] = value;
      }else if (preferences.ui[name] !== undefined) {
        delete preferences.ui[name];
      }
      this.setPreferences(preferences);
    },
    setPreferences: function(preferences) {
      SessionStorageService.setPreferences(preferences);
      if (offlineEnabled || LocalStorageService.getReplaceable() !== null) {
        LocalStorageService.setPreferences(preferences);
      }
    },
    setTransportPreferences: function(transportPreferences) {
      this.setPreferences(migrateTransportPreferences(transportPreferences));
    },
    setLatestModified: function(modified, ownerUUID) {
      // Only set if given value is larger than set value
      var currentLatestModified = this.getLatestModified(ownerUUID);
      if (!currentLatestModified || (modified && currentLatestModified < modified)) {
        if (offlineEnabled){
          SessionStorageService.setLatestModified(modified, ownerUUID);
          if (offlineEnabled) {
            LocalStorageService.setLatestModified(modified, ownerUUID);
          }
        }else{
          latestModified[ownerUUID] = modified;
        }
      }
    },
    setUserModified: function(modified) {
      SessionStorageService.setUserModified(modified);
      if (offlineEnabled || LocalStorageService.getReplaceable() !== null) {
        LocalStorageService.setUserModified(modified);
      }
    },
    setItemsSynchronized: function(timestamp, ownerUUID) {
      itemsSynchronized[ownerUUID] = timestamp;
    },
    // Web storage getters
    getCollectives: function() {
      syncWebStorages();
      return SessionStorageService.getCollectives();
    },
    getCredentials: function() {
      syncWebStorages();
      return SessionStorageService.getCredentials();
    },
    getBackendDelta: function(){
      syncWebStorages();
      var storedDelta = SessionStorageService.getBackendDelta();
      return storedDelta ? parseInt(storedDelta) : undefined;
    },
    getEmail: function() {
      // Sync only email in Web Storages.
      if (LocalStorageService.getEmail()) {
        SessionStorageService.setEmail(LocalStorageService.getEmail());
      }
      return SessionStorageService.getEmail();
    },
    getUserUUID: function() {
      syncWebStorages();
      return SessionStorageService.getUserUUID();
    },
    getCohort: function() {
      syncWebStorages();
      return SessionStorageService.getCohort();
    },
    getLatestModified: function(ownerUUID) {
      if (offlineEnabled){
        var currentLatestModified = SessionStorageService.getLatestModified(ownerUUID);
        if (currentLatestModified) return parseInt(currentLatestModified);
      }else{
        return latestModified[ownerUUID];
      }
    },
    getItemsSynchronized: function(ownerUUID) {
      return itemsSynchronized[ownerUUID];
    },
    isItemsSynchronized: function(ownerUUID) {
      return itemsSynchronized[ownerUUID] !== undefined;
    },
    getTransportPreferences: function() {
      syncWebStorages();
      var preferences = SessionStorageService.getPreferences();

      var transportPreferences = {};
      for (var property in preferences){
        if (preferences.hasOwnProperty(property)){
          transportPreferences[property] = preferences[property];
        }
      }
      if (transportPreferences.ui) {
        transportPreferences.ui = JSON.stringify(preferences.ui);
      }
      return transportPreferences;
    },
    getPreferences: function() {
      syncWebStorages();
      return SessionStorageService.getPreferences();
    },
    getUIPreference: function(key) {
      syncWebStorages();
      var preferences = SessionStorageService.getPreferences();
      if (preferences && preferences.ui) {
        return preferences.ui[key];
      }
    },
    getRememberByDefault: function() {
      return offlineEnabled;
    },
    getUser: function() {
      syncWebStorages();
      if (SessionStorageService.getUserUUID()) {
        var user = {
          uuid: SessionStorageService.getUserUUID(),
          type: parseInt(SessionStorageService.getUserType()),
          modified: SessionStorageService.getUserModified()
        };
        if (SessionStorageService.getCohort()) {
          user.cohort = parseInt(SessionStorageService.getCohort());
        }
        return user;
      }
    },
    getUserType: function() {
      return parseInt(SessionStorageService.getUserType());
    },
    registerNofifyOwnerCallback: function(callback, id){
      notifyOwnerCallbacks[id] = callback;

      // In case the registration comes after UserSessionService has received owners,
      // notify caller immediately
      var userUUID = this.getUserUUID();
      if (userUUID){
        callback(userUUID);
      }
      var collectives = this.getCollectives();
      if (collectives){
        for (var uuid in collectives){
          callback(uuid, true);
        }
      }
    },
    // NOTE: Here for easier testing!
    executeNotifyOwnerCallbacks: function(userUUID, collectives){
      executeNotifyOwnerCallbacks(userUUID, collectives);
    }
  };
}
UserSessionService['$inject'] = ['base64', 'LocalStorageService', 'PersistentStorageService',
'SessionStorageService'];
angular.module('em.base').factory('UserSessionService', UserSessionService);
<|endoftext|>


<commit_before>import RepeatGroup from './repeat_group';

import log from 'loglevel';

var Collision;

export default Collision = {

    tiles: {},

    startTile (tile) {
        let state = this.tiles[tile] = {
            bboxes: {           // current set of placed bounding boxes
                aabb: [],
                obb: []
            },
            objects: {},        // objects to collide, grouped by priority, then by style
            keep: {},           // objects that were kept after collision, grouped by style
            styles: new Set()   // styles contributing collision objects
        };

        // Promise resolved when all registered styles have added objects
        state.complete = new Promise((resolve, reject) => {
            state.resolve = resolve;
            state.reject = reject;
        });
    },

    resetTile (tile) {
        delete this.tiles[tile];
    },

    // Add a style to the pending set, collision will block on all styles submitting to collision set
    addStyle (style, tile) {
        this.tiles[tile].styles.add(style);
    },

    // Add collision objects for a style
    collide (objects, style, tile) {
        let state = this.tiles[tile];
        if (!state) {
            log.warn('Collision.collide() called with null tile', tile, this.tiles, Object.keys(this.tiles[tile]).length, style, objects);
            return;
        }

        // Group by priority and style
        let tile_objects = state.objects;
        for (let i=0; i < objects.length; i++) {
            let obj = objects[i];
            let priority = obj.layout.priority;
            tile_objects[priority] = tile_objects[priority] || {};
            tile_objects[priority][style] = tile_objects[priority][style] || [];
            tile_objects[priority][style].push(obj);
        }

        // Remove from pending style set, if no more styles, do collision & finish tile
        state.styles.delete(style);
        if (state.styles.size === 0) {
            this.endTile(tile);
        }

        // Wait for objects to be added from all styles
        return state.complete.then(() => {
            return state.keep[style] || [];
        });
    },

    // Test labels for collisions, higher to lower priority
    // When two collide, discard the lower-priority label
    endTile (tile) {
        let state = this.tiles[tile];
        let bboxes = state.bboxes;
        let keep = state.keep;

        RepeatGroup.clear(tile);

        // Process labels by priority, then by style
        let priorities = Object.keys(state.objects).sort((a, b) => a - b);
        for (let priority of priorities) {
            let style_objects = state.objects[priority];
            if (!style_objects) { // no labels at this priority, skip to next
                continue;
            }

            // For each style
            for (let style in style_objects) {
                let objects = style_objects[style];
                keep[style] = keep[style] || [];

                for (let i = 0; i < objects.length; i++) {
                    let { label, layout } = objects[i]; // TODO: `label` should be generic

                    // test the label for intersections with other labels in the tile
                    if (!layout.collide || !label.discard(bboxes)) {
                        // check for repeats
                        let check = RepeatGroup.check(label, layout, tile);
                        if (check) {
                            log.trace(`discard label '${label.text}', (one_per_group: ${check.one_per_group}), dist ${Math.sqrt(check.dist_sq)/layout.units_per_pixel} < ${Math.sqrt(check.repeat_dist_sq)/layout.units_per_pixel}`);
                            continue;
                        }
                        // register as placed for future repeat culling
                        RepeatGroup.add(label, layout, tile);

                        label.add(bboxes); // add label to currently visible set
                        keep[style].push(objects[i]);
                    }
                    else if (layout.collide) {
                        log.trace(`discard label '${label.text}' due to collision`);
                    }
                }
            }
        }

        delete this.tiles[tile];
        state.resolve();
    }

};
<commit_msg>fix error reporting when collision called without tile<commit_after>import RepeatGroup from './repeat_group';

import log from 'loglevel';

var Collision;

export default Collision = {

    tiles: {},

    startTile (tile) {
        let state = this.tiles[tile] = {
            bboxes: {           // current set of placed bounding boxes
                aabb: [],
                obb: []
            },
            objects: {},        // objects to collide, grouped by priority, then by style
            keep: {},           // objects that were kept after collision, grouped by style
            styles: new Set()   // styles contributing collision objects
        };

        // Promise resolved when all registered styles have added objects
        state.complete = new Promise((resolve, reject) => {
            state.resolve = resolve;
            state.reject = reject;
        });
    },

    resetTile (tile) {
        delete this.tiles[tile];
    },

    // Add a style to the pending set, collision will block on all styles submitting to collision set
    addStyle (style, tile) {
        this.tiles[tile].styles.add(style);
    },

    // Add collision objects for a style
    collide (objects, style, tile) {
        let state = this.tiles[tile];
        if (!state) {
            log.trace('Collision.collide() called with null tile', tile, this.tiles, style, objects);
            return Promise.reject(Error('Collision.collide() called with null tile', tile, this.tiles, style, objects));
        }

        // Group by priority and style
        let tile_objects = state.objects;
        for (let i=0; i < objects.length; i++) {
            let obj = objects[i];
            let priority = obj.layout.priority;
            tile_objects[priority] = tile_objects[priority] || {};
            tile_objects[priority][style] = tile_objects[priority][style] || [];
            tile_objects[priority][style].push(obj);
        }

        // Remove from pending style set, if no more styles, do collision & finish tile
        state.styles.delete(style);
        if (state.styles.size === 0) {
            this.endTile(tile);
        }

        // Wait for objects to be added from all styles
        return state.complete.then(() => {
            return state.keep[style] || [];
        });
    },

    // Test labels for collisions, higher to lower priority
    // When two collide, discard the lower-priority label
    endTile (tile) {
        let state = this.tiles[tile];
        let bboxes = state.bboxes;
        let keep = state.keep;

        RepeatGroup.clear(tile);

        // Process labels by priority, then by style
        let priorities = Object.keys(state.objects).sort((a, b) => a - b);
        for (let priority of priorities) {
            let style_objects = state.objects[priority];
            if (!style_objects) { // no labels at this priority, skip to next
                continue;
            }

            // For each style
            for (let style in style_objects) {
                let objects = style_objects[style];
                keep[style] = keep[style] || [];

                for (let i = 0; i < objects.length; i++) {
                    let { label, layout } = objects[i]; // TODO: `label` should be generic

                    // test the label for intersections with other labels in the tile
                    if (!layout.collide || !label.discard(bboxes)) {
                        // check for repeats
                        let check = RepeatGroup.check(label, layout, tile);
                        if (check) {
                            log.trace(`discard label '${label.text}', (one_per_group: ${check.one_per_group}), dist ${Math.sqrt(check.dist_sq)/layout.units_per_pixel} < ${Math.sqrt(check.repeat_dist_sq)/layout.units_per_pixel}`);
                            continue;
                        }
                        // register as placed for future repeat culling
                        RepeatGroup.add(label, layout, tile);

                        label.add(bboxes); // add label to currently visible set
                        keep[style].push(objects[i]);
                    }
                    else if (layout.collide) {
                        log.trace(`discard label '${label.text}' due to collision`);
                    }
                }
            }
        }

        delete this.tiles[tile];
        state.resolve();
    }

};
<|endoftext|>


<commit_before>if (!ORYX.Plugins)
    ORYX.Plugins = {};

if (!ORYX.Config)
    ORYX.Config = {};

function updateHistorySVG() {
    document.getElementById('svgviewerid').innerHTML = ORYX.EDITOR.localStorageSVG;
}

ORYX.Plugins.LocalHistory = Clazz.extend({
    construct: function(facade){
        this.facade = facade;
        this.historyEntry;
        this.historyProxy;
        this.historyStore;
        this.storage;
        this.fail;
        this.uid;
        this.historyInterval;

        if(this.haveSupportForLocalHistory()) {
            this.setupAndLoadHistoryData();
            this.startStoring();
        }

        this.facade.offer({
            'name': "Display Local History",
            'functionality': this.displayLocalHistory.bind(this),
            'group': "localstorage",
            'icon': ORYX.PATH + "images/view.png",
             dropDownGroupIcon : ORYX.PATH + "images/localhistory.png",
            'description': "Display Local History",
            'index': 1,
            'minShape': 0,
            'maxShape': 0,
            'isEnabled': function(){
                profileParamName = "profile";
                profileParamName = profileParamName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
                regexSa = "[\\?&]"+profileParamName+"=([^&#]*)";
                regexa = new RegExp( regexSa );
                profileParams = regexa.exec( window.location.href );
                profileParamValue = profileParams[1];
                return profileParamValue == "jbpm" && ORYX.LOCAL_HISTORY_ENABLED;
            }.bind(this)
        });

        this.facade.offer({
            'name': "Clear Local History",
            'functionality': this.clearLocalHistory.bind(this),
            'group': "localstorage",
            'icon': ORYX.PATH + "images/clear.png",
            dropDownGroupIcon : ORYX.PATH + "images/localhistory.png",
            'description': "Clear Local History",
            'index': 2,
            'minShape': 0,
            'maxShape': 0,
            'isEnabled': function(){
                profileParamName = "profile";
                profileParamName = profileParamName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
                regexSa = "[\\?&]"+profileParamName+"=([^&#]*)";
                regexa = new RegExp( regexSa );
                profileParams = regexa.exec( window.location.href );
                profileParamValue = profileParams[1];
                return profileParamValue == "jbpm" && ORYX.LOCAL_HISTORY_ENABLED;
            }.bind(this)
        });

        this.facade.offer({
            'name': "Enable Local History",
            'functionality': this.enableLocalHistory.bind(this),
            'group': "localstorage",
            'icon': ORYX.PATH + "images/enable.png",
            dropDownGroupIcon : ORYX.PATH + "images/localhistory.png",
            'description': "Enable Local History",
            'index': 2,
            'minShape': 0,
            'maxShape': 0,
            'isEnabled': function(){
                profileParamName = "profile";
                profileParamName = profileParamName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
                regexSa = "[\\?&]"+profileParamName+"=([^&#]*)";
                regexa = new RegExp( regexSa );
                profileParams = regexa.exec( window.location.href );
                profileParamValue = profileParams[1];
                return profileParamValue == "jbpm" && !ORYX.LOCAL_HISTORY_ENABLED;
            }.bind(this)
        });

        this.facade.offer({
            'name': "Disable Local History",
            'functionality': this.disableLocalHistory.bind(this),
            'group': "localstorage",
            'icon': ORYX.PATH + "images/disable.png",
            dropDownGroupIcon : ORYX.PATH + "images/localhistory.png",
            'description': "Disable Local History",
            'index': 2,
            'minShape': 0,
            'maxShape': 0,
            'isEnabled': function(){
                profileParamName = "profile";
                profileParamName = profileParamName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
                regexSa = "[\\?&]"+profileParamName+"=([^&#]*)";
                regexa = new RegExp( regexSa );
                profileParams = regexa.exec( window.location.href );
                profileParamValue = profileParams[1];
                return profileParamValue == "jbpm" && ORYX.LOCAL_HISTORY_ENABLED;
            }.bind(this)
        });

        window.onbeforeunload = function(){
            this.stopStoring();
        }.bind(this);
    },
    displayLocalHistory : function() {
        var gridId = Ext.id();
        var grid = new Ext.grid.EditorGridPanel({
            autoScroll: true,
            autoHeight: true,
            store: this.historyStore,
            id: gridId,
            stripeRows: true,
            cm: new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
            {
                id: 'pid',
                header: 'Id',
                width: 100,
                dataIndex: 'processid',
                editor: new Ext.form.TextField({ allowBlank: true, disabled: true })
            },
            {
                id: 'pname',
                header: 'Name',
                width: 100,
                dataIndex: 'processname',
                editor: new Ext.form.TextField({ allowBlank: true, disabled: true })
            },
            {
                id: 'ppkg',
                header: 'Package',
                width: 100,
                dataIndex: 'processpkg',
                editor: new Ext.form.TextField({ allowBlank: true, disabled: true })
            },
            {
                id: 'pver',
                header: 'Version',
                width: 100,
                dataIndex: 'processversion',
                editor: new Ext.form.TextField({ allowBlank: true, disabled: true })
            },
            {
                id: 'tms',
                header: 'Time Stamp',
                width: 200,
                dataIndex: 'timestamp',
                editor: new Ext.form.TextField({ allowBlank: true, disabled: true })
            },{
                id: 'pim',
                header: 'Process Image',
                width: 150,
                dataIndex: 'svg',
                renderer: function(val) {
                    if(val && val.length > 0) {
                        ORYX.EDITOR.localStorageSVG = val;
                        return '';
                    } else {
                        return "Process image not available.";
                    }
                    return "";
                }
            }])
        });

        var localHistoryPanel = new Ext.Panel({
            id: 'localHistoryPanel',
            title: 'Select Process Id and click "Restore" to restore.',
            layout:'column',
            items:[
                grid
            ],
            layoutConfig: {
                columns: 1
            },
            defaults: {
                columnWidth: 1.0
            }
        });

        var dialog = new Ext.Window({
            layout		: 'anchor',
            autoCreate	: true,
            title		: 'Local History View',
            height		: 350,
            width		: 780,
            modal		: true,
            collapsible	: false,
            fixedcenter	: true,
            shadow		: true,
            resizable   : true,
            proxyDrag	: true,
            autoScroll  : true,
            keys:[{
                key	: 27,
                fn	: function(){
                    dialog.hide()
                }.bind(this)
            }],
            items		:[localHistoryPanel],
            listeners	:{
                hide: function(){
                    dialog.destroy();
                }.bind(this)
            },
            buttons		: [{
                text: 'Restore',
                handler: function(){
                    if(grid.getSelectionModel().getSelectedCell() != null) {
                        var selectedIndex = grid.getSelectionModel().getSelectedCell()[0];
                        var outValue = this.historyStore.getAt(selectedIndex).data['json'];
                        if(outValue && outValue.length > 0) {
                            this.clearCanvas();
                            var outObj = outValue.evalJSON();
                            this.facade.importJSON(outObj);
                        } else {
                            Ext.Msg.minWidth = 400;
                            Ext.Msg.alert("Invalid Process info. Unable to restore.");
                        }
                        dialog.hide()
                    } else {
                        Ext.Msg.alert('Please select a process id');
                    }
                }.bind(this)
            }, {
                text: ORYX.I18N.PropertyWindow.cancel,
                handler: function(){
                    dialog.hide()
                }.bind(this)
            }]
        });

        dialog.show();
        grid.render();
        grid.focus( false, 100 );
    },
    setupAndLoadHistoryData : function() {
        this.historyEntry = Ext.data.Record.create(
            [
                {name: 'processid' },
                {name: 'processname' },
                {name: 'processpkg'},
                {name: 'processversion'},
                {name: 'timestamp'},
                {name: 'json' },
                {name: 'svg' }
            ]
        );
        this.historyProxy = new Ext.data.MemoryProxy({root: []});
        this.historyStore = new Ext.data.Store({
            autoDestroy: true,
            reader: new Ext.data.JsonReader({
                root: "root"
            }, this.historyEntry),
            proxy: this.historyProxy
        });
        this.historyStore.load();
        if(this.storage) {
            var processJSON = ORYX.EDITOR.getSerializedJSON();
            var processId = jsonPath(processJSON.evalJSON(), "$.properties.id");
            var processPackage = jsonPath(processJSON.evalJSON(), "$.properties.package");
            var processHistory = this.storage.getItem(processPackage + "_" + processId);
            if(processHistory) {
                var history = processHistory.evalJSON();
                for (var i = 0; i < history.length; i ++) {
                    var item = history[i];
                    this.addToStore(item);
                }
            }
        }
    },
    addToStore : function(item) {
        this.historyStore.insert(0, new this.historyEntry({
            processid: item.processid,
            processname: item.processname,
            processpkg: item.processpkg,
            processversion: item.processversion,
            timestamp: new Date(item.timestamp).format("d.m.Y H:i:s"),
            json: item.json,
            svg:  item.svg
        }));
        this.historyStore.commitChanges();
    },
    clearLocalHistory : function() {
        this.historyStore.removeAll();
        this.historyStore.commitChanges();
        var processJSON = ORYX.EDITOR.getSerializedJSON();
        var processId = jsonPath(processJSON.evalJSON(), "$.properties.id");
        this.storage.removeItem(processId);
        Ext.Msg.minWidth = 400;
        Ext.Msg.alert("Local History has been cleared.");
    },
    enableLocalHistory : function() {
        this.setupAndLoadHistoryData();
        Ext.Msg.minWidth = 400;
        Ext.Msg.alert("Local History has been enabled.");
    },
    disableLocalHistory : function() {
        Ext.Msg.minWidth = 400;
        Ext.Msg.alert("Local History has been disabled.");
    },
    haveSupportForLocalHistory : function() {
        try {
            this.uid = new Date;
            (this.storage = window.localStorage).setItem(this.uid, this.uid);
            this.fail = this.storage.getItem(this.uid) != this.uid;
            this.storage.removeItem(this.uid);
            this.fail && (this.storage = false);
        } catch(e) {}
        return this.storage && ORYX.LOCAL_HISTORY_ENABLED;
    },
    addToHistory : function() {
        var processJSON = ORYX.EDITOR.getSerializedJSON();
        var formattedSvgDOM = DataManager.serialize(ORYX.EDITOR.getCanvas().getSVGRepresentation(false));
        var processName = jsonPath(processJSON.evalJSON(), "$.properties.name");
        var processPackage = jsonPath(processJSON.evalJSON(), "$.properties.package");
        var processId = jsonPath(processJSON.evalJSON(), "$.properties.id");
        var processVersion = jsonPath(processJSON.evalJSON(), "$.properties.version");

        var item = {
            processid: processId,
            processname: processName,
            processpkg: processPackage,
            processversion: processVersion,
            timestamp: new Date().getTime(),
            json: processJSON,
            svg: formattedSvgDOM
        };

        try {
            var processHistory = this.storage.getItem(processPackage + "_" + processId);
            if(processHistory) {
                var pobject = processHistory.evalJSON();
                pobject.push(item);
                this.storage.setItem(processPackage + "_" + processId, eval(JSON.stringify(pobject)));
            } else {
                var addArray = new Array();
                addArray.push(item);
                this.storage.setItem(processPackage + "_" + processId, eval(JSON.stringify(addArray)));
            }
            this.addToStore(item);
        } catch (e) {
            Ext.Msg.minWidth = 500;
            Ext.Msg.alert("Local History quota exceeded. Clearing local history.");
            this.clearLocalHistory();

        }
    },
    clearCanvas: function() {
        ORYX.EDITOR.getCanvas().nodes.each(function(node) {
            ORYX.EDITOR.deleteShape(node);
        }.bind(this));

        ORYX.EDITOR.getCanvas().edges.each(function(edge) {
            ORYX.EDITOR.deleteShape(edge);
        }.bind(this));
    },
    disableLocalHistory: function() {
        ORYX.LOCAL_HISTORY_ENABLED = false;
        this.stopStoring();
        this.facade.raiseEvent({type: ORYX.CONFIG.EVENT_STENCIL_SET_LOADED});
    },
    enableLocalHistory: function() {
        ORYX.LOCAL_HISTORY_ENABLED = true;
        this.setupAndLoadHistoryData();
        this.startStoring();
        this.facade.raiseEvent({type: ORYX.CONFIG.EVENT_STENCIL_SET_LOADED});
    },
    startStoring: function() {
        this.historyInterval = setInterval(this.addToHistory.bind(this), ORYX.LOCAL_HISTORY_TIMEOUT);
    },
    stopStoring: function() {
        clearInterval(this.historyInterval);
    }

});<commit_msg>localhistory - fixing toolbar indexes<commit_after>if (!ORYX.Plugins)
    ORYX.Plugins = {};

if (!ORYX.Config)
    ORYX.Config = {};

function updateHistorySVG() {
    document.getElementById('svgviewerid').innerHTML = ORYX.EDITOR.localStorageSVG;
}

ORYX.Plugins.LocalHistory = Clazz.extend({
    construct: function(facade){
        this.facade = facade;
        this.historyEntry;
        this.historyProxy;
        this.historyStore;
        this.storage;
        this.fail;
        this.uid;
        this.historyInterval;

        if(this.haveSupportForLocalHistory()) {
            this.setupAndLoadHistoryData();
            this.startStoring();
        }

        this.facade.offer({
            'name': "Display Local History",
            'functionality': this.displayLocalHistory.bind(this),
            'group': "localstorage",
            'icon': ORYX.PATH + "images/view.png",
             dropDownGroupIcon : ORYX.PATH + "images/localhistory.png",
            'description': "Display Local History",
            'index': 1,
            'minShape': 0,
            'maxShape': 0,
            'isEnabled': function(){
                profileParamName = "profile";
                profileParamName = profileParamName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
                regexSa = "[\\?&]"+profileParamName+"=([^&#]*)";
                regexa = new RegExp( regexSa );
                profileParams = regexa.exec( window.location.href );
                profileParamValue = profileParams[1];
                return profileParamValue == "jbpm" && ORYX.LOCAL_HISTORY_ENABLED;
            }.bind(this)
        });

        this.facade.offer({
            'name': "Clear Local History",
            'functionality': this.clearLocalHistory.bind(this),
            'group': "localstorage",
            'icon': ORYX.PATH + "images/clear.png",
            dropDownGroupIcon : ORYX.PATH + "images/localhistory.png",
            'description': "Clear Local History",
            'index': 2,
            'minShape': 0,
            'maxShape': 0,
            'isEnabled': function(){
                profileParamName = "profile";
                profileParamName = profileParamName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
                regexSa = "[\\?&]"+profileParamName+"=([^&#]*)";
                regexa = new RegExp( regexSa );
                profileParams = regexa.exec( window.location.href );
                profileParamValue = profileParams[1];
                return profileParamValue == "jbpm" && ORYX.LOCAL_HISTORY_ENABLED;
            }.bind(this)
        });

        this.facade.offer({
            'name': "Enable Local History",
            'functionality': this.enableLocalHistory.bind(this),
            'group': "localstorage",
            'icon': ORYX.PATH + "images/enable.png",
            dropDownGroupIcon : ORYX.PATH + "images/localhistory.png",
            'description': "Enable Local History",
            'index': 3,
            'minShape': 0,
            'maxShape': 0,
            'isEnabled': function(){
                profileParamName = "profile";
                profileParamName = profileParamName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
                regexSa = "[\\?&]"+profileParamName+"=([^&#]*)";
                regexa = new RegExp( regexSa );
                profileParams = regexa.exec( window.location.href );
                profileParamValue = profileParams[1];
                return profileParamValue == "jbpm" && !ORYX.LOCAL_HISTORY_ENABLED;
            }.bind(this)
        });

        this.facade.offer({
            'name': "Disable Local History",
            'functionality': this.disableLocalHistory.bind(this),
            'group': "localstorage",
            'icon': ORYX.PATH + "images/disable.png",
            dropDownGroupIcon : ORYX.PATH + "images/localhistory.png",
            'description': "Disable Local History",
            'index': 4,
            'minShape': 0,
            'maxShape': 0,
            'isEnabled': function(){
                profileParamName = "profile";
                profileParamName = profileParamName.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
                regexSa = "[\\?&]"+profileParamName+"=([^&#]*)";
                regexa = new RegExp( regexSa );
                profileParams = regexa.exec( window.location.href );
                profileParamValue = profileParams[1];
                return profileParamValue == "jbpm" && ORYX.LOCAL_HISTORY_ENABLED;
            }.bind(this)
        });

        window.onbeforeunload = function(){
            this.stopStoring();
        }.bind(this);
    },
    displayLocalHistory : function() {
        var gridId = Ext.id();
        var grid = new Ext.grid.EditorGridPanel({
            autoScroll: true,
            autoHeight: true,
            store: this.historyStore,
            id: gridId,
            stripeRows: true,
            cm: new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(),
            {
                id: 'pid',
                header: 'Id',
                width: 100,
                dataIndex: 'processid',
                editor: new Ext.form.TextField({ allowBlank: true, disabled: true })
            },
            {
                id: 'pname',
                header: 'Name',
                width: 100,
                dataIndex: 'processname',
                editor: new Ext.form.TextField({ allowBlank: true, disabled: true })
            },
            {
                id: 'ppkg',
                header: 'Package',
                width: 100,
                dataIndex: 'processpkg',
                editor: new Ext.form.TextField({ allowBlank: true, disabled: true })
            },
            {
                id: 'pver',
                header: 'Version',
                width: 100,
                dataIndex: 'processversion',
                editor: new Ext.form.TextField({ allowBlank: true, disabled: true })
            },
            {
                id: 'tms',
                header: 'Time Stamp',
                width: 200,
                dataIndex: 'timestamp',
                editor: new Ext.form.TextField({ allowBlank: true, disabled: true })
            },{
                id: 'pim',
                header: 'Process Image',
                width: 150,
                dataIndex: 'svg',
                renderer: function(val) {
                    if(val && val.length > 0) {
                        ORYX.EDITOR.localStorageSVG = val;
                        return '';
                    } else {
                        return "Process image not available.";
                    }
                    return "";
                }
            }])
        });

        var localHistoryPanel = new Ext.Panel({
            id: 'localHistoryPanel',
            title: 'Select Process Id and click "Restore" to restore.',
            layout:'column',
            items:[
                grid
            ],
            layoutConfig: {
                columns: 1
            },
            defaults: {
                columnWidth: 1.0
            }
        });

        var dialog = new Ext.Window({
            layout		: 'anchor',
            autoCreate	: true,
            title		: 'Local History View',
            height		: 350,
            width		: 780,
            modal		: true,
            collapsible	: false,
            fixedcenter	: true,
            shadow		: true,
            resizable   : true,
            proxyDrag	: true,
            autoScroll  : true,
            keys:[{
                key	: 27,
                fn	: function(){
                    dialog.hide()
                }.bind(this)
            }],
            items		:[localHistoryPanel],
            listeners	:{
                hide: function(){
                    dialog.destroy();
                }.bind(this)
            },
            buttons		: [{
                text: 'Restore',
                handler: function(){
                    if(grid.getSelectionModel().getSelectedCell() != null) {
                        var selectedIndex = grid.getSelectionModel().getSelectedCell()[0];
                        var outValue = this.historyStore.getAt(selectedIndex).data['json'];
                        if(outValue && outValue.length > 0) {
                            this.clearCanvas();
                            var outObj = outValue.evalJSON();
                            this.facade.importJSON(outObj);
                        } else {
                            Ext.Msg.minWidth = 400;
                            Ext.Msg.alert("Invalid Process info. Unable to restore.");
                        }
                        dialog.hide()
                    } else {
                        Ext.Msg.alert('Please select a process id');
                    }
                }.bind(this)
            }, {
                text: ORYX.I18N.PropertyWindow.cancel,
                handler: function(){
                    dialog.hide()
                }.bind(this)
            }]
        });

        dialog.show();
        grid.render();
        grid.focus( false, 100 );
    },
    setupAndLoadHistoryData : function() {
        this.historyEntry = Ext.data.Record.create(
            [
                {name: 'processid' },
                {name: 'processname' },
                {name: 'processpkg'},
                {name: 'processversion'},
                {name: 'timestamp'},
                {name: 'json' },
                {name: 'svg' }
            ]
        );
        this.historyProxy = new Ext.data.MemoryProxy({root: []});
        this.historyStore = new Ext.data.Store({
            autoDestroy: true,
            reader: new Ext.data.JsonReader({
                root: "root"
            }, this.historyEntry),
            proxy: this.historyProxy
        });
        this.historyStore.load();
        if(this.storage) {
            var processJSON = ORYX.EDITOR.getSerializedJSON();
            var processId = jsonPath(processJSON.evalJSON(), "$.properties.id");
            var processPackage = jsonPath(processJSON.evalJSON(), "$.properties.package");
            var processHistory = this.storage.getItem(processPackage + "_" + processId);
            if(processHistory) {
                var history = processHistory.evalJSON();
                for (var i = 0; i < history.length; i ++) {
                    var item = history[i];
                    this.addToStore(item);
                }
            }
        }
    },
    addToStore : function(item) {
        this.historyStore.insert(0, new this.historyEntry({
            processid: item.processid,
            processname: item.processname,
            processpkg: item.processpkg,
            processversion: item.processversion,
            timestamp: new Date(item.timestamp).format("d.m.Y H:i:s"),
            json: item.json,
            svg:  item.svg
        }));
        this.historyStore.commitChanges();
    },
    clearLocalHistory : function() {
        this.historyStore.removeAll();
        this.historyStore.commitChanges();
        var processJSON = ORYX.EDITOR.getSerializedJSON();
        var processId = jsonPath(processJSON.evalJSON(), "$.properties.id");
        this.storage.removeItem(processId);
        Ext.Msg.minWidth = 400;
        Ext.Msg.alert("Local History has been cleared.");
    },
    enableLocalHistory : function() {
        this.setupAndLoadHistoryData();
        Ext.Msg.minWidth = 400;
        Ext.Msg.alert("Local History has been enabled.");
    },
    disableLocalHistory : function() {
        Ext.Msg.minWidth = 400;
        Ext.Msg.alert("Local History has been disabled.");
    },
    haveSupportForLocalHistory : function() {
        try {
            this.uid = new Date;
            (this.storage = window.localStorage).setItem(this.uid, this.uid);
            this.fail = this.storage.getItem(this.uid) != this.uid;
            this.storage.removeItem(this.uid);
            this.fail && (this.storage = false);
        } catch(e) {}
        return this.storage && ORYX.LOCAL_HISTORY_ENABLED;
    },
    addToHistory : function() {
        var processJSON = ORYX.EDITOR.getSerializedJSON();
        var formattedSvgDOM = DataManager.serialize(ORYX.EDITOR.getCanvas().getSVGRepresentation(false));
        var processName = jsonPath(processJSON.evalJSON(), "$.properties.name");
        var processPackage = jsonPath(processJSON.evalJSON(), "$.properties.package");
        var processId = jsonPath(processJSON.evalJSON(), "$.properties.id");
        var processVersion = jsonPath(processJSON.evalJSON(), "$.properties.version");

        var item = {
            processid: processId,
            processname: processName,
            processpkg: processPackage,
            processversion: processVersion,
            timestamp: new Date().getTime(),
            json: processJSON,
            svg: formattedSvgDOM
        };

        try {
            var processHistory = this.storage.getItem(processPackage + "_" + processId);
            if(processHistory) {
                var pobject = processHistory.evalJSON();
                pobject.push(item);
                this.storage.setItem(processPackage + "_" + processId, eval(JSON.stringify(pobject)));
            } else {
                var addArray = new Array();
                addArray.push(item);
                this.storage.setItem(processPackage + "_" + processId, eval(JSON.stringify(addArray)));
            }
            this.addToStore(item);
        } catch (e) {
            Ext.Msg.minWidth = 500;
            Ext.Msg.alert("Local History quota exceeded. Clearing local history.");
            this.clearLocalHistory();

        }
    },
    clearCanvas: function() {
        ORYX.EDITOR.getCanvas().nodes.each(function(node) {
            ORYX.EDITOR.deleteShape(node);
        }.bind(this));

        ORYX.EDITOR.getCanvas().edges.each(function(edge) {
            ORYX.EDITOR.deleteShape(edge);
        }.bind(this));
    },
    disableLocalHistory: function() {
        ORYX.LOCAL_HISTORY_ENABLED = false;
        this.stopStoring();
        this.facade.raiseEvent({type: ORYX.CONFIG.EVENT_STENCIL_SET_LOADED});
    },
    enableLocalHistory: function() {
        ORYX.LOCAL_HISTORY_ENABLED = true;
        this.setupAndLoadHistoryData();
        this.startStoring();
        this.facade.raiseEvent({type: ORYX.CONFIG.EVENT_STENCIL_SET_LOADED});
    },
    startStoring: function() {
        this.historyInterval = setInterval(this.addToHistory.bind(this), ORYX.LOCAL_HISTORY_TIMEOUT);
    },
    stopStoring: function() {
        clearInterval(this.historyInterval);
    }

});<|endoftext|>


<commit_before>import styled from 'styled-components'
import { media } from 'theme/utils/media'

const Base = styled.div`
  h2 {
    font-size: 1.99rem;
    margin-top: 2em;
  }

  h3 {
    font-size: 1.524rem;
    margin-top: .5em;
  }

  h3:nth-last-child(2) {
    margin-bottom: .8em;
  }
`

const Wrapper = styled.div`background-color: red;`

export const NoteContainer = Base.extend`
  letter-spacing: -.010em;
  section {
    display: flex;
    flex-wrap: wrap;

    h3 {
      width: 50%;
      font-size: 1.2em;
      ${media.tablet`
        width: 100%;
      `};
    }
  }
`

export const BlogContainer = Base.extend`
  p {
    cursor: default;
    ${media.tablet`
      // text-align: center;
    `};
  }
`

export const LinkContainer = Base.extend`
  h3 {
    font-size: 1em;
  }
`

export const ProjectContainer = Base.extend`
  width: 100%;
  section {
    display: flex;
    flex-wrap: wrap;

    h3 {
      width: 33.3%;
      font-size: 1.2em;
      ${media.tablet`
        width: 50%;
      `} ${media.phone`
        width: 100%;
      `};
    }
  }
`
<commit_msg>update link font size<commit_after>import styled from 'styled-components'
import { media } from 'theme/utils/media'

const Base = styled.div`
  h2 {
    font-size: 1.99rem;
    margin-top: 2em;
  }

  h3 {
    font-size: 1.524rem;
    margin-top: .5em;
  }

  h3:nth-last-child(2) {
    margin-bottom: .8em;
  }
`

const Wrapper = styled.div`background-color: red;`

export const NoteContainer = Base.extend`
  letter-spacing: -.010em;
  section {
    display: flex;
    flex-wrap: wrap;

    h3 {
      width: 50%;
      font-size: 1.2em;
      ${media.tablet`
        width: 100%;
      `};
    }
  }
`

export const BlogContainer = Base.extend`
  p {
    cursor: default;
    ${media.tablet`
      // text-align: center;
    `};
  }
`

export const LinkContainer = Base.extend`
  h3 {
    font-size: 1.2em;
  }
`

export const ProjectContainer = Base.extend`
  width: 100%;
  section {
    display: flex;
    flex-wrap: wrap;

    h3 {
      width: 33.3%;
      font-size: 1.2em;
      ${media.tablet`
        width: 50%;
      `} ${media.phone`
        width: 100%;
      `};
    }
  }
`
<|endoftext|>


<commit_before>/* eslint import/no-extraneous-dependencies: ['error', {'devDependencies': true}] */
import webpack from 'webpack';
import {getIfUtils, removeEmpty} from 'webpack-config-utils';
import AssetsPlugin from 'assets-webpack-plugin';
import Visualizer from 'webpack-visualizer-plugin';
import LodashModuleReplacementPlugin from 'lodash-webpack-plugin';
import CleanPlugin from 'clean-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';

export default function (env) {
  const {ifDevelopment, ifProduction} = getIfUtils(env);
  const assetsPath = './lib';

  return {
    devtool: ifDevelopment('eval-source-map', 'source-map'),
    entry: {
      example: './src/index',
      vendor: ['react', 'react-dom', 'spectacle']
    },
    output: {
      path: assetsPath,
      filename: '[name].js'
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
          options: {
            presets: [['es2015', {modules: false}], 'react'],
            plugins: removeEmpty([
              ifProduction('transform-react-remove-prop-types'),
              ifDevelopment('transform-react-jsx-source'),
              'transform-runtime',
              'lodash'
            ]),
            comments: false,
            cacheDirectory: true
          }
        }, {
          test: /\.css$/,
          loader: 'style-loader!css-loader'
        },
        {
          test: /\.(png|jpg|gif)$/,
          use: [
            {
              loader: 'file-loader',
              options: {
                limit: 8192
              }
            },
            {
              loader: 'img-loader',
              options: {
                progressive: true
              }
            }
          ]
        },
        {
          test: /\.svg$/,
          loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
        },
        {
          test: /\.mustache$/,
          loader: 'mustache-loader'
        }
      ]
    },
    plugins: removeEmpty([
      ifProduction(new CleanPlugin([assetsPath], {root: __dirname})),
      new AssetsPlugin(),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(env)
        }
      }),
      ifDevelopment(new webpack.NamedModulesPlugin()),
      new webpack.optimize.CommonsChunkPlugin({
        names: ['vendor', 'manifest']
      }),
      ifProduction(new webpack.LoaderOptionsPlugin({
        minimize: true,
        debug: false
      })),
      ifProduction(new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          screw_ie8: true,
          warnings: false
        }
      })),
      ifProduction(new Visualizer()),
      ifProduction(new LodashModuleReplacementPlugin()),
      new HtmlWebpackPlugin({
        template: 'src/index.mustache'
      })
    ])
  };
}
<commit_msg>build(entry-directories): output to subdirectories for per-presentation entry points<commit_after>/* eslint import/no-extraneous-dependencies: ['error', {'devDependencies': true}] */
import webpack from 'webpack';
import {getIfUtils, removeEmpty} from 'webpack-config-utils';
import AssetsPlugin from 'assets-webpack-plugin';
import Visualizer from 'webpack-visualizer-plugin';
import LodashModuleReplacementPlugin from 'lodash-webpack-plugin';
import CleanPlugin from 'clean-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';

export default function (env) {
  const {ifDevelopment, ifProduction} = getIfUtils(env);
  const assetsPath = './lib';
  const defaultChunks = ['vendor', 'manifest'];

  return {
    devtool: ifDevelopment('eval-source-map', 'source-map'),
    entry: {
      'example/index': './src/index',
      vendor: ['react', 'react-dom', 'spectacle']
    },
    output: {
      path: assetsPath,
      filename: '[name].js'
    },
    module: {
      rules: [
        {
          test: /\.js$/,
          exclude: /node_modules/,
          loader: 'babel-loader',
          options: {
            presets: [['es2015', {modules: false}], 'react'],
            plugins: removeEmpty([
              ifProduction('transform-react-remove-prop-types'),
              ifDevelopment('transform-react-jsx-source'),
              'transform-runtime',
              'lodash'
            ]),
            comments: false,
            cacheDirectory: true
          }
        }, {
          test: /\.css$/,
          loader: 'style-loader!css-loader'
        },
        {
          test: /\.(png|jpg|gif)$/,
          use: [
            {
              loader: 'file-loader',
              options: {
                limit: 8192,
                publicPath: '..//'
              }
            },
            {
              loader: 'img-loader',
              options: {
                progressive: true
              }
            }
          ]
        },
        {
          test: /\.svg$/,
          loader: 'url-loader?limit=10000&mimetype=image/svg+xml'
        },
        {
          test: /\.mustache$/,
          loader: 'mustache-loader'
        }
      ]
    },
    plugins: removeEmpty([
      ifProduction(new CleanPlugin([assetsPath], {root: __dirname})),
      new AssetsPlugin(),
      new webpack.DefinePlugin({
        'process.env': {
          NODE_ENV: JSON.stringify(env)
        }
      }),
      ifDevelopment(new webpack.NamedModulesPlugin()),
      new webpack.optimize.CommonsChunkPlugin({
        names: defaultChunks
      }),
      ifProduction(new webpack.LoaderOptionsPlugin({
        minimize: true,
        debug: false
      })),
      ifProduction(new webpack.optimize.UglifyJsPlugin({
        sourceMap: true,
        compress: {
          screw_ie8: true,
          warnings: false
        }
      })),
      ifProduction(new Visualizer()),
      ifProduction(new LodashModuleReplacementPlugin()),
      new HtmlWebpackPlugin({
        chunks: [...defaultChunks, 'example/index'],
        filename: 'example/index.html',
        template: 'src/index.mustache'
      })
    ])
  };
}
<|endoftext|>


<commit_before>/*
Language: AVR Assembler
Author: Vladimir Ermakov <vooon341@gmail.com>
Category: assembler
Website: https://www.microchip.com/webdoc/avrassembler/avrassembler.wb_instruction_list.html
*/

function(hljs) {
  return {
    case_insensitive: true,
    lexemes: '\\.?' + hljs.IDENT_RE,
    keywords: {
      keyword:
        /* mnemonic */
        'adc add adiw and andi asr bclr bld brbc brbs brcc brcs break breq brge brhc brhs ' +
        'brid brie brlo brlt brmi brne brpl brsh brtc brts brvc brvs bset bst call cbi cbr ' +
        'clc clh cli cln clr cls clt clv clz com cp cpc cpi cpse dec eicall eijmp elpm eor ' +
        'fmul fmuls fmulsu icall ijmp in inc jmp ld ldd ldi lds lpm lsl lsr mov movw mul ' +
        'muls mulsu neg nop or ori out pop push rcall ret reti rjmp rol ror sbc sbr sbrc sbrs ' +
        'sec seh sbi sbci sbic sbis sbiw sei sen ser ses set sev sez sleep spm st std sts sub ' +
        'subi swap tst wdr',
      built_in:
        /* general purpose registers */
        'r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 ' +
        'r23 r24 r25 r26 r27 r28 r29 r30 r31 x|0 xh xl y|0 yh yl z|0 zh zl ' +
        /* IO Registers (ATMega128) */
        'ucsr1c udr1 ucsr1a ucsr1b ubrr1l ubrr1h ucsr0c ubrr0h tccr3c tccr3a tccr3b tcnt3h ' +
        'tcnt3l ocr3ah ocr3al ocr3bh ocr3bl ocr3ch ocr3cl icr3h icr3l etimsk etifr tccr1c ' +
        'ocr1ch ocr1cl twcr twdr twar twsr twbr osccal xmcra xmcrb eicra spmcsr spmcr portg ' +
        'ddrg ping portf ddrf sreg sph spl xdiv rampz eicrb eimsk gimsk gicr eifr gifr timsk ' +
        'tifr mcucr mcucsr tccr0 tcnt0 ocr0 assr tccr1a tccr1b tcnt1h tcnt1l ocr1ah ocr1al ' +
        'ocr1bh ocr1bl icr1h icr1l tccr2 tcnt2 ocr2 ocdr wdtcr sfior eearh eearl eedr eecr ' +
        'porta ddra pina portb ddrb pinb portc ddrc pinc portd ddrd pind spdr spsr spcr udr0 ' +
        'ucsr0a ucsr0b ubrr0l acsr admux adcsr adch adcl porte ddre pine pinf',
      meta:
        '.byte .cseg .db .def .device .dseg .dw .endmacro .equ .eseg .exit .include .list ' +
        '.listmac .macro .nolist .org .set'
    },
    contains: [
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.COMMENT(
        ';',
        '$',
        {
          relevance: 0
        }
      ),
      hljs.C_NUMBER_MODE, // 0x..., decimal, float
      hljs.BINARY_NUMBER_MODE, // 0b...
      {
        className: 'number',
        begin: '\\b(\\$[a-zA-Z0-9]+|0o[0-7]+)' // $..., 0o...
      },
      hljs.QUOTE_STRING_MODE,
      {
        className: 'string',
        begin: '\'', end: '[^\\\\]\'',
        illegal: '[^\\\\][^\']'
      },
      {className: 'symbol',  begin: '^[A-Za-z0-9_.$]+:'},
      {className: 'meta', begin: '#', end: '$'},
      {  // подстановка в «.macro»
        className: 'subst',
        begin: '@[0-9]+'
      }
    ]
  };
}
<commit_msg>(avrasm) update comment to english (#2197)<commit_after>/*
Language: AVR Assembler
Author: Vladimir Ermakov <vooon341@gmail.com>
Category: assembler
Website: https://www.microchip.com/webdoc/avrassembler/avrassembler.wb_instruction_list.html
*/

function(hljs) {
  return {
    case_insensitive: true,
    lexemes: '\\.?' + hljs.IDENT_RE,
    keywords: {
      keyword:
        /* mnemonic */
        'adc add adiw and andi asr bclr bld brbc brbs brcc brcs break breq brge brhc brhs ' +
        'brid brie brlo brlt brmi brne brpl brsh brtc brts brvc brvs bset bst call cbi cbr ' +
        'clc clh cli cln clr cls clt clv clz com cp cpc cpi cpse dec eicall eijmp elpm eor ' +
        'fmul fmuls fmulsu icall ijmp in inc jmp ld ldd ldi lds lpm lsl lsr mov movw mul ' +
        'muls mulsu neg nop or ori out pop push rcall ret reti rjmp rol ror sbc sbr sbrc sbrs ' +
        'sec seh sbi sbci sbic sbis sbiw sei sen ser ses set sev sez sleep spm st std sts sub ' +
        'subi swap tst wdr',
      built_in:
        /* general purpose registers */
        'r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 ' +
        'r23 r24 r25 r26 r27 r28 r29 r30 r31 x|0 xh xl y|0 yh yl z|0 zh zl ' +
        /* IO Registers (ATMega128) */
        'ucsr1c udr1 ucsr1a ucsr1b ubrr1l ubrr1h ucsr0c ubrr0h tccr3c tccr3a tccr3b tcnt3h ' +
        'tcnt3l ocr3ah ocr3al ocr3bh ocr3bl ocr3ch ocr3cl icr3h icr3l etimsk etifr tccr1c ' +
        'ocr1ch ocr1cl twcr twdr twar twsr twbr osccal xmcra xmcrb eicra spmcsr spmcr portg ' +
        'ddrg ping portf ddrf sreg sph spl xdiv rampz eicrb eimsk gimsk gicr eifr gifr timsk ' +
        'tifr mcucr mcucsr tccr0 tcnt0 ocr0 assr tccr1a tccr1b tcnt1h tcnt1l ocr1ah ocr1al ' +
        'ocr1bh ocr1bl icr1h icr1l tccr2 tcnt2 ocr2 ocdr wdtcr sfior eearh eearl eedr eecr ' +
        'porta ddra pina portb ddrb pinb portc ddrc pinc portd ddrd pind spdr spsr spcr udr0 ' +
        'ucsr0a ucsr0b ubrr0l acsr admux adcsr adch adcl porte ddre pine pinf',
      meta:
        '.byte .cseg .db .def .device .dseg .dw .endmacro .equ .eseg .exit .include .list ' +
        '.listmac .macro .nolist .org .set'
    },
    contains: [
      hljs.C_BLOCK_COMMENT_MODE,
      hljs.COMMENT(
        ';',
        '$',
        {
          relevance: 0
        }
      ),
      hljs.C_NUMBER_MODE, // 0x..., decimal, float
      hljs.BINARY_NUMBER_MODE, // 0b...
      {
        className: 'number',
        begin: '\\b(\\$[a-zA-Z0-9]+|0o[0-7]+)' // $..., 0o...
      },
      hljs.QUOTE_STRING_MODE,
      {
        className: 'string',
        begin: '\'', end: '[^\\\\]\'',
        illegal: '[^\\\\][^\']'
      },
      {className: 'symbol',  begin: '^[A-Za-z0-9_.$]+:'},
      {className: 'meta', begin: '#', end: '$'},
      {  // substitution within a macro
        className: 'subst',
        begin: '@[0-9]+'
      }
    ]
  };
}
<|endoftext|>


<commit_before>/*
 * This file is part of the WordPress Standard project.
 *
 * Copyright (c) 2015-2016 LIN3S <info@lin3s.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Gorka Laucirica <gorka.lauzirika@gmail.com>
 * @author Beñat Espiña <benatespina@gmail.com>
 * @author Jon Torrado <jontorrado@gmail.com>
 */

'use strict';

var gulp = require('gulp'),
  concat = require('gulp-concat'),
  cssnext = require('postcss-cssnext'),
  cssnano = require('gulp-cssnano'),
  file = require('gulp-file'),
  livereload = require('gulp-livereload'),
  modernizr = require('gulp-modernizr'),
  plumber = require('gulp-plumber'),
  postcss = require('gulp-postcss'),
  rename = require('gulp-rename'),
  sass = require('gulp-sass'),
  scsslint = require('gulp-scss-lint'),
  svgSprite = require('gulp-svg-sprite'),
  uglify = require('gulp-uglify');

var paths = {
  npm: './node_modules',
  assets: './Resources/assets',
  sass: './Resources/assets/scss',
  js: './Resources/assets/js',
  css: './Resources/build/css',
  buildJs: './Resources/build/js',
  svg: './Resources/assets/svg',
  buildSvg: './Resources/build/svg'
};

var watch = {
  sass: './Resources/assets/scss/**/*.scss',
  svg: './Resources/assets/svg/**/*.svg'
};

// Plumber error function
function onError(err) {
  console.log(err);
  this.emit('end');
}

gulp.task('wp-style', function () {
  var content = '/*\nTheme Name: WordPress Standard';
  content += '\nAuthor: LIN3S';
  content += '\nAuthor URI: http://www.lin3s.com/\n*/';

  return file('style.css', content, {src: true}).pipe(gulp.dest('.'));
});

gulp.task('scss-lint', function () {
  return gulp.src([
      watch.sass,
      '!' + paths.sass + '/base/_reset.scss',
      '!' + paths.sass + '/base/_grid.scss'
    ])
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(scsslint({
      'config': './.scss_lint.yml'
    }));
});

gulp.task('sass', ['wp-style', 'scss-lint'], function () {
  return gulp.src(paths.sass + '/app.scss')
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(sass({
      errLogToConsole: true
    }))
    .pipe(postcss([cssnext]))
    .pipe(gulp.dest(paths.css))
    .pipe(livereload());
});

gulp.task('sass:prod', function () {
  return gulp.src([
      paths.sass + '/app.scss'
      // Put here css/scss vendor files, for example:
      // paths.npm + '/slick-carousel/slick/slick.scss'
    ])
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(sass())
    .pipe(postcss([cssnext]))
    .pipe(cssnano({
      keepSpecialComments: 1,
      rebase: false
    }))
    .pipe(rename({
      suffix: '.min'
    }))
    .pipe(gulp.dest(paths.css));
});

gulp.task('sprites', function () {
  return gulp.src(paths.svg + '/*.svg')
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(svgSprite({
      mode: {
        symbol: {
          dest: '',
          sprite: 'symbols',
          example: {dest: 'symbols'}
        }
      }
    }))
    .pipe(gulp.dest(paths.buildSvg));
});

gulp.task('vendor-css', function () {
  return gulp.src([
      // Put here css files of vendors, for example:
      // paths.npm + '/slick-carousel/slick/slick.css'
    ])
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(concat('vendor.css'))
    .pipe(gulp.dest(paths.css));
});

gulp.task('modernizr', function () {
  return gulp.src([paths.js + '/*.js'])
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(modernizr({
      'options': [
        'setClasses', 'addTest', 'html5printshiv', 'testProp', 'fnBind'
      ],
      'tests': ['objectfit', 'flexbox']
    }))
    .pipe(gulp.dest(paths.buildJs))
});

gulp.task('js:prod', ['modernizr'], function () {
  return gulp.src([
      paths.buildJs + '/modernizr.js',
      paths.npm + '/fastclick/lib/fastclick.js',
      paths.npm + '/svg4everybody/dist/svg4everybody.min.js',
      // Put here js vendor files, for example:
      // paths.npm + '/slick-carousel/slick/slick.min.js'
      paths.js + '/*.js'
    ])
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(concat('app.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest(paths.buildJs));
});

gulp.task('watch', function () {
  livereload.listen();
  gulp.watch(watch.sass, ['sass']);
  gulp.watch(watch.svg, ['sprites']);
});

gulp.task('default', ['sass', 'sprites', 'modernizr']);

gulp.task('prod', ['sass:prod', 'sprites', 'modernizr', 'js:prod']);
<commit_msg>All vendors minified<commit_after>/*
 * This file is part of the WordPress Standard project.
 *
 * Copyright (c) 2015-2016 LIN3S <info@lin3s.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @author Gorka Laucirica <gorka.lauzirika@gmail.com>
 * @author Beñat Espiña <benatespina@gmail.com>
 * @author Jon Torrado <jontorrado@gmail.com>
 */

'use strict';

var gulp = require('gulp'),
  concat = require('gulp-concat'),
  cssnext = require('postcss-cssnext'),
  cssnano = require('gulp-cssnano'),
  file = require('gulp-file'),
  livereload = require('gulp-livereload'),
  modernizr = require('gulp-modernizr'),
  plumber = require('gulp-plumber'),
  postcss = require('gulp-postcss'),
  rename = require('gulp-rename'),
  sass = require('gulp-sass'),
  scsslint = require('gulp-scss-lint'),
  svgSprite = require('gulp-svg-sprite'),
  uglify = require('gulp-uglify');

var paths = {
  npm: './node_modules',
  assets: './Resources/assets',
  sass: './Resources/assets/scss',
  js: './Resources/assets/js',
  css: './Resources/build/css',
  buildJs: './Resources/build/js',
  svg: './Resources/assets/svg',
  buildSvg: './Resources/build/svg'
};

var watch = {
  sass: './Resources/assets/scss/**/*.scss',
  svg: './Resources/assets/svg/**/*.svg'
};

// Plumber error function
function onError(err) {
  console.log(err);
  this.emit('end');
}

gulp.task('wp-style', function () {
  var content = '/*\nTheme Name: WordPress Standard';
  content += '\nAuthor: LIN3S';
  content += '\nAuthor URI: http://www.lin3s.com/\n*/';

  return file('style.css', content, {src: true}).pipe(gulp.dest('.'));
});

gulp.task('scss-lint', function () {
  return gulp.src([
      watch.sass,
      '!' + paths.sass + '/base/_reset.scss',
      '!' + paths.sass + '/base/_grid.scss'
    ])
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(scsslint({
      'config': './.scss_lint.yml'
    }));
});

gulp.task('sass', ['wp-style', 'scss-lint'], function () {
  return gulp.src(paths.sass + '/app.scss')
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(sass({
      errLogToConsole: true
    }))
    .pipe(postcss([cssnext]))
    .pipe(gulp.dest(paths.css))
    .pipe(livereload());
});

gulp.task('sass:prod', function () {
  return gulp.src([
      paths.sass + '/app.scss'
      // Put here css/scss vendor files, for example:
      // paths.npm + '/slick-carousel/slick/slick.scss'
    ])
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(sass())
    .pipe(postcss([cssnext]))
    .pipe(cssnano({
      keepSpecialComments: 1,
      rebase: false
    }))
    .pipe(rename({
      suffix: '.min'
    }))
    .pipe(gulp.dest(paths.css));
});

gulp.task('sprites', function () {
  return gulp.src(paths.svg + '/*.svg')
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(svgSprite({
      mode: {
        symbol: {
          dest: '',
          sprite: 'symbols',
          example: {dest: 'symbols'}
        }
      }
    }))
    .pipe(gulp.dest(paths.buildSvg));
});

gulp.task('modernizr', function () {
  return gulp.src([paths.js + '/*.js'])
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(modernizr({
      'options': [
        'setClasses', 'addTest', 'html5printshiv', 'testProp', 'fnBind'
      ],
      'tests': ['objectfit', 'flexbox']
    }))
    .pipe(gulp.dest(paths.buildJs))
});

gulp.task('js:prod', ['modernizr'], function () {
  return gulp.src([
      paths.buildJs + '/modernizr.js',
      paths.npm + '/fastclick/lib/fastclick.js',
      paths.npm + '/svg4everybody/dist/svg4everybody.min.js',
      // Put here js vendor files, for example:
      // paths.npm + '/slick-carousel/slick/slick.min.js'
      paths.js + '/*.js'
    ])
    .pipe(plumber({
      errorHandler: onError
    }))
    .pipe(concat('app.min.js'))
    .pipe(uglify())
    .pipe(gulp.dest(paths.buildJs));
});

gulp.task('watch', function () {
  livereload.listen();
  gulp.watch(watch.sass, ['sass']);
  gulp.watch(watch.svg, ['sprites']);
});

gulp.task('default', ['sass', 'sprites', 'modernizr']);

gulp.task('prod', ['sass:prod', 'sprites', 'modernizr', 'js:prod']);
<|endoftext|>