<commit_before>// Handle the colormaps and color constants.

import rx from '/imports/common/rx';
import '/imports/lib/color'; // source of 'Color' object
import jPalette from '/imports/lib/jPalette';
import util from '/imports/common/util';

// Some color constants
var BINARY_BOTH_ON_DARK_BG = '#00FF00',
    BINARY_BOTH_ON_LIGHT_BG = '#AA00AA',
    BINARY_BOTH_OFF_DARK_BG = '#404040',
    BINARY_BOTH_OFF_LIGHT_BG = '#c0c0c0',
    BINARY_1ST_ON_DARK_BG = '#ffff00',  // second is off
    BINARY_1ST_ON_LIGHT_BG = '#ff0000',
    BINARY_2ND_ON = '#0000ff',          // first is off

    CONTINUOUS_HIGH_DARK_BG = BINARY_1ST_ON_DARK_BG,
    CONTINUOUS_HIGH_LIGHT_BG  = BINARY_1ST_ON_LIGHT_BG,
    CONTINUOUS_LOW_DARK_BG = BINARY_BOTH_OFF_DARK_BG,
    CONTINUOUS_LOW_LIGHT_BG  = BINARY_BOTH_OFF_LIGHT_BG,

    CONTINUOUS2_BOTH_HIGH_DARK_BG = BINARY_BOTH_ON_DARK_BG,
    CONTINUOUS2_BOTH_HIGH_LIGHT_BG = BINARY_BOTH_ON_LIGHT_BG,
    CONTINUOUS2_2ND_HIGH_DARK_BG = BINARY_2ND_ON, // first is low
    CONTINUOUS2_2ND_HIGH_LIGHT_BG  = CONTINUOUS2_2ND_HIGH_DARK_BG,

    DISABLED = '#aaaaaa', // not for colormap, but for some disabled widgets
    NO_ATTRS = 'cyan',
    NO_DATA_DARK_BG = '#303030',
    NO_DATA_LIGHT_BG = '#E0E0E0';

exports.disabled = function () {
    // Not for colormap, but for some disabled widgets/
    return DISABLED;
};

exports.defaultContLow = function () {
    return (Session.equals('background', 'white')) ?
        CONTINUOUS_LOW_LIGHT_BG : CONTINUOUS_LOW_DARK_BG ;
};

exports.defaultContHigh = function () {
    return (Session.equals('background', 'white')) ?
        CONTINUOUS_HIGH_LIGHT_BG : CONTINUOUS_HIGH_DARK_BG;
};

exports.defaultContBothHigh = function () {
    return (Session.equals('background', 'white')) ?
        CONTINUOUS2_BOTH_HIGH_LIGHT_BG : CONTINUOUS2_BOTH_HIGH_DARK_BG;
};

exports.defaultCont2High1Low = function () {
    return (Session.equals('background', 'white')) ?
        CONTINUOUS2_2ND_HIGH_LIGHT_BG : CONTINUOUS2_2ND_HIGH_DARK_BG;
};

exports.defaultBinaryOff = function () {
    return (Session.equals('background', 'white')) ?
        BINARY_BOTH_OFF_LIGHT_BG : BINARY_BOTH_OFF_DARK_BG;
};

exports.defaultBinaryOn = function () {
    return (Session.equals('background', 'white')) ?
        BINARY_1ST_ON_LIGHT_BG : BINARY_1ST_ON_DARK_BG;
};

exports.defaultBinBothOn = function () {
    return (Session.equals('background', 'white')) ?
        BINARY_BOTH_ON_LIGHT_BG : BINARY_BOTH_ON_DARK_BG;
};

exports.defaultSecondBinOn = function () {
    return BINARY_2ND_ON;
};

exports.noDataColor = function () {
    return (Session.equals('background', 'white')) ?
        NO_DATA_LIGHT_BG : NO_DATA_DARK_BG;
};

exports.noAttrsColor = function () {
    return NO_ATTRS;
};

exports.have_colormap = function (colormap_name) {

    // Returns true if the given string is the name of a colormap, or false if
    // it is only a layer.
    return (colormap_name in colormaps);
};

exports.findColorCount = function (layer_name) {
    // Find the number of colors for this layer. Continuous values and
    // undefined layer_names are assigned a count of zero.
    var nColors = 0;

    if (util.is_cat_or_bin(layer_name)) {
        var colormap = colormaps[layer_name];
        if (colormap.length > 0) {

            // Categorical values
            nColors = colormap.length;
        }
    }
    return nColors;
};

exports.continuousLowColor = function(layerName) {
    // Get's the low color for a continuous attribute using the
    // appropriate colormap entry. If colormap entry is not present
    // then a default according to the background is made.
    var color,
        low = 0;
    if (colormaps[layerName]) {
        color =  colormaps[layerName][low].color.hexString();
    } else {
        colormaps[layerName] = exports.defaultContinuous();
        color =  colormaps[layerName][low].color.hexString();
    }
    return color;
};

exports.continuousHighColor = function(layerName) {
    // Get's the high color for a continuous attribute using the
    // appropriate colormap entry. If colormap entry is not present
    // then a default according to the background is made.
    var color,
        high = 1;
    if (colormaps[layerName]) {
        color =  colormaps[layerName][high].color.hexString();
    } else {
        colormaps[layerName] = exports.defaultContinuous();
        color =  colormaps[layerName][high].color.hexString();
    }
    return color;
};

exports.binaryOffColor = function(layerName) {
    // Get's the off color for a binary attribute using the
    // appropriate colormap entry. If colormap entry is not present
    // then a default according to the background is made.
    var color,
        off = 0;
    if (colormaps[layerName]) {
        color =  colormaps[layerName][off].color.hexString();
    } else {
        colormaps[layerName] = exports.defaultBinary();
        color =  colormaps[layerName][off].color.hexString();
    }
    return color;
};

exports.binaryOnColor = function(layerName) {
    // Get's the on color for a binary attribute using the
    // appropriate colormap entry. If colormap entry is not present
    // then a default according to the background is made.
    var color,
        on = 1;

    if (colormaps[layerName]) {
        color =  colormaps[layerName][on].color.hexString();
    } else {
        colormaps[layerName] = exports.defaultBinary();
        color =  colormaps[layerName][on].color.hexString();
    }
    return color;
};

exports.defaultBinary = function () {
    var defaultColormap = [
        {
            "color": new Color(exports.defaultBinaryOff()),
            "name": "0",
        },
        {
            "color": new Color(exports.defaultBinaryOn()),
            "name": "1",
        }
    ];
    return defaultColormap;
};

exports.defaultContinuous = function () {
    var defaultColormap = [
        {
            "color": new Color(exports.defaultContLow()),
            "name": "Low",
        },
        {
            "color": new Color(exports.defaultContHigh()),
            "name": "High",
        }
    ];
    return defaultColormap;
};

export function getOne (attrName) {

    // Return a shallow copy of an attr's colormap.
    if (colormaps[attrName]) {
        return colormaps[attrName].map(cat => {
            return cat
        })
    }
}

export function getCategoryCount (attrName) {

    // Get an array of category strings of a colormap.
    let count = 0
    if (attrName in colormaps) {
        count = colormaps[attrName].length
    }
    return count
}

exports.getCategoryStrings = function(attrName) {

    // Get an array of category strings of a colormap.
    if (attrName in colormaps) {
        return colormaps[attrName].map(cat => cat.name)
    }
    return []
};

exports.getCategoryString = function(attrName, catIndex) {

    // Find the string associated with this category code.
    if (attrName in colormaps) {
        return colormaps[attrName][catIndex].name;
    }
    return ''
};

export function getCategoryIndex (attrName, catName) {

    // Find the index associated with this category string.
    // Start off as if we were passed and index rather than a name.
    let index = catName
    if (attrName in colormaps) {
        colormaps[attrName].forEach((cat, i) => {
            if (cat.name === catName) {
                index = i
            }
        })
    }
    return index
}

exports.updateCategoryColor = function (layerName, catName, newHexStr) {

    // Update the colormap, then redraw the hexmap
    var catI;

    // Find the category index of this color.
    _.find(colormaps[layerName], function (cat, i) {
        if (cat.name === catName) {
            catI = i;
            return true;
        }
        return false;
    });

    // Update the global colormap only saving a persistColor if it is different
    // from the new value.
    // Also, remove any persistColor if it is the same as the new value.
    var cat = colormaps[layerName][catI],
        colorHexStr = cat.color.hexString(),
        persistHexStr = cat.persistColor ?
            cat.persistColor.hexString() : null;

    if (newHexStr === colorHexStr) {
        // nothing to do here

    } else if (newHexStr === persistHexStr) {
        cat.color = cat.persistColor;
        delete cat.persistColor;

    } else if (persistHexStr === null) {
        cat.persistColor = cat.color;
        cat.color = new Color(newHexStr);

    } else {
        cat.color = new Color(newHexStr);
    }
};

exports.toStoreFormat = function (colormap) {

    // Convert one attr colormap into a form that state can save.
    var cats = _.map(colormap, function(val) {
            return val.name;

        }),
        colors = _.map(colormap, function(val) {
            return val.color.hexString();
        });
    return {cats: cats, colors: colors};
};

exports.fromStoreFormatCategories = function (cats, data) {

    // Create an operating colormap for an attribute by the given categories
    // from state, then generate colors. Return the operating colormap and
    // operating data with codes replacing the category strings.

    // Generate colors.
    var jpColormap = _.map(
        jPalette.jColormap.get('hexmap')(cats.length + 1).map,
        function (val, key) { // eslint-disable-line no-unused-vars

            // Ignore alpha, taking the default of one.
            return {r: val.r, g: val.g, b: val.b};
        }
    );

    // Remove the repeating red at the end.
    jpColormap.splice(cats.length, 1);

    // Create the operating colormap.
    var colormap = _.map(jpColormap, function(color, i) {
        return {
            name: cats[i],
            color: new Color(color), // operating color in map
        };
    });

    // Replace category string values in the data with codes.
    var vals = _.map(data, function (strVal) {
        return cats.indexOf(strVal);
    });

    return { colormap: colormap, data: _.object(_.keys(data), vals) };
};

exports.fromStoreFormat = function (colorStore) {

    // Create an operating colormap for an attribute by the given colormap
    // from store, returning the operating colormap.
    return _.map(colorStore.cats, function (cat, i) {
        return {
            name: cat,
            color: new Color(colorStore.colors[i]),
        };
    });
};

exports.received = function (parsed) {

    // Process downloaded color map information.
    for(var i = 0; i < parsed.length; i++) {
        // Get the name of the layer
        var layer_name = parsed[i][0];

        // Skip blank lines
        if(layer_name == "") {
            continue;
        }

        // This holds all the categories (name and color) by integer index
        var colormap = [];

        for (var j = 1; j < parsed[i].length; j += 3) {

            // Store each color assignment.
            // Doesn't run if there aren't any assignments, leaving an empty
            // colormap object that just forces automatic color selection.

            // This holds the index of the category
            var category_index = parseInt(parsed[i][j]);

            // The colormap gets an object with the name and color using the
            // position in the array as the index. The index given in the file
            // is ignored. Color is stored as a Color object.
            colormap[category_index] = {
                name: parsed[i][j + 1],
                color: new Color(parsed[i][j + 2]),
            };
        }

        // Store the finished color map in the global object
        colormaps[layer_name] = colormap;
    }
    rx.set('inited.colormap');
};

<commit_msg>fix occasional error on binary with no colormap<commit_after>// Handle the colormaps and color constants.

import rx from '/imports/common/rx';
import '/imports/lib/color'; // source of 'Color' object
import jPalette from '/imports/lib/jPalette';
import util from '/imports/common/util';

// Some color constants
var BINARY_BOTH_ON_DARK_BG = '#00FF00',
    BINARY_BOTH_ON_LIGHT_BG = '#AA00AA',
    BINARY_BOTH_OFF_DARK_BG = '#404040',
    BINARY_BOTH_OFF_LIGHT_BG = '#c0c0c0',
    BINARY_1ST_ON_DARK_BG = '#ffff00',  // second is off
    BINARY_1ST_ON_LIGHT_BG = '#ff0000',
    BINARY_2ND_ON = '#0000ff',          // first is off

    CONTINUOUS_HIGH_DARK_BG = BINARY_1ST_ON_DARK_BG,
    CONTINUOUS_HIGH_LIGHT_BG  = BINARY_1ST_ON_LIGHT_BG,
    CONTINUOUS_LOW_DARK_BG = BINARY_BOTH_OFF_DARK_BG,
    CONTINUOUS_LOW_LIGHT_BG  = BINARY_BOTH_OFF_LIGHT_BG,

    CONTINUOUS2_BOTH_HIGH_DARK_BG = BINARY_BOTH_ON_DARK_BG,
    CONTINUOUS2_BOTH_HIGH_LIGHT_BG = BINARY_BOTH_ON_LIGHT_BG,
    CONTINUOUS2_2ND_HIGH_DARK_BG = BINARY_2ND_ON, // first is low
    CONTINUOUS2_2ND_HIGH_LIGHT_BG  = CONTINUOUS2_2ND_HIGH_DARK_BG,

    DISABLED = '#aaaaaa', // not for colormap, but for some disabled widgets
    NO_ATTRS = 'cyan',
    NO_DATA_DARK_BG = '#303030',
    NO_DATA_LIGHT_BG = '#E0E0E0';

exports.disabled = function () {
    // Not for colormap, but for some disabled widgets/
    return DISABLED;
};

exports.defaultContLow = function () {
    return (Session.equals('background', 'white')) ?
        CONTINUOUS_LOW_LIGHT_BG : CONTINUOUS_LOW_DARK_BG ;
};

exports.defaultContHigh = function () {
    return (Session.equals('background', 'white')) ?
        CONTINUOUS_HIGH_LIGHT_BG : CONTINUOUS_HIGH_DARK_BG;
};

exports.defaultContBothHigh = function () {
    return (Session.equals('background', 'white')) ?
        CONTINUOUS2_BOTH_HIGH_LIGHT_BG : CONTINUOUS2_BOTH_HIGH_DARK_BG;
};

exports.defaultCont2High1Low = function () {
    return (Session.equals('background', 'white')) ?
        CONTINUOUS2_2ND_HIGH_LIGHT_BG : CONTINUOUS2_2ND_HIGH_DARK_BG;
};

exports.defaultBinaryOff = function () {
    return (Session.equals('background', 'white')) ?
        BINARY_BOTH_OFF_LIGHT_BG : BINARY_BOTH_OFF_DARK_BG;
};

exports.defaultBinaryOn = function () {
    return (Session.equals('background', 'white')) ?
        BINARY_1ST_ON_LIGHT_BG : BINARY_1ST_ON_DARK_BG;
};

exports.defaultBinBothOn = function () {
    return (Session.equals('background', 'white')) ?
        BINARY_BOTH_ON_LIGHT_BG : BINARY_BOTH_ON_DARK_BG;
};

exports.defaultSecondBinOn = function () {
    return BINARY_2ND_ON;
};

exports.noDataColor = function () {
    return (Session.equals('background', 'white')) ?
        NO_DATA_LIGHT_BG : NO_DATA_DARK_BG;
};

exports.noAttrsColor = function () {
    return NO_ATTRS;
};

exports.have_colormap = function (colormap_name) {

    // Returns true if the given string is the name of a colormap, or false if
    // it is only a layer.
    return (colormap_name in colormaps);
};

exports.findColorCount = function (layer_name) {
    // Find the number of colors for this layer. Continuous values and
    // undefined layer_names are assigned a count of zero.
    var nColors = 0;

    if (util.is_cat_or_bin(layer_name)) {
        var colormap = colormaps[layer_name];
        if (colormap.length > 0) {

            // Categorical values
            nColors = colormap.length;
        }
    }
    return nColors;
};

exports.continuousLowColor = function(layerName) {
    // Get's the low color for a continuous attribute using the
    // appropriate colormap entry. If colormap entry is not present
    // then a default according to the background is made.
    var color,
        low = 0;
    if (colormaps[layerName]) {
        color =  colormaps[layerName][low].color.hexString();
    } else {
        colormaps[layerName] = exports.defaultContinuous();
        color =  colormaps[layerName][low].color.hexString();
    }
    return color;
};

exports.continuousHighColor = function(layerName) {
    // Get's the high color for a continuous attribute using the
    // appropriate colormap entry. If colormap entry is not present
    // then a default according to the background is made.
    var color,
        high = 1;
    if (colormaps[layerName]) {
        color =  colormaps[layerName][high].color.hexString();
    } else {
        colormaps[layerName] = exports.defaultContinuous();
        color =  colormaps[layerName][high].color.hexString();
    }
    return color;
};

exports.binaryOffColor = function(layerName) {
    // Get's the off color for a binary attribute using the
    // appropriate colormap entry. If colormap entry is not present
    // then a default according to the background is made.
    var color,
        off = 0;
    if (colormaps[layerName]) {
        color =  colormaps[layerName][off].color.hexString();
    } else {
        colormaps[layerName] = exports.defaultBinary();
        color =  colormaps[layerName][off].color.hexString();
    }
    return color;
};

exports.binaryOnColor = function(layerName) {
    // Get's the on color for a binary attribute using the
    // appropriate colormap entry. If colormap entry is not present
    // then a default according to the background is made.
    var color,
        on = 1;

    if (colormaps[layerName]) {
        color =  colormaps[layerName][on].color.hexString();
    } else {
        colormaps[layerName] = exports.defaultBinary();
        color =  colormaps[layerName][on].color.hexString();
    }
    return color;
};

exports.defaultBinary = function () {
    var defaultColormap = [
        {
            "color": new Color(exports.defaultBinaryOff()),
            "name": "0",
        },
        {
            "color": new Color(exports.defaultBinaryOn()),
            "name": "1",
        }
    ];
    return defaultColormap;
};

exports.defaultContinuous = function () {
    var defaultColormap = [
        {
            "color": new Color(exports.defaultContLow()),
            "name": "Low",
        },
        {
            "color": new Color(exports.defaultContHigh()),
            "name": "High",
        }
    ];
    return defaultColormap;
};

export function getOne (attrName) {

    // Return a shallow copy of an attr's colormap.
    if (colormaps[attrName]) {
        return colormaps[attrName].map(cat => {
            return cat
        })
    }
}

export function getCategoryCount (attrName) {

    // Get an array of category strings of a colormap.
    let count = 0
    if (attrName in colormaps) {
        count = colormaps[attrName].length
    }
    return count
}

exports.getCategoryStrings = function(attrName) {

    // Get an array of category strings of a colormap.
    if (attrName in colormaps) {
        return colormaps[attrName].map(cat => cat.name)
    }
    return []
};

exports.getCategoryString = function(attrName, catIndex) {

    // Find the string associated with this category code.
    if (attrName in colormaps && catIndex in colormaps[attrName]) {
        return colormaps[attrName][catIndex].name;
    }
    return ''
};

export function getCategoryIndex (attrName, catName) {

    // Find the index associated with this category string.
    // Start off as if we were passed and index rather than a name.
    let index = catName
    if (attrName in colormaps) {
        colormaps[attrName].forEach((cat, i) => {
            if (cat.name === catName) {
                index = i
            }
        })
    }
    return index
}

exports.updateCategoryColor = function (layerName, catName, newHexStr) {

    // Update the colormap, then redraw the hexmap
    var catI;

    // Find the category index of this color.
    _.find(colormaps[layerName], function (cat, i) {
        if (cat.name === catName) {
            catI = i;
            return true;
        }
        return false;
    });

    // Update the global colormap only saving a persistColor if it is different
    // from the new value.
    // Also, remove any persistColor if it is the same as the new value.
    var cat = colormaps[layerName][catI],
        colorHexStr = cat.color.hexString(),
        persistHexStr = cat.persistColor ?
            cat.persistColor.hexString() : null;

    if (newHexStr === colorHexStr) {
        // nothing to do here

    } else if (newHexStr === persistHexStr) {
        cat.color = cat.persistColor;
        delete cat.persistColor;

    } else if (persistHexStr === null) {
        cat.persistColor = cat.color;
        cat.color = new Color(newHexStr);

    } else {
        cat.color = new Color(newHexStr);
    }
};

exports.toStoreFormat = function (colormap) {

    // Convert one attr colormap into a form that state can save.
    var cats = _.map(colormap, function(val) {
            return val.name;

        }),
        colors = _.map(colormap, function(val) {
            return val.color.hexString();
        });
    return {cats: cats, colors: colors};
};

exports.fromStoreFormatCategories = function (cats, data) {

    // Create an operating colormap for an attribute by the given categories
    // from state, then generate colors. Return the operating colormap and
    // operating data with codes replacing the category strings.

    // Generate colors.
    var jpColormap = _.map(
        jPalette.jColormap.get('hexmap')(cats.length + 1).map,
        function (val, key) { // eslint-disable-line no-unused-vars

            // Ignore alpha, taking the default of one.
            return {r: val.r, g: val.g, b: val.b};
        }
    );

    // Remove the repeating red at the end.
    jpColormap.splice(cats.length, 1);

    // Create the operating colormap.
    var colormap = _.map(jpColormap, function(color, i) {
        return {
            name: cats[i],
            color: new Color(color), // operating color in map
        };
    });

    // Replace category string values in the data with codes.
    var vals = _.map(data, function (strVal) {
        return cats.indexOf(strVal);
    });

    return { colormap: colormap, data: _.object(_.keys(data), vals) };
};

exports.fromStoreFormat = function (colorStore) {

    // Create an operating colormap for an attribute by the given colormap
    // from store, returning the operating colormap.
    return _.map(colorStore.cats, function (cat, i) {
        return {
            name: cat,
            color: new Color(colorStore.colors[i]),
        };
    });
};

exports.received = function (parsed) {

    // Process downloaded color map information.
    for(var i = 0; i < parsed.length; i++) {
        // Get the name of the layer
        var layer_name = parsed[i][0];

        // Skip blank lines
        if(layer_name == "") {
            continue;
        }

        // This holds all the categories (name and color) by integer index
        var colormap = [];

        for (var j = 1; j < parsed[i].length; j += 3) {

            // Store each color assignment.
            // Doesn't run if there aren't any assignments, leaving an empty
            // colormap object that just forces automatic color selection.

            // This holds the index of the category
            var category_index = parseInt(parsed[i][j]);

            // The colormap gets an object with the name and color using the
            // position in the array as the index. The index given in the file
            // is ignored. Color is stored as a Color object.
            colormap[category_index] = {
                name: parsed[i][j + 1],
                color: new Color(parsed[i][j + 2]),
            };
        }

        // Store the finished color map in the global object
        colormaps[layer_name] = colormap;
    }
    rx.set('inited.colormap');
};

<|endoftext|>


<commit_before>angular.module('cesium.app.controllers', ['cesium.services'])

  .config(function($httpProvider) {
    'ngInject';

    //Enable cross domain calls
    $httpProvider.defaults.useXDomain = true;

    //Remove the header used to identify ajax call  that would prevent CORS from working
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
  })

  .config(function($stateProvider, $urlRouterProvider) {
    'ngInject';

    $stateProvider

      .state('app', {
        url: "/app",
        abstract: true,
        templateUrl: "templates/menu.html",
        controller: 'AppCtrl',
        data: {
          large: false
        }
      })

      .state('app.home', {
        url: "/home",
        views: {
          'menuContent': {
            templateUrl: "templates/home/home.html"
          }
        }
      })

      .state('app.lock', {
        cache: false,
        url: "/lock",
        views: {
          'menuContent': {
            templateUrl: "templates/common/view_passcode.html",
            controller: 'PassCodeCtrl'
          }
        }
      })
    ;

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/app/home');

  })

  .controller('AppCtrl', AppController)

  .controller('PluginExtensionPointCtrl', PluginExtensionPointController)

  .controller('EmptyModalCtrl', EmptyModalController)

  .controller('AboutCtrl', AboutController)

  .controller('PassCodeCtrl', PassCodeController)

;

/**
 * Useful for modal with no controller (see Modal service)
 */
function EmptyModalController($scope, parameters) {

}

/**
 * Useful controller that could be reuse in plugin, using $scope.extensionPoint for condition rendered in templates
 */
function PluginExtensionPointController($scope, PluginService) {
  'ngInject';
  $scope.extensionPoint = PluginService.extensions.points.current.get();
}

/**
 * Abstract controller (inherited by other controllers)
 */
function AppController($scope, $rootScope, $state, $ionicSideMenuDelegate, $q, $timeout, $ionicHistory, $controller,
                       UIUtils, BMA, csWallet, Device, Modals, csSettings, csConfig
  ) {
  'ngInject';

  $scope.search = {};
  $scope.login = csWallet.isLogin();

  $scope.showHome = function() {
    $ionicHistory.nextViewOptions({
      historyRoot: true
    });
    return $state.go('app.home')
      .then(UIUtils.loading.hide);
  };

  ////////////////////////////////////////
  // Device Methods
  ////////////////////////////////////////

  $scope.scanQrCodeAndGo = function() {
    if (!Device.enable) {
      return;
    }
    Device.camera.scan()
    .then(function(uri) {
      if (!uri) {
        return;
      }
      BMA.uri.parse(uri)
      .then(function(result){
        // If pubkey
        if (result && result.pubkey) {
          $state.go('app.wot_identity', {
            pubkey: result.pubkey,
            node: result.host ? result.host: null}
          );
        }
        else {
          UIUtils.alert.error(result, 'ERROR.SCAN_UNKNOWN_FORMAT');
        }
      })
      .catch(UIUtils.onError('ERROR.SCAN_UNKNOWN_FORMAT'));
    })
    .catch(UIUtils.onError('ERROR.SCAN_FAILED'));
  };

  ////////////////////////////////////////
  // Show Help tour
  ////////////////////////////////////////

  $scope.createHelptipScope = function(isTour) {
    if (!isTour && ($rootScope.tour || !$rootScope.settings.helptip.enable || UIUtils.screen.isSmall())) {
      return; // avoid other helptip to be launched (e.g. csWallet)
    }
    // Create a new scope for the tour controller
    var helptipScope = $scope.$new();
    $controller('HelpTipCtrl', { '$scope': helptipScope});
    return helptipScope;
  };

  $scope.startHelpTour = function(skipClearCache) {
    $rootScope.tour = true; // to avoid other helptip to be launched (e.g. csWallet)

    //
    if (!skipClearCache) {
      $ionicHistory.clearHistory();
      return $ionicHistory.clearCache()
        .then(function() {
          $scope.startHelpTour(true/*continue*/);
        });
    }

    var helptipScope = $scope.createHelptipScope(true);
    return helptipScope.startHelpTour()
    .then(function() {
      helptipScope.$destroy();
      delete $rootScope.tour;
    })
    .catch(function(err){
      delete $rootScope.tour;
    });
  };

  ////////////////////////////////////////
  // Login & wallet
  ////////////////////////////////////////

  $scope.isLogin = function() {
    return $scope.login;
  };

  $scope.showProfilePopover = function(event) {
    return UIUtils.popover.show(event, {
      templateUrl :'templates/common/popover_profile.html',
      scope: $scope,
      autoremove: true,
      afterShow: function(popover) {
        $scope.profilePopover = popover;
        $timeout(function() {
          UIUtils.ink({selector: '#profile-popover .ink, #profile-popover .ink-dark'});
        }, 100);
      }
    });
  };

  $scope.closeProfilePopover = function() {
    if ($scope.profilePopover && $scope.profilePopover.isShown()) {
      $timeout(function(){$scope.profilePopover.hide();});
    }
  };

  // Load wallet data (after login)
  $scope.loadWalletData = function(options) {
    return csWallet.loadData(options)
      /*.catch(UIUtils.onError('ERROR.LOAD_WALLET_DATA_ERROR'))*/

      .then(function(walletData) {
        // Warn if wallet has been never used - see #167
        var showAlert = !csConfig.initPhase && csWallet.isNeverUsed() && (!csSettings.data.wallet || csSettings.data.wallet.alertIfUnusedWallet);
        if (!showAlert) return walletData;
        return UIUtils.loading.hide()
          .then(function(){
            return UIUtils.alert.confirm('CONFIRM.LOGIN_UNUSED_WALLET', 'CONFIRM.LOGIN_UNUSED_WALLET_TITLE',
              {
                okText: 'COMMON.BTN_CONTINUE'
              });
          })
          .then(function(confirm) {
            if (confirm) return walletData;
            return csWallet.logout();
          });
      })

      .then(function(walletData) {
        if (walletData) {
          $rootScope.walletData = walletData;
          return walletData;
        }
        else { // cancel login
          throw 'CANCELLED';
        }
      });
  };

  // Login and load wallet
  $scope.loadWallet = function(options) {
    if (!csWallet.isLogin()) {
      return $scope.showLoginModal()
        .then(function (walletData) {
          if (walletData) {
            $rootScope.viewFirstEnter = false;
            // Force full load, even if min data asked
            // Because user can wait when just filled login (by modal)
            if (options && options.minData) options.minData = false;
            return $scope.loadWalletData(options);
          }
          else { // failed to login
            throw 'CANCELLED';
          }
        });
    }
    else if (!csWallet.data.loaded) {
      return $scope.loadWalletData(options);
    }
    else {
      return $q.when(csWallet.data);
    }
  };

  // Login and go to a state (or wallet if not)
  $scope.loginAndGo = function(state) {
    $scope.closeProfilePopover();

    state = state || 'app.view_wallet';

    if (!csWallet.isLogin()) {
      return $scope.showLoginModal()
        .then(function(walletData){
          if (walletData) {
            return $state.go(state ? state : 'app.view_wallet')
              .then(UIUtils.loading.hide);
          }
        });
    }
    else {
      return $state.go(state);
    }
  };

  // Show login modal
  $scope.showLoginModal = function() {
    return Modals.showLogin()
    .then(function(formData){
      if (!formData) return;
      var rememberMeChanged = (csSettings.data.rememberMe !== formData.rememberMe);
      if (rememberMeChanged) {
        csSettings.data.rememberMe = formData.rememberMe;
        csSettings.data.useLocalStorage = csSettings.data.rememberMe ? true : csSettings.data.useLocalStorage;
        csSettings.store();
      }
      return csWallet.login(formData.username, formData.password);
    })
    .then(function(walletData){
      if (walletData) {
        $rootScope.walletData = walletData;
      }
      return walletData;
    })
    .catch(UIUtils.onError('ERROR.CRYPTO_UNKNOWN_ERROR'));
  };

  // Logout
  $scope.logout = function(options) {
    options = options || {};
    if (!options.force && $scope.profilePopover) {
      // Make the popover if really closed, to avoid UI refresh on popover buttons
      return $scope.profilePopover.hide()
        .then(function(){
          options.force = true;
          return $scope.logout(options);
        });
    }
    if (options.askConfirm) {
      return UIUtils.alert.confirm('CONFIRM.LOGOUT')
        .then(function(confirm) {
          if (confirm) {
            options.askConfirm=false;
            return $scope.logout(options);
          }
        });
    }

    UIUtils.loading.show();
    return csWallet.logout()
      .then(function() {
        $ionicSideMenuDelegate.toggleLeft();
        $ionicHistory.clearHistory();

        return $ionicHistory.clearCache()
          .then(function() {
            return $scope.showHome();
          });
      })
      .catch(UIUtils.onError());
  };

  // add listener on wallet event
  csWallet.api.data.on.login($scope, function(walletData, deferred) {
    $scope.login = true;
    return deferred ? deferred.resolve() : $q.when();
  });
  csWallet.api.data.on.logout($scope, function() {
    $scope.login = false;
  });

  // If connected and same pubkey
  $scope.isUserPubkey = function(pubkey) {
    return csWallet.isUserPubkey(pubkey);
  };

  ////////////////////////////////////////
  // Useful modals
  ////////////////////////////////////////

  // Open transfer modal
  $scope.showTransferModal = function(parameters) {
    return $scope.loadWallet()
    .then(function(walletData){
      UIUtils.loading.hide();
      if (walletData) {
        return Modals.showTransfer(parameters);
      }
    })
    .then(function(result){
      if (result){
        UIUtils.alert.info('INFO.TRANSFER_SENT');
        $state.go('app.view_wallet');
      }
    });
  };

  $scope.showAboutModal = function() {
    return Modals.showAbout();
  };

  $scope.showJoinModal = function() {
    $scope.closeProfilePopover();
    return Modals.showJoin();
  };

  $scope.showSettings = function() {
    $scope.closeProfilePopover();
    return $state.go('app.settings');
  };

  $scope.showHelpModal = function(parameters) {
    return Modals.showHelp(parameters);
  };

  ////////////////////////////////////////
  // Layout Methods
  ////////////////////////////////////////
  $scope.showFab = function(id, timeout) {
    UIUtils.motion.toggleOn({selector: '#'+id + '.button-fab'}, timeout);
  };

  $scope.hideFab = function(id, timeout) {
    UIUtils.motion.toggleOff({selector: '#'+id + '.button-fab'}, timeout);
  };

}

function AboutController($scope, csConfig) {
  'ngInject';
  $scope.config = csConfig;
}

function PassCodeController($scope) {
  'ngInject';

}
<commit_msg>Make sure to protect login modal, if HTTPS enable - fix #340<commit_after>angular.module('cesium.app.controllers', ['cesium.services'])

  .config(function($httpProvider) {
    'ngInject';

    //Enable cross domain calls
    $httpProvider.defaults.useXDomain = true;

    //Remove the header used to identify ajax call  that would prevent CORS from working
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
  })

  .config(function($stateProvider, $urlRouterProvider) {
    'ngInject';

    $stateProvider

      .state('app', {
        url: "/app",
        abstract: true,
        templateUrl: "templates/menu.html",
        controller: 'AppCtrl',
        data: {
          large: false
        }
      })

      .state('app.home', {
        url: "/home",
        views: {
          'menuContent': {
            templateUrl: "templates/home/home.html"
          }
        }
      })

      .state('app.lock', {
        cache: false,
        url: "/lock",
        views: {
          'menuContent': {
            templateUrl: "templates/common/view_passcode.html",
            controller: 'PassCodeCtrl'
          }
        }
      })
    ;

    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/app/home');

  })

  .controller('AppCtrl', AppController)

  .controller('PluginExtensionPointCtrl', PluginExtensionPointController)

  .controller('EmptyModalCtrl', EmptyModalController)

  .controller('AboutCtrl', AboutController)

  .controller('PassCodeCtrl', PassCodeController)

;

/**
 * Useful for modal with no controller (see Modal service)
 */
function EmptyModalController($scope, parameters) {

}

/**
 * Useful controller that could be reuse in plugin, using $scope.extensionPoint for condition rendered in templates
 */
function PluginExtensionPointController($scope, PluginService) {
  'ngInject';
  $scope.extensionPoint = PluginService.extensions.points.current.get();
}

/**
 * Abstract controller (inherited by other controllers)
 */
function AppController($scope, $rootScope, $state, $ionicSideMenuDelegate, $q, $timeout, $ionicHistory, $controller, $window,
                       UIUtils, BMA, csWallet, Device, Modals, csSettings, csConfig
  ) {
  'ngInject';

  $scope.search = {};
  $scope.login = csWallet.isLogin();

  $scope.showHome = function() {
    $ionicHistory.nextViewOptions({
      historyRoot: true
    });
    return $state.go('app.home')
      .then(UIUtils.loading.hide);
  };

  ////////////////////////////////////////
  // Device Methods
  ////////////////////////////////////////

  $scope.scanQrCodeAndGo = function() {
    if (!Device.enable) {
      return;
    }
    Device.camera.scan()
    .then(function(uri) {
      if (!uri) {
        return;
      }
      BMA.uri.parse(uri)
      .then(function(result){
        // If pubkey
        if (result && result.pubkey) {
          $state.go('app.wot_identity', {
            pubkey: result.pubkey,
            node: result.host ? result.host: null}
          );
        }
        else {
          UIUtils.alert.error(result, 'ERROR.SCAN_UNKNOWN_FORMAT');
        }
      })
      .catch(UIUtils.onError('ERROR.SCAN_UNKNOWN_FORMAT'));
    })
    .catch(UIUtils.onError('ERROR.SCAN_FAILED'));
  };

  ////////////////////////////////////////
  // Show Help tour
  ////////////////////////////////////////

  $scope.createHelptipScope = function(isTour) {
    if (!isTour && ($rootScope.tour || !$rootScope.settings.helptip.enable || UIUtils.screen.isSmall())) {
      return; // avoid other helptip to be launched (e.g. csWallet)
    }
    // Create a new scope for the tour controller
    var helptipScope = $scope.$new();
    $controller('HelpTipCtrl', { '$scope': helptipScope});
    return helptipScope;
  };

  $scope.startHelpTour = function(skipClearCache) {
    $rootScope.tour = true; // to avoid other helptip to be launched (e.g. csWallet)

    //
    if (!skipClearCache) {
      $ionicHistory.clearHistory();
      return $ionicHistory.clearCache()
        .then(function() {
          $scope.startHelpTour(true/*continue*/);
        });
    }

    var helptipScope = $scope.createHelptipScope(true);
    return helptipScope.startHelpTour()
    .then(function() {
      helptipScope.$destroy();
      delete $rootScope.tour;
    })
    .catch(function(err){
      delete $rootScope.tour;
    });
  };

  ////////////////////////////////////////
  // Login & wallet
  ////////////////////////////////////////

  $scope.isLogin = function() {
    return $scope.login;
  };

  $scope.showProfilePopover = function(event) {
    return UIUtils.popover.show(event, {
      templateUrl :'templates/common/popover_profile.html',
      scope: $scope,
      autoremove: true,
      afterShow: function(popover) {
        $scope.profilePopover = popover;
        $timeout(function() {
          UIUtils.ink({selector: '#profile-popover .ink, #profile-popover .ink-dark'});
        }, 100);
      }
    });
  };

  $scope.closeProfilePopover = function() {
    if ($scope.profilePopover && $scope.profilePopover.isShown()) {
      $timeout(function(){$scope.profilePopover.hide();});
    }
  };

  // Load wallet data (after login)
  $scope.loadWalletData = function(options) {
    return csWallet.loadData(options)
      /*.catch(UIUtils.onError('ERROR.LOAD_WALLET_DATA_ERROR'))*/

      .then(function(walletData) {
        // Warn if wallet has been never used - see #167
        var showAlert = !csConfig.initPhase && csWallet.isNeverUsed() && (!csSettings.data.wallet || csSettings.data.wallet.alertIfUnusedWallet);
        if (!showAlert) return walletData;
        return UIUtils.loading.hide()
          .then(function(){
            return UIUtils.alert.confirm('CONFIRM.LOGIN_UNUSED_WALLET', 'CONFIRM.LOGIN_UNUSED_WALLET_TITLE',
              {
                okText: 'COMMON.BTN_CONTINUE'
              });
          })
          .then(function(confirm) {
            if (confirm) return walletData;
            return csWallet.logout();
          });
      })

      .then(function(walletData) {
        if (walletData) {
          $rootScope.walletData = walletData;
          return walletData;
        }
        else { // cancel login
          throw 'CANCELLED';
        }
      });
  };

  // Login and load wallet
  $scope.loadWallet = function(options) {
    if (!csWallet.isLogin()) {
      return $scope.showLoginModal()
        .then(function (walletData) {
          if (walletData) {
            $rootScope.viewFirstEnter = false;
            // Force full load, even if min data asked
            // Because user can wait when just filled login (by modal)
            if (options && options.minData) options.minData = false;
            return $scope.loadWalletData(options);
          }
          else { // failed to login
            throw 'CANCELLED';
          }
        });
    }
    else if (!csWallet.data.loaded) {
      return $scope.loadWalletData(options);
    }
    else {
      return $q.when(csWallet.data);
    }
  };

  // Login and go to a state (or wallet if not)
  $scope.loginAndGo = function(state) {
    $scope.closeProfilePopover();

    state = state || 'app.view_wallet';

    if (!csWallet.isLogin()) {

      // Make sure to protect login modal, if HTTPS enable - fix #340
      if (csConfig.httpsMode && $window.location && $window.location.protocol !== 'https:') {
        var href = $window.location.href;
        var hashIndex = href.indexOf('#');
        var rootPath = (hashIndex != -1) ? href.substr(0, hashIndex) : href;
        rootPath = 'https' + rootPath.substr(4);
        href = rootPath + $state.href(state);
        if (csConfig.httpsModeDebug) {
          console.debug('[httpsMode] --- Should redirect to: ' + href);
        }
        else {
          $window.location.href = href;
        }
        return;
      }

      return $scope.showLoginModal()
        .then(function(walletData){
          if (walletData) {
            return $state.go(state ? state : 'app.view_wallet')
              .then(UIUtils.loading.hide);
          }
        });
    }
    else {
      return $state.go(state);
    }
  };

  // Show login modal
  $scope.showLoginModal = function() {
    return Modals.showLogin()
    .then(function(formData){
      if (!formData) return;
      var rememberMeChanged = (csSettings.data.rememberMe !== formData.rememberMe);
      if (rememberMeChanged) {
        csSettings.data.rememberMe = formData.rememberMe;
        csSettings.data.useLocalStorage = csSettings.data.rememberMe ? true : csSettings.data.useLocalStorage;
        csSettings.store();
      }
      return csWallet.login(formData.username, formData.password);
    })
    .then(function(walletData){
      if (walletData) {
        $rootScope.walletData = walletData;
      }
      return walletData;
    })
    .catch(UIUtils.onError('ERROR.CRYPTO_UNKNOWN_ERROR'));
  };

  // Logout
  $scope.logout = function(options) {
    options = options || {};
    if (!options.force && $scope.profilePopover) {
      // Make the popover if really closed, to avoid UI refresh on popover buttons
      return $scope.profilePopover.hide()
        .then(function(){
          options.force = true;
          return $scope.logout(options);
        });
    }
    if (options.askConfirm) {
      return UIUtils.alert.confirm('CONFIRM.LOGOUT')
        .then(function(confirm) {
          if (confirm) {
            options.askConfirm=false;
            return $scope.logout(options);
          }
        });
    }

    UIUtils.loading.show();
    return csWallet.logout()
      .then(function() {
        $ionicSideMenuDelegate.toggleLeft();
        $ionicHistory.clearHistory();

        return $ionicHistory.clearCache()
          .then(function() {
            return $scope.showHome();
          });
      })
      .catch(UIUtils.onError());
  };

  // add listener on wallet event
  csWallet.api.data.on.login($scope, function(walletData, deferred) {
    $scope.login = true;
    return deferred ? deferred.resolve() : $q.when();
  });
  csWallet.api.data.on.logout($scope, function() {
    $scope.login = false;
  });

  // If connected and same pubkey
  $scope.isUserPubkey = function(pubkey) {
    return csWallet.isUserPubkey(pubkey);
  };

  ////////////////////////////////////////
  // Useful modals
  ////////////////////////////////////////

  // Open transfer modal
  $scope.showTransferModal = function(parameters) {
    return $scope.loadWallet()
    .then(function(walletData){
      UIUtils.loading.hide();
      if (walletData) {
        return Modals.showTransfer(parameters);
      }
    })
    .then(function(result){
      if (result){
        UIUtils.alert.info('INFO.TRANSFER_SENT');
        $state.go('app.view_wallet');
      }
    });
  };

  $scope.showAboutModal = function() {
    return Modals.showAbout();
  };

  $scope.showJoinModal = function() {
    $scope.closeProfilePopover();
    return Modals.showJoin();
  };

  $scope.showSettings = function() {
    $scope.closeProfilePopover();
    return $state.go('app.settings');
  };

  $scope.showHelpModal = function(parameters) {
    return Modals.showHelp(parameters);
  };

  ////////////////////////////////////////
  // Layout Methods
  ////////////////////////////////////////
  $scope.showFab = function(id, timeout) {
    UIUtils.motion.toggleOn({selector: '#'+id + '.button-fab'}, timeout);
  };

  $scope.hideFab = function(id, timeout) {
    UIUtils.motion.toggleOff({selector: '#'+id + '.button-fab'}, timeout);
  };

}

function AboutController($scope, csConfig) {
  'ngInject';
  $scope.config = csConfig;
}

function PassCodeController($scope) {
  'ngInject';

}
<|endoftext|>


<commit_before>var assert = require('assert')
var pf = require('./index')

describe('waterfall', function () {
    it('should pass arguments', function (done) {
        pf.waterfall(
            function (x, callback) { callback(null, x / 2, x * 2) },
            function (y, z, callback) { callback(null, y + z); }
        )(4, function (err, res) {
            assert.equal(res, 10)
            done()
        })
    })

    it('should pass error', function (done) {
        pf.waterfall(
            function (callback) { callback('an error') },
            function (callback) { callback(null); }
        )(function (err) {
            assert.equal(err, 'an error')
            done()
        })
    })

    it('should work concurrently', function (done) {
        var func = pf.waterfall(function (callback) {
            setTimeout(callback, 10);
        })
        var calls = [];

        func(function () { calls.push(1) })
        func(function () { calls.push(2) })
        setTimeout(function () {
            assert.deepEqual(calls, [1, 2]);
            done();
        }, 10);
    })
})

describe('serial', function () {
    it('should be serial', function (done) {
        var calls = [];

        pf.serial(
            function (callback) { setTimeout(function () {calls.push(1); callback(null)}, 20) },
            function (callback) { setTimeout(function () {calls.push(2); callback(null)}, 10) }
        )(function (err) {
            assert.deepEqual(calls, [1, 2])
            done()
        })
    })

    it('should pass results', function (done) {
        pf.serial(
            function (callback) { callback(null, 1, 2) },
            function (callback) { callback(null, 3) },
            function (callback) { callback(null) }
        )(function (err, res) {
            assert.deepEqual(res, [[1, 2], 3, undefined])
            done()
        })
    })

    it('should pass error', function (done) {
        pf.serial(
            function (callback) { callback('an error') },
            function (callback) { callback(null); }
        )(function (err) {
            assert.equal(err, 'an error')
            done()
        })
    })
})

describe('parallel', function () {
    it('should be parallel', function (done) {
        var calls = [];

        pf.parallel(
            function (callback) { setTimeout(function () {calls.push(1); callback(null)}, 20) },
            function (callback) { setTimeout(function () {calls.push(2); callback(null)}, 10) }
        )(function (err) {
            assert.deepEqual(calls, [2, 1])
            done()
        })
    })

    it('should pass results', function (done) {
        pf.parallel(
            function (callback) { callback(null, 1, 2) },
            function (callback) { callback(null, 3) },
            function (callback) { callback(null) }
        )(function (err, res) {
            assert.deepEqual(res, [[1, 2], 3, undefined])
            done()
        })
    })

    it('should pass error', function (done) {
        pf.parallel(
            function (callback) { callback('an error') },
            function (callback) { callback(null); }
        )(function (err) {
            assert.equal(err, 'an error')
            done()
        })
    })
})

describe('manual', function () {
    it('should waterfall', function (done) {
        pf.manual({
            start: function (x, next) { next.sum(null, x / 2, x * 2) },
            sum: function (y, z, next) { next.end(null, y + z); }
        })(4, function (err, res) {
            assert.equal(res, 10)
            done()
        })
    })

    it('should pass error', function (done) {
        pf.manual({
            start: function (next) { next.other('an error') },
            other: function (next) { next.end(null); }
        })(function (err) {
            assert.equal(err, 'an error')
            done()
        })
    })
})

describe('auto', function () {
    it('should waterfall', function (done) {
        pf.auto({
            start: function (callback) { callback(null, 4) },
            divmul: ['start', function (x, callback) { callback(null, x / 2, x * 2) }],
            sum: ['divmul', function (yz, callback) { callback(null, yz[0] + yz[1]); }]
        })(function (err, res) {
            assert.deepEqual(res, {start: 4, divmul: [2, 8], sum: 10})
            done()
        })
    })

    it('should pass error', function (done) {
        pf.auto({
            auto: function (callback) { callback('an error') },
            other: function (callback) { callback(null); }
        })(function (err) {
            assert.equal(err, 'an error')
            done()
        })
    })

    it('should try parallel', function (done) {
        var calls = [];

        pf.auto({
            1: function (callback) { setTimeout(function () {calls.push(1); callback(null)}, 20) },
            2: function (callback) { setTimeout(function () {calls.push(2); callback(null)}, 10) },
            3: ['1', '2', function (_x, _y, callback) {
                calls.push(3)
                callback(null)
            }]
        })(function (err) {
            assert.deepEqual(calls, [2, 1, 3])
            done()
        })
    })
})

describe('retry', function () {
    function failing(n, func) {
        var i = 0;

        return function () {
            var callback = arguments[arguments.length-1];

            i++;
            if (i <= n) callback("Error " + i)
            else func.apply(null, arguments)
        }
    }
    function noop(callback) {
        callback(null);
    }

    it('should retry', function (done) {
        pf.retry(failing(2, noop))(function (err) {
            assert.ifError(err)
            done()
        })
    })

    it('should eventually fail', function (done) {
        pf.retry(2, failing(2, noop))(function (err) {
            assert.equal(err, "Error 2")
            done()
        })
    })

    it('should preserve interface', function (done) {
        function add(x, y, callback) {
            callback(null, x + y);
        }

        pf.retry(failing(2, add))(1, 2, function (err, res) {
            assert.equal(res, 3)
            done()
        })
    })

    describe('timeout', function () {
        it('should take constant', function (done) {
            _time(pf.retry({timeout: 10}, failing(2, noop)))(function (delay) {
                assert(delay >= 20)
                done()
            })
        })

        it('should respect factor', function (done) {
            _time(pf.retry({timeout: 10, factor: 2}, failing(2, noop)))(function (delay) {
                assert(delay >= 30)
                done()
            })
        })

        it('should take function', function (done) {
            function timeout(attempt) {
                return 10 * Math.pow(2, attempt - 1)
            }

            var start = (new Date()).getTime();
            _time(pf.retry({timeout: timeout}, failing(2, noop)))(function (delay) {
                assert(delay >= 30)
                done()
            })
        })
    })

describe('limit', function () {
    it('should limit', function (done) {
        var running = 0, max = 0;
        var limited = pf.limit(2, function (callback) {
            running++;
            if (running > max) max = running;
            setTimeout(function () { running--; callback(null) }, 10)
        })

        pf.parallel(limited, limited, limited)(function (err, results) {
            assert.equal(max, 2)
            done()
        })
    })

    it('should limit by', function (done) {
        var running = 0, max = 0;
        var limited = pf.limit({limit: 2, by: function (x) { return x }}, function (x, callback) {
            running++;
            if (running > max) max = running;
            setTimeout(function () { running--; callback(null) }, 10)
        })
        var limited1 = limited.bind(null, 1);
        var limited2 = limited.bind(null, 2);

        pf.parallel(limited1, limited1, limited1, limited2)(function (err, results) {
            assert.equal(max, 3)
            done()
        })
    })

    it('should pass error', function (done) {
        pf.limit(2, function (callback) { callback('an error') })(function (err) {
            assert.equal(err, "an error")
            done()
        })
    })

    it('should preserve interface', function (done) {
        function add(x, y, callback) {
            callback(null, x + y);
        }

        pf.limit(2, add)(1, 2, function (err, res) {
            assert.equal(res, 3)
            done()
        })
    })
})

function _time(func) {
    return function () {
        var args = [].slice.call(arguments);
        var callback = args.pop();

        var start = (new Date()).getTime();
        func.apply(null, args.concat([function () {
            var end = (new Date()).getTime();
            callback(end - start);
        }]))
    }
}
<commit_msg>Fix tests<commit_after>var assert = require('assert')
var pf = require('./index')

describe('waterfall', function () {
    it('should pass arguments', function (done) {
        pf.waterfall(
            function (x, callback) { callback(null, x / 2, x * 2) },
            function (y, z, callback) { callback(null, y + z); }
        )(4, function (err, res) {
            assert.equal(res, 10)
            done()
        })
    })

    it('should pass error', function (done) {
        pf.waterfall(
            function (callback) { callback('an error') },
            function (callback) { callback(null); }
        )(function (err) {
            assert.equal(err, 'an error')
            done()
        })
    })

    it('should work concurrently', function (done) {
        var func = pf.waterfall(function (callback) {
            setTimeout(callback, 10);
        })
        var calls = [];

        func(function () { calls.push(1) })
        func(function () { calls.push(2) })
        setTimeout(function () {
            assert.deepEqual(calls, [1, 2]);
            done();
        }, 10);
    })
})

describe('serial', function () {
    it('should be serial', function (done) {
        var calls = [];

        pf.serial(
            function (callback) { setTimeout(function () {calls.push(1); callback(null)}, 20) },
            function (callback) { setTimeout(function () {calls.push(2); callback(null)}, 10) }
        )(function (err) {
            assert.deepEqual(calls, [1, 2])
            done()
        })
    })

    it('should pass results', function (done) {
        pf.serial(
            function (callback) { callback(null, 1, 2) },
            function (callback) { callback(null, 3) },
            function (callback) { callback(null) }
        )(function (err, res) {
            assert.deepEqual(res, [[1, 2], 3, undefined])
            done()
        })
    })

    it('should pass error', function (done) {
        pf.serial(
            function (callback) { callback('an error') },
            function (callback) { callback(null); }
        )(function (err) {
            assert.equal(err, 'an error')
            done()
        })
    })
})

describe('parallel', function () {
    it('should be parallel', function (done) {
        var calls = [];

        pf.parallel(
            function (callback) { setTimeout(function () {calls.push(1); callback(null)}, 20) },
            function (callback) { setTimeout(function () {calls.push(2); callback(null)}, 10) }
        )(function (err) {
            assert.deepEqual(calls, [2, 1])
            done()
        })
    })

    it('should pass results', function (done) {
        pf.parallel(
            function (callback) { callback(null, 1, 2) },
            function (callback) { callback(null, 3) },
            function (callback) { callback(null) }
        )(function (err, res) {
            assert.deepEqual(res, [[1, 2], 3, undefined])
            done()
        })
    })

    it('should pass error', function (done) {
        pf.parallel(
            function (callback) { callback('an error') },
            function (callback) { callback(null); }
        )(function (err) {
            assert.equal(err, 'an error')
            done()
        })
    })
})

describe('manual', function () {
    it('should waterfall', function (done) {
        pf.manual({
            start: function (x, next) { next.sum(null, x / 2, x * 2) },
            sum: function (y, z, next) { next.end(null, y + z); }
        })(4, function (err, res) {
            assert.equal(res, 10)
            done()
        })
    })

    it('should pass error', function (done) {
        pf.manual({
            start: function (next) { next.other('an error') },
            other: function (next) { next.end(null); }
        })(function (err) {
            assert.equal(err, 'an error')
            done()
        })
    })
})

describe('auto', function () {
    it('should waterfall', function (done) {
        pf.auto({
            start: function (callback) { callback(null, 4) },
            divmul: ['start', function (x, callback) { callback(null, x / 2, x * 2) }],
            sum: ['divmul', function (yz, callback) { callback(null, yz[0] + yz[1]); }]
        })(function (err, res) {
            assert.deepEqual(res, {start: 4, divmul: [2, 8], sum: 10})
            done()
        })
    })

    it('should pass error', function (done) {
        pf.auto({
            auto: function (callback) { callback('an error') },
            other: function (callback) { callback(null); }
        })(function (err) {
            assert.equal(err, 'an error')
            done()
        })
    })

    it('should try parallel', function (done) {
        var calls = [];

        pf.auto({
            1: function (callback) { setTimeout(function () {calls.push(1); callback(null)}, 20) },
            2: function (callback) { setTimeout(function () {calls.push(2); callback(null)}, 10) },
            3: ['1', '2', function (_x, _y, callback) {
                calls.push(3)
                callback(null)
            }]
        })(function (err) {
            assert.deepEqual(calls, [2, 1, 3])
            done()
        })
    })
})

describe('retry', function () {
    function failing(n, func) {
        var i = 0;

        return function () {
            var callback = arguments[arguments.length-1];

            i++;
            if (i <= n) callback("Error " + i)
            else func.apply(null, arguments)
        }
    }
    function noop(callback) {
        callback(null);
    }

    it('should retry', function (done) {
        pf.retry(failing(2, noop))(function (err) {
            assert.ifError(err)
            done()
        })
    })

    it('should eventually fail', function (done) {
        pf.retry(2, failing(2, noop))(function (err) {
            assert.equal(err, "Error 2")
            done()
        })
    })

    it('should preserve interface', function (done) {
        function add(x, y, callback) {
            callback(null, x + y);
        }

        pf.retry(failing(2, add))(1, 2, function (err, res) {
            assert.equal(res, 3)
            done()
        })
    })

    describe('timeout', function () {
        it('should take constant', function (done) {
            _time(pf.retry({timeout: 10}, failing(2, noop)))(function (delay) {
                assert(delay >= 20)
                done()
            })
        })

        it('should respect factor', function (done) {
            _time(pf.retry({timeout: 10, factor: 2}, failing(2, noop)))(function (delay) {
                assert(delay >= 30)
                done()
            })
        })

        it('should take function', function (done) {
            function timeout(attempt) {
                return 10 * Math.pow(2, attempt - 1)
            }

            var start = (new Date()).getTime();
            _time(pf.retry({timeout: timeout}, failing(2, noop)))(function (delay) {
                assert(delay >= 30)
                done()
            })
        })
    })

})

describe('limit', function () {
    it('should limit', function (done) {
        var running = 0, max = 0;
        var limited = pf.limit(2, function (callback) {
            running++;
            if (running > max) max = running;
            setTimeout(function () { running--; callback(null) }, 10)
        })

        pf.parallel(limited, limited, limited)(function (err, results) {
            assert.equal(max, 2)
            done()
        })
    })

    it('should limit by', function (done) {
        var running = 0, max = 0;
        var limited = pf.limit({limit: 2, by: function (x) { return x }}, function (x, callback) {
            running++;
            if (running > max) max = running;
            setTimeout(function () { running--; callback(null) }, 10)
        })
        var limited1 = limited.bind(null, 1);
        var limited2 = limited.bind(null, 2);

        pf.parallel(limited1, limited1, limited1, limited2)(function (err, results) {
            assert.equal(max, 3)
            done()
        })
    })

    it('should pass error', function (done) {
        pf.limit(2, function (callback) { callback('an error') })(function (err) {
            assert.equal(err, "an error")
            done()
        })
    })

    it('should preserve interface', function (done) {
        function add(x, y, callback) {
            callback(null, x + y);
        }

        pf.limit(2, add)(1, 2, function (err, res) {
            assert.equal(res, 3)
            done()
        })
    })
})

function _time(func) {
    return function () {
        var args = [].slice.call(arguments);
        var callback = args.pop();

        var start = (new Date()).getTime();
        func.apply(null, args.concat([function () {
            var end = (new Date()).getTime();
            callback(end - start);
        }]))
    }
}
<|endoftext|>


<commit_before>var utyls = require('./');
var assert=require('chai').assert;

 var utobj=new utyls();

 //Tests for isChar
//TODO: Add More Tests eg: Create a custom datatype and try to pass it.
describe('Tests for isChar->',function(){

it('Passes Integer',function(){

   assert.equal(utobj.isChar(7),false,"");

});

it('Passes Char',function(){

   assert.equal(utobj.isChar('g'),true,"");

});

it('Passes String',function(){

   assert.equal(utobj.isChar('string'),false,"")

});

it('Passes float/double',function(){

   assert.equal(utobj.isChar(5.67),false,"");

});
});

//Tests for isInteger

describe("Tests for isInteger->",function(){

   it("Passes char",function(){

      assert.equal(utobj.isInteger('7'),false,"");

   });

   it("Passes String",function(){

      assert.equal(utobj.isInteger("787"),false,"");

   });

   it("Passes double/float",function(){

      assert.equal(utobj.isInteger(6.78),false,"");

   });

   it("Passes Integer",function(){

      assert.equal(utobj.isInteger(7),true,"");

   });

});

//TODO: Need More Tests to be written

describe("Tests for leftpad",function(){

   it("Without default arguement",function(){

       assert.equal(utobj.leftpad("7",3),"**7","");
   });

   it("With default arguement",function(){

       assert.equal(utobj.leftpad("7",3,"0"),"007","");

   });

   it("Passes required length less than string length",function(){

      assert.equal(utobj.leftpad("788",2,"6"),"788","");

   });

   it("Passes a string instead of padding character",()=>{

      assert.equal(utobj.leftpad("776",10,"607"),undefined,"") ;
   });

   it("Passes negative length as required  length",()=>{

      assert.equal(utobj.leftpad("gha",-9),"gha","");

   });

   it("Passes empty string ",()=>{

      assert.equal(utobj.leftpad("",10),"**********","");
   });

   it("String and required length",()=>{

      assert.equal(utobj.leftpad("ThisisTextoflength50",50),"******************************ThisisTextoflength50","");
   });

});

<commit_msg>Added More Unit Tests for leftpad<commit_after>var utyls = require('./');
var assert=require('chai').assert;

 var utobj=new utyls();

 //Tests for isChar
//TODO: Add More Tests eg: Create a custom datatype and try to pass it.
describe('Tests for isChar->',function(){

it('Passes Integer',function(){

   assert.equal(utobj.isChar(7),false,"");

});

it('Passes Char',function(){

   assert.equal(utobj.isChar('g'),true,"");

});

it('Passes String',function(){

   assert.equal(utobj.isChar('string'),false,"")

});

it('Passes float/double',function(){

   assert.equal(utobj.isChar(5.67),false,"");

});
});

//Tests for isInteger

describe("Tests for isInteger->",function(){

   it("Passes char",function(){

      assert.equal(utobj.isInteger('7'),false,"");

   });

   it("Passes String",function(){

      assert.equal(utobj.isInteger("787"),false,"");

   });

   it("Passes double/float",function(){

      assert.equal(utobj.isInteger(6.78),false,"");

   });

   it("Passes Integer",function(){

      assert.equal(utobj.isInteger(7),true,"");

   });

});

//TODO: Need More Tests to be written

describe("Tests for leftpad",function(){

   it("Without default arguement",function(){

       assert.equal(utobj.leftpad("7",3),"**7","");
   });

   it("With default arguement",function(){

       assert.equal(utobj.leftpad("7",3,"0"),"007","");

   });

   it("Passes required length less than string length",function(){

      assert.equal(utobj.leftpad("788",2,"6"),"788","");

   });

   it("Passes a string instead of padding character",function(){

      assert.equal(utobj.leftpad("776",10,"607"),undefined,"") ;
   });

   it("Passes negative length as required  length",function(){

      assert.equal(utobj.leftpad("gha",-9),"gha","");

   });

   it("Passes empty string ",function(){

      assert.equal(utobj.leftpad("",10),"**********","");
   });

   it("String and required length",function(){

      assert.equal(utobj.leftpad("ThisisTextoflength50",50),"******************************ThisisTextoflength50","");
   });

});

<|endoftext|>


<commit_before>function func1(opts) {
  //todo a todo
  //fixme a fixme
  //todo and another
  //fixme and another
    //fixme and another
  console.log(opts)
  console.log('hello')
  console.log('world')
  console.log('goodbye')
  console.log('world')
}

function func1(opts) {  //unused param on function declaration line
  console.log('hello'); //good line
  console.log('world')  //issue line

  while(true){
    var x = new function(unusedParam){
      console.log('inside a function')  //nested issue line
    }
  }
}
<commit_msg>asdas<commit_after>function func1(opts) {
  //todo a todo
  //fixme a fixme
  //todo and another
  //fixme and another
    //fixme and another
      //fixme and another
  console.log(opts)
  console.log('hello')
  console.log('world')
  console.log('goodbye')
  console.log('world')
}

function func1(opts) {  //unused param on function declaration line
  console.log('hello'); //good line
  console.log('world')  //issue line

  while(true){
    var x = new function(unusedParam){
      console.log('inside a function')  //nested issue line
    }
  }
}
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-17 11:21:30<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>/**********************************************************************
 Freeciv - Copyright (C) 2009 - Andreas Røsdal   andrearo@pvv.ntnu.no
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
***********************************************************************/

var C_S_INITIAL = 0;    /* Client boot, only used once on program start. */
var C_S_PREPARING = 1;  /* Main menu (disconnected) and connected in pregame. */
var C_S_RUNNING = 2;    /* Connected with game in progress. */
var C_S_OVER = 3;       /* Connected with game over. */

var civclient_state = C_S_INITIAL;

var endgame_player_info = [];

/**************************************************************************
 Sets the client state (initial, pre, running, over etc).
**************************************************************************/
function set_client_state(newstate)
{
  var connect_error = (C_S_PREPARING == civclient_state)
      && (C_S_PREPARING == newstate);
  var oldstate = civclient_state;

  if (civclient_state != newstate) {
    civclient_state = newstate;

    switch (civclient_state) {
    case C_S_RUNNING:
      chatbox_text = " ";
      $.unblockUI();
      show_new_game_message();

      set_client_page(PAGE_GAME);
      setup_window_size();

      if (observing) center_tile_mapcanvas(map_pos_to_tile(15,15));
      update_metamessage_on_gamestart();
      deduplicate_player_colors();

      break;
    case C_S_OVER:
      setTimeout(show_endgame_dialog, 500);
      break;
    case C_S_PREPARING:
      break;
    default:
      break;
    }
  }

}

function client_state()
{
  return civclient_state;
}

/**************************************************************************
  Return TRUE if the client can change the view; i.e. if the mapview is
  active.  This function should be called each time before allowing the
  user to do mapview actions.
**************************************************************************/
function can_client_change_view()
{
  return ((client.conn.playing != null || client_is_observer())
      && (C_S_RUNNING == client_state()
	      || C_S_OVER == client_state()));
}

/**************************************************************************
  Webclient does have observer support.
**************************************************************************/
function client_is_observer()
{
  return client.conn['observer'] || observing;
}

/**************************************************************************
  Intro message
**************************************************************************/
function show_new_game_message()
{

  if (observing) {
    /* do nothing. */

  } else if (is_small_screen()) {
    show_dialog_message("Welcome to Freeciv-web",
      "You lead a great civilization. Your task is to conquer the world!\n\
      Click on units for giving them orders, and drag units on the map to move them.\n\
      Good luck, and have a lot of fun!");

  } else  {
    if (is_touch_device()) {
      show_dialog_message("Welcome to Freeciv-web",
      "Welcome to Freeciv-web.  You lead a great civilization.  Your\n\
      task is to conquer the world!  You should start by\n\
      exploring the land around you with your explorer,\n\
      and using your settlers to find a good place to build\n\
      a city. Click on units for giving them orders. \n\
      To move your units around, carefully use your \n\
      finger to drag units to the place you want it to go.\n\
      Good luck, and have a lot of fun!");

    } else {
      show_dialog_message("Welcome to Freeciv-web",
      "Welcome to Freeciv-web.  You lead a great civilization.  Your\n\
      task is to conquer the world!  You should start by\n\
      exploring the land around you with your explorer,\n\
      and using your settlers to find a good place to build\n\
      a city. Right-click with the mouse on your units for a list of available \n\
      orders such as move, explore, build cities and attack.\n\
      Good luck, and have a lot of fun!");

    }

  }
}

/**************************************************************************
...
**************************************************************************/
function alert_war(player_no)
{
  var pplayer = players[player_no];
  show_dialog_message("War!", "You are now at war with the "
	+ nations[pplayer['nation']]['adjective']
    + " leader " + pplayer['name'] + "!");
}

/**************************************************************************
 Shows the endgame dialog
**************************************************************************/
function show_endgame_dialog()
{
  var title = "Final Report: The Greatest Civilizations in the world!";
  var message = "";
  for (var i = 0; i < endgame_player_info.length; i++) {
    var pplayer = players[endgame_player_info[i]['player_id']];
    var nation_adj = nations[pplayer['nation']]['adjective'];
    message += (i+1) + ": The " + nation_adj + " ruler " + pplayer['name'] + " scored " + endgame_player_info[i]['score'] + " points" + "
";
  }

  show_dialog_message(title, message);
}

/**************************************************************************

**************************************************************************/
function update_metamessage_on_gamestart()
{
  if (!observing && !metamessage_changed && client.conn.playing != null
      && client.conn.playing['pid'] == players[0]['pid']) {
    var pplayer = client.conn.playing;
    var metasuggest = username + " ruler of the " + nations[pplayer['nation']]['adjective'] + " empire.";

    var test_packet = {"type" : packet_chat_msg_req, "message" : "/metamessage " + metasuggest};
    var myJSONText = JSON.stringify(test_packet);
    send_request (myJSONText);
    setTimeout("chatbox_text = ' '; add_chatbox_text('');", 500);

  }
}

<commit_msg>Fix multiline strings.<commit_after>/**********************************************************************
 Freeciv - Copyright (C) 2009 - Andreas Røsdal   andrearo@pvv.ntnu.no
   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.
***********************************************************************/

var C_S_INITIAL = 0;    /* Client boot, only used once on program start. */
var C_S_PREPARING = 1;  /* Main menu (disconnected) and connected in pregame. */
var C_S_RUNNING = 2;    /* Connected with game in progress. */
var C_S_OVER = 3;       /* Connected with game over. */

var civclient_state = C_S_INITIAL;

var endgame_player_info = [];

/**************************************************************************
 Sets the client state (initial, pre, running, over etc).
**************************************************************************/
function set_client_state(newstate)
{
  var connect_error = (C_S_PREPARING == civclient_state)
      && (C_S_PREPARING == newstate);
  var oldstate = civclient_state;

  if (civclient_state != newstate) {
    civclient_state = newstate;

    switch (civclient_state) {
    case C_S_RUNNING:
      chatbox_text = " ";
      $.unblockUI();
      show_new_game_message();

      set_client_page(PAGE_GAME);
      setup_window_size();

      if (observing) center_tile_mapcanvas(map_pos_to_tile(15,15));
      update_metamessage_on_gamestart();
      deduplicate_player_colors();

      break;
    case C_S_OVER:
      setTimeout(show_endgame_dialog, 500);
      break;
    case C_S_PREPARING:
      break;
    default:
      break;
    }
  }

}

function client_state()
{
  return civclient_state;
}

/**************************************************************************
  Return TRUE if the client can change the view; i.e. if the mapview is
  active.  This function should be called each time before allowing the
  user to do mapview actions.
**************************************************************************/
function can_client_change_view()
{
  return ((client.conn.playing != null || client_is_observer())
      && (C_S_RUNNING == client_state()
	      || C_S_OVER == client_state()));
}

/**************************************************************************
  Webclient does have observer support.
**************************************************************************/
function client_is_observer()
{
  return client.conn['observer'] || observing;
}

/**************************************************************************
  Intro message
**************************************************************************/
function show_new_game_message()
{

  if (observing) {
    /* do nothing. */

  } else if (is_small_screen()) {
    show_dialog_message("Welcome to Freeciv-web",
      "You lead a great civilization. Your task is to conquer the world!\n" +
      "Click on units for giving them orders, and drag units on the map to move them.\n" +
      "Good luck, and have a lot of fun!");

  } else  {
    if (is_touch_device()) {
      show_dialog_message("Welcome to Freeciv-web",
      "Welcome to Freeciv-web.  You lead a great civilization.  Your\n" +
      "task is to conquer the world!  You should start by\n" +
      "exploring the land around you with your explorer,\n" +
      "and using your settlers to find a good place to build\n" +
      "a city. Click on units for giving them orders. \n" +
      "To move your units around, carefully use your \n" +
      "finger to drag units to the place you want it to go.\n" +
      "Good luck, and have a lot of fun!");

    } else {
      show_dialog_message("Welcome to Freeciv-web",
      "Welcome to Freeciv-web.  You lead a great civilization.  Your\n" +
      "task is to conquer the world!  You should start by\n" +
      "exploring the land around you with your explorer,\n" +
      "and using your settlers to find a good place to build\n" +
      "a city. Right-click with the mouse on your units for a list of available \n" +
      "orders such as move, explore, build cities and attack.\n" +
      "Good luck, and have a lot of fun!");

    }

  }
}

/**************************************************************************
...
**************************************************************************/
function alert_war(player_no)
{
  var pplayer = players[player_no];
  show_dialog_message("War!", "You are now at war with the "
	+ nations[pplayer['nation']]['adjective']
    + " leader " + pplayer['name'] + "!");
}

/**************************************************************************
 Shows the endgame dialog
**************************************************************************/
function show_endgame_dialog()
{
  var title = "Final Report: The Greatest Civilizations in the world!";
  var message = "";
  for (var i = 0; i < endgame_player_info.length; i++) {
    var pplayer = players[endgame_player_info[i]['player_id']];
    var nation_adj = nations[pplayer['nation']]['adjective'];
    message += (i+1) + ": The " + nation_adj + " ruler " + pplayer['name'] + " scored " + endgame_player_info[i]['score'] + " points" + "
";
  }

  show_dialog_message(title, message);
}

/**************************************************************************

**************************************************************************/
function update_metamessage_on_gamestart()
{
  if (!observing && !metamessage_changed && client.conn.playing != null
      && client.conn.playing['pid'] == players[0]['pid']) {
    var pplayer = client.conn.playing;
    var metasuggest = username + " ruler of the " + nations[pplayer['nation']]['adjective'] + " empire.";

    var test_packet = {"type" : packet_chat_msg_req, "message" : "/metamessage " + metasuggest};
    var myJSONText = JSON.stringify(test_packet);
    send_request (myJSONText);
    setTimeout("chatbox_text = ' '; add_chatbox_text('');", 500);

  }
}

<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-3 11:02:46<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>'use strict';

var http = require('http');
var assert = require('assert');
var requestStats = require('./index');

setTimeout(function () {
  throw new Error('Too long time have passed');
}, 2000);

var cbCount = 0;
var done = function () {
  cbCount++;
  return function () {
    if (!--cbCount) process.exit();
  };
};

assert.stats = function (stats) {
  assert(stats.ok);
  assert(stats.time >= 10);
  assert(stats.req.bytes > 0); // different headers will result in different results
  assert.equal(typeof stats.req.headers.connection, 'string');
  assert.equal(stats.req.method, 'PUT');
  assert.equal(stats.req.path, '/');
  assert(stats.res.bytes > 0); // different headers will result in different results
  assert.equal(typeof stats.res.headers.connection, 'string');
  assert.equal(stats.res.status, 200);
};

var _listen = function (server) {
  server.listen(0, function () {
    var options = {
      host: 'localhost',
      port: server.address().port,
      method: 'PUT'
    };

    var req = http.request(options, function (res) {
      res.resume();
      res.once('end', function () {
        server.close();
      });
    });

    req.end('42');
  });
};

var _respond = function (req, res) {
  req.on('end', function () {
    setTimeout(function () {
      res.end('Answer to the Ultimate Question of Life, The Universe, and Everything');
    }, 10);
  });
  req.resume();
};

var testNormalImpl = function () {
  var callback = done();
  _listen(http.createServer(function (req, res) {
    requestStats(req, res).once('stats', function (stats) {
      assert.stats(stats);
      callback();
    });
    _respond(req, res);
  }));
};

var testNSAImpl = function () {
  var callback = done();
  var server = http.createServer(_respond);
  requestStats(server).once('stats', function (stats) {
    assert.stats(stats);
    callback();
  });
  _listen(server);
};

var testMiddlewareImpl = function () {
  var callback1 = done();
  var callback2 = done();
  _listen(http.createServer(function (req, res) {
    requestStats.middleware()(req, res, callback1);
    requestStats().once('stats', function (stats) {
      assert.stats(stats);
      callback2();
    });
    _respond(req, res);
  }));
};

testNormalImpl();
testNSAImpl();
testMiddlewareImpl();
<commit_msg>Clean up tests<commit_after>'use strict';

var http = require('http');
var assert = require('assert');
var requestStats = require('./index');

setTimeout(function () {
  assert(false, 'Too long time have passed');
}, 2000);

var cbCount = 0;
var done = function () {
  cbCount++;
  return function () {
    if (!--cbCount) process.exit();
  };
};

assert.stats = function (stats) {
  assert(stats.ok);
  assert(stats.time >= 10);
  assert(stats.req.bytes > 0); // different headers will result in different results
  assert.equal(typeof stats.req.headers.connection, 'string');
  assert.equal(stats.req.method, 'PUT');
  assert.equal(stats.req.path, '/');
  assert(stats.res.bytes > 0); // different headers will result in different results
  assert.equal(typeof stats.res.headers.connection, 'string');
  assert.equal(stats.res.status, 200);
};

var _listen = function (server) {
  server.listen(0, function () {
    var options = {
      host: 'localhost',
      port: server.address().port,
      method: 'PUT'
    };

    var req = http.request(options, function (res) {
      res.resume();
      res.once('end', function () {
        server.close();
      });
    });

    req.end('42');
  });
};

var _respond = function (req, res) {
  req.on('end', function () {
    setTimeout(function () {
      res.end('Answer to the Ultimate Question of Life, The Universe, and Everything');
    }, 10);
  });
  req.resume();
};

(function () {
  var callback = done();
  _listen(http.createServer(function (req, res) {
    requestStats(req, res).once('stats', function (stats) {
      assert.stats(stats);
      callback();
    });
    _respond(req, res);
  }));
})();

(function () {
  var callback = done();
  var server = http.createServer(_respond);
  requestStats(server).once('stats', function (stats) {
    assert.stats(stats);
    callback();
  });
  _listen(server);
})();

(function () {
  var callback1 = done();
  var callback2 = done();
  _listen(http.createServer(function (req, res) {
    requestStats.middleware()(req, res, callback1);
    requestStats().once('stats', function (stats) {
      assert.stats(stats);
      callback2();
    });
    _respond(req, res);
  }));
})();
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-6-14 11:42:24<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>/*!
 * is-node-stream <https://github.com/tunnckoCore/is-node-stream>
 *
 * Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
 * Released under the MIT license.
 */

/* jshint asi:true */

'use strict'

var fs = require('fs')
var net = require('net')
var test = require('assertit')
var stream = require('stream')
var isNodeStream = require('./index')

test('isNodeStream() return `true` for streams only', function (done) {
  test.equal(isNodeStream(new stream.Stream()), true)
  test.equal(isNodeStream(new stream.Duplex()), true)
  test.equal(isNodeStream(new stream.Readable()), true)
  test.equal(isNodeStream(new stream.Writable()), true)
  test.equal(isNodeStream(new stream.Transform()), true)
  test.equal(isNodeStream(new stream.PassThrough()), true)
  test.equal(isNodeStream(new net.Socket()), true)
  test.equal(isNodeStream(fs.createReadStream('package.json')), true)
  done()
})

test('isNodeStream() return `false` otherwise', function (done) {
  var fakeOne = {
    pipe: function fake () {}
  }
  var fakeTwo = []
  fakeTwo.pipe = function fakePipe () {}

  test.equal(isNodeStream(undefined), false)
  test.equal(isNodeStream(null), false)
  test.equal(isNodeStream(1234), false)
  test.equal(isNodeStream('foo'), false)
  test.equal(isNodeStream({a: 'b'}), false)
  test.equal(isNodeStream(fakeOne), false)
  test.equal(isNodeStream(fakeTwo), false)
  done()
})

test('isNodeStream.readable() return `true` for readable streams', function (done) {
  test.equal(isNodeStream.readable(process.stdin), true)
  test.equal(isNodeStream.readable(new stream.Duplex()), true)
  test.equal(isNodeStream.readable(new stream.Readable()), true)
  test.equal(isNodeStream.readable(new stream.Transform()), true)
  test.equal(isNodeStream.readable(new stream.PassThrough()), true)
  test.equal(isNodeStream.readable(fs.createReadStream('package.json')), true)
  done()
})

test('isNodeStream.readable() return `false` otherwise', function (done) {
  test.equal(isNodeStream.readable(process.stdout), false)
  test.equal(isNodeStream.readable(new stream.Writable()), false)
  test.equal(isNodeStream.readable(fs.createWriteStream('foobar.log')), false)
  done()
})

test('isNodeStream.writable() return `true` for writable streams', function (done) {
  test.equal(isNodeStream.writable(process.stdout), true)
  test.equal(isNodeStream.writable(new stream.Duplex()), true)
  test.equal(isNodeStream.writable(new stream.Writable()), true)
  test.equal(isNodeStream.writable(new stream.Transform()), true)
  test.equal(isNodeStream.writable(new stream.PassThrough()), true)
  test.equal(isNodeStream.writable(fs.createWriteStream('foobar.log')), true)
  done()
})

test('isNodeStream.writable() return `false` otherwise', function (done) {
  test.equal(isNodeStream.writable(process.stdin), false)
  test.equal(isNodeStream.writable(new stream.Readable()), false)
  test.equal(isNodeStream.writable(fs.createReadStream('package.json')), false)
  done()
})

test('isNodeStream.duplex() return `true` for duplex streams', function (done) {
  test.equal(isNodeStream.duplex(new stream.Duplex()), true)
  test.equal(isNodeStream.duplex(new stream.Transform()), true)
  test.equal(isNodeStream.duplex(new stream.PassThrough()), true)
  done()
})

test('isNodeStream.duplex() return `false` otherwise', function (done) {
  test.equal(isNodeStream.duplex(new stream.Readable()), false)
  test.equal(isNodeStream.duplex(new stream.Writable()), false)
  done()
})
<commit_msg>fix "complexity" reported by codeclimate<commit_after>/*!
 * is-node-stream <https://github.com/tunnckoCore/is-node-stream>
 *
 * Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
 * Released under the MIT license.
 */

/* jshint asi:true */

'use strict'

var fs = require('fs')
var net = require('net')
var test = require('assertit')
var stream = require('stream')
var isNodeStream = require('./index')

test('isNodeStream() return `true` for streams only', function (done) {
  test.equal(isNodeStream(new stream.Stream()), true)
  test.equal(isNodeStream(new stream.Duplex()), true)
  test.equal(isNodeStream(new stream.Readable()), true)
  test.equal(isNodeStream(new stream.Writable()), true)
  test.equal(isNodeStream(new stream.Transform()), true)
  test.equal(isNodeStream(new stream.PassThrough()), true)
  test.equal(isNodeStream(new net.Socket()), true)
  test.equal(isNodeStream(fs.createReadStream('package.json')), true)
  done()
})

test('isNodeStream() return `false` otherwise', function (done) {
  var fakeOne = {
    pipe: function fake () {}
  }
  var fakeTwo = []
  fakeTwo.pipe = function fakePipe () {}

  test.equal(isNodeStream(undefined), false)
  test.equal(isNodeStream(null), false)
  test.equal(isNodeStream(1234), false)
  test.equal(isNodeStream('foo'), false)
  test.equal(isNodeStream({a: 'b'}), false)
  test.equal(isNodeStream(fakeOne), false)
  test.equal(isNodeStream(fakeTwo), false)
  done()
})

test('isNodeStream.readable() return `true` for readable streams', function (done) {
  test.equal(isNodeStream.readable(process.stdin), true)
  test.equal(isNodeStream.readable(new stream.Duplex()), true)
  test.equal(isNodeStream.readable(new stream.Readable()), true)
  test.equal(isNodeStream.readable(new stream.Transform()), true)
  test.equal(isNodeStream.readable(new stream.PassThrough()), true)
  test.equal(isNodeStream.readable(fs.createReadStream('package.json')), true)
  done()
})

test('isNodeStream.readable() return `false` otherwise', function (done) {
  test.equal(isNodeStream.readable(process.stdout), false)
  test.equal(isNodeStream.readable(new stream.Writable()), false)
  test.equal(isNodeStream.readable(fs.createWriteStream('foobar.log')), false)
  done()
})

test('isNodeStream.writable() returns `true` for writable streams', function (done) {
  test.equal(isNodeStream.writable(fs.createWriteStream('foobar.log')), true)
  test.equal(isNodeStream.writable(new stream.PassThrough()), true)
  test.equal(isNodeStream.writable(new stream.Transform()), true)
  test.equal(isNodeStream.writable(new stream.Writable()), true)
  test.equal(isNodeStream.writable(new stream.Duplex()), true)
  test.equal(isNodeStream.writable(process.stdout), true)
  done()
})

test('isNodeStream.writable() return `false` otherwise', function (done) {
  test.equal(isNodeStream.writable(fs.createReadStream('package.json')), false)
  test.equal(isNodeStream.writable(new stream.Readable()), false)
  test.equal(isNodeStream.writable(process.stdin), false)
  done()
})

test('isNodeStream.duplex() return `true` for duplex streams', function (done) {
  test.equal(isNodeStream.duplex(new stream.Duplex()), true)
  test.equal(isNodeStream.duplex(new stream.Transform()), true)
  test.equal(isNodeStream.duplex(new stream.PassThrough()), true)
  done()
})

test('isNodeStream.duplex() return `false` otherwise', function (done) {
  test.equal(isNodeStream.duplex(new stream.Readable()), false)
  test.equal(isNodeStream.duplex(new stream.Writable()), false)
  done()
})
<|endoftext|>


<commit_before>'use strict';

angular.module('mockedLatest', []).value('latestJSON', {
    query : {
        "id" : 101,
        "title" : "Why it's great to be a nerd",
        "author" : "Lauri Järvilehto"
    }
});
<commit_msg>Removed mockLatest.js<commit_after><|endoftext|>


<commit_before>

42 lines (36 sloc)  1.41 KB
'use strict';

function sum (x,y) {
  return [x + y, 'The sum of 4 and 7 is 11.'];
}

function testSum() { //eslint-disable-line
if (sum(4,7)[1] === 'The sum of 4 and 7 is 11.') {
console.log('%c TEST FOR sum() PASSES', 'color: green');
} else {
console.log('%c TEST FOR sum() FAILS', 'color: red');
}
}
testSum();

function multiply(x , y) {
  return [x * y, 'The product of 5 and 9 is 45.'];
}

function testMultiply() { //eslint-disable-line
  if (multiply(5,9)[1] === 'The product of 5 and 9 is 45.') {
    console.log('%c TEST FOR multiply() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR multiply() FAILS', 'color: red');
  }
}
testMultiply();

function sumAndMultiply (x , y , z) {
  return [x + y + z, x * y * z, '4 and 7 and 5 sum to 16.', 'The product of 4 and 7 and 5 is 140.'];
}

function testSumAndMultiply() { //eslint-disable-line
  if (sumAndMultiply(4, 7, 5)[2] === '4 and 7 and 5 sum to 16.' && sumAndMultiply(4, 7, 5)[3] === 'The product of 4 and 7 and 5 is 140.') {
    console.log('%c TEST FOR sumAndMultiply() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR sumAndMultiply() FAILS', 'color: red');
  }
}
testSumAndMultiply();

var testArray = [2 , 3, 4];

function sumArray(testArray) {
  return [sum, '2,3,4 was passed in as an array of numbers, and 9 is their sum.'];
}

function testSumArray() { //eslint-disable-line
  if (sumArray(testArray)[1] === '2,3,4 was passed in as an array of numbers, and 9 is their sum.') {
    console.log('%c TEST FOR sumArray() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR sumArray() FAILS', 'color: red');
  }
}
testSumArray();

function testMultiplyArray() { //eslint-disable-line
  if (multiplyArray(testArray)[1] === 'The numbers 2,3,4 have a product of 24.') {
    console.log('%c TEST FOR multiplyArray() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR multiplyArray() FAILS', 'color: red');
  }
}
<commit_msg>problem-05<commit_after>

42 lines (36 sloc)  1.41 KB
'use strict';

function sum (x,y) {
  return [x + y, 'The sum of 4 and 7 is 11.'];
}

function testSum() { //eslint-disable-line
if (sum(4,7)[1] === 'The sum of 4 and 7 is 11.') {
console.log('%c TEST FOR sum() PASSES', 'color: green');
} else {
console.log('%c TEST FOR sum() FAILS', 'color: red');
}
}
testSum();

function multiply(x , y) {
  return [x * y, 'The product of 5 and 9 is 45.'];
}

function testMultiply() { //eslint-disable-line
  if (multiply(5,9)[1] === 'The product of 5 and 9 is 45.') {
    console.log('%c TEST FOR multiply() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR multiply() FAILS', 'color: red');
  }
}
testMultiply();

function sumAndMultiply (x , y , z) {
  return [x + y + z, x * y * z, '4 and 7 and 5 sum to 16.', 'The product of 4 and 7 and 5 is 140.'];
}

function testSumAndMultiply() { //eslint-disable-line
  if (sumAndMultiply(4, 7, 5)[2] === '4 and 7 and 5 sum to 16.' && sumAndMultiply(4, 7, 5)[3] === 'The product of 4 and 7 and 5 is 140.') {
    console.log('%c TEST FOR sumAndMultiply() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR sumAndMultiply() FAILS', 'color: red');
  }
}
testSumAndMultiply();

var testArray = [2 , 3, 4];

function sumArray(testArray) {
  return [sum, '2,3,4 was passed in as an array of numbers, and 9 is their sum.'];
}

function testSumArray() { //eslint-disable-line
  if (sumArray(testArray)[1] === '2,3,4 was passed in as an array of numbers, and 9 is their sum.') {
    console.log('%c TEST FOR sumArray() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR sumArray() FAILS', 'color: red');
  }
}
testSumArray();

function multiplyArray(testArray) {
  return [testArray, 'The numbers 2,3,4 have a product of 24.'];
}

function testMultiplyArray() { //eslint-disable-line
  if (multiplyArray(testArray)[1] === 'The numbers 2,3,4 have a product of 24.') {
    console.log('%c TEST FOR multiplyArray() PASSES', 'color: green');
  } else {
    console.log('%c TEST FOR multiplyArray() FAILS', 'color: red');
  }
}
testMultiplyArray();
<|endoftext|>